Skip to main content

oa/plot/
figure.rs

1//! `oa::plot::Figure` — top-level container for a grid of `oa::plot::Axes`.
2//!
3//! Three terminal sinks:
4//! - `show()` — compose once and open the figure in the image viewer.
5//! - `save_to(engine, path)` — headless GPU render → image file (Experimental).
6//! - `render_on(engine)` — return the composition as an `oa::Image` (Experimental).
7//!
8//! Donor reference: `oa/ui/plot/figure.h`, `oa/ui/plot/figure.cpp`
9
10use super::axes::{Axes, AxesLayout, Scale, TickFormat, legend_row_rect, scale_value};
11pub use super::types::FigureConfig;
12use crate::ui::{TextLayoutConfig, Ui, UiGridConfig, UiStyle, types::PixelRect};
13use crate::{Color, Engine, Error, Image, Result, Texture};
14
15// ── Theme ─────────────────────────────────────────────────────────────────────
16
17/// Figure theme preset selector.
18///
19/// A theme resolves to a `UiStyle` preset; all figure colors come from that
20/// shared token set, so plots, widgets, and viewer chrome cannot diverge.
21///
22/// Donor: `oa::plot::Theme`.
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
24pub enum Theme {
25	#[default]
26	Dark = 0,
27	Light = 1,
28}
29
30impl Theme {
31	/// Resolve the shared UI style behind this figure theme.
32	pub fn ui_style(self) -> crate::ui::UiStyle {
33		match self {
34			Theme::Dark => crate::ui::UiStyle::default(),
35			Theme::Light => crate::ui::UiStyle::realm_light(),
36		}
37	}
38}
39
40// ── FigureConfig ──────────────────────────────────────────────────────────────
41
42impl Default for FigureConfig {
43	fn default() -> Self {
44		Self {
45			title: "oa::plot".to_owned(),
46			rows: 1,
47			cols: 1,
48			width: 800,
49			height: 600,
50			h_spacing: 20,
51			v_spacing: 24,
52			padding: 20,
53			theme: Theme::Dark,
54			background: Color::new(0.0, 0.0, 0.0, 0.0), // use theme
55		}
56	}
57}
58
59// ── Figure ────────────────────────────────────────────────────────────────────
60
61/// Pixel rect returned by [`Figure::cell_rect`].
62///
63/// Donor: `oa::plot::Figure::Rect`.
64#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
65pub struct CellRect {
66	pub x: i32,
67	pub y: i32,
68	pub w: i32,
69	pub h: i32,
70}
71
72/// Grid figure container.
73///
74/// Created without an Engine; the Engine is supplied only at sink time.
75pub struct Figure {
76	config: FigureConfig,
77	axes: Vec<Axes>,
78	fig_x_label: String,
79	fig_y_label: String,
80}
81
82impl Figure {
83	/// Construct a new figure with the given configuration.
84	pub fn new(mut config: FigureConfig) -> Self {
85		config.rows = config.rows.max(1);
86		config.cols = config.cols.max(1);
87		config.h_spacing = config.h_spacing.max(0);
88		config.v_spacing = config.v_spacing.max(0);
89		config.padding = config.padding.max(0);
90		let rows = config.rows as usize;
91		let cols = config.cols as usize;
92		let axes = vec![Axes::default(); rows * cols];
93		Self {
94			config,
95			axes,
96			fig_x_label: String::new(),
97			fig_y_label: String::new(),
98		}
99	}
100
101	/// Construct with default configuration.
102	pub fn default_config() -> Self {
103		Self::new(FigureConfig::default())
104	}
105
106	/// Access the (row, col) axes — both 0-indexed.
107	pub fn ax(&mut self, row: i32, col: i32) -> &mut Axes {
108		let r = row.clamp(0, self.config.rows - 1) as usize;
109		let c = col.clamp(0, self.config.cols - 1) as usize;
110		let cols = self.config.cols as usize;
111		&mut self.axes[r * cols + c]
112	}
113
114	/// Recorded axes in row-major cell order.
115	pub fn axes(&self) -> &[Axes] {
116		&self.axes
117	}
118
119	/// Set the figure-level title (also replaces the window title in `show`).
120	pub fn title(&mut self, text: &str) {
121		self.config.title = text.to_owned();
122	}
123
124	/// Set the figure-level horizontal axis label (rendered below the grid).
125	///
126	/// Donor: `oa::plot::Figure::xLabel`.
127	pub fn x_label(&mut self, text: &str) {
128		self.fig_x_label = text.to_owned();
129	}
130
131	/// Set the figure-level vertical axis label (rendered left of the grid).
132	///
133	/// Donor: `oa::plot::Figure::yLabel`.
134	pub fn y_label(&mut self, text: &str) {
135		self.fig_y_label = text.to_owned();
136	}
137
138	// ── Layout queries ────────────────────────────────────────────────────────
139
140	/// Return the figure configuration.
141	///
142	/// Donor: `oa::plot::Figure::config()`.
143	pub fn config(&self) -> &FigureConfig {
144		&self.config
145	}
146
147	/// Return the row count.
148	///
149	/// Donor: `oa::plot::Figure::rows()`.
150	pub fn rows(&self) -> i32 {
151		self.config.rows.max(1)
152	}
153
154	/// Return the column count.
155	///
156	/// Donor: `oa::plot::Figure::cols()`.
157	pub fn cols(&self) -> i32 {
158		self.config.cols.max(1)
159	}
160
161	/// Compute the pixel rect of the `(row, col)` cell inside a canvas of
162	/// `(w × h)` pixels, after all figure-level title/label bands are reserved.
163	///
164	/// Donor: `oa::plot::Figure::cellRect`.
165	pub fn cell_rect(&self, row: i32, col: i32, w: u32, h: u32) -> CellRect {
166		let layout = FigureLayout::compute(&self.config, &self.fig_x_label, &self.fig_y_label, w, h);
167		let r = row.clamp(0, self.config.rows - 1) as usize;
168		let c = col.clamp(0, self.config.cols - 1) as usize;
169		let ax_x = layout.pad + c as u32 * (layout.cell_w + layout.hs);
170		let ax_y = layout.top_band + r as u32 * (layout.cell_h + layout.vs);
171		CellRect {
172			x: ax_x as i32,
173			y: ax_y as i32,
174			w: layout.cell_w as i32,
175			h: layout.cell_h as i32,
176		}
177	}
178
179	// ── Sinks ─────────────────────────────────────────────────────────────────
180
181	pub fn save_to(&self, path: &str) -> Result<()> {
182		self.save_to_on(&Engine::current()?, path)
183	}
184
185	/// Headless GPU render → PNG/JPEG/WebP file.
186	///
187	/// GPU composition → file encode is Experimental.  The current
188	/// implementation produces a composed Texture and saves it.
189	pub fn save_to_on(&self, engine: &Engine, path: &str) -> Result<()> {
190		let texture = self.render_to_texture(engine)?;
191		crate::render::save_texture_file(&texture, std::path::Path::new(path), 90)
192	}
193
194	pub fn render(&self) -> Result<Image> {
195		self.render_on(&Engine::current()?)
196	}
197
198	/// Headless GPU render → `oa::Image` (normalized Float32 `[1, 4, H, W]`).
199	///
200	/// GPU→Image readback is Experimental.
201	pub fn render_on(&self, engine: &Engine) -> Result<Image> {
202		let texture = self.render_to_texture(engine)?;
203		let rgba8 = texture.read_rgba8()?;
204		let w = texture.width();
205		let h = texture.height();
206		// Convert packed RGBA8 to Float32 NCHW [1, 4, H, W].
207		let count = w * h;
208		let mut data = vec![0.0f32; 4 * count];
209		for i in 0..count {
210			data[i] = rgba8[i * 4] as f32 / 255.0;
211			data[count + i] = rgba8[i * 4 + 1] as f32 / 255.0;
212			data[count * 2 + i] = rgba8[i * 4 + 2] as f32 / 255.0;
213			data[count * 3 + i] = rgba8[i * 4 + 3] as f32 / 255.0;
214		}
215		let matrix = crate::Matrix::new_from_f32_on(engine, [1, 4, h, w], &data)?;
216		Image::new(matrix, crate::ImageLayout::Nchw, crate::ImageFormat::Rgba)
217	}
218
219	pub fn show(&self) -> Result<()> {
220		self.show_on(&Engine::current()?)
221	}
222
223	/// Compose the figure once and open it in the OA image viewer.
224	///
225	/// The window uses the image canvas with pan, zoom and fit controls.
226	/// The supplied engine must support desktop presentation. This call
227	/// returns when the viewer closes.
228	///
229	/// # Errors
230	///
231	/// Returns an error if composition fails or the viewer cannot open or
232	/// present the texture on the supplied engine.
233	pub fn show_on(&self, engine: &Engine) -> Result<()> {
234		let texture = self.render_to_texture(engine)?;
235		crate::viewer::Viewer::show_with_config(
236			engine,
237			&texture,
238			crate::viewer::ViewerConfig {
239				title: self.config.title.clone(),
240				width: self.config.width,
241				height: self.config.height,
242				..Default::default()
243			},
244		)
245	}
246
247	// ── Composition ──────────────────────────────────────────────────────────
248
249	/// Replay the complete figure into an already-open `Ui` GPU frame.
250	///
251	/// This is the public seam used by `ViewerLiveSource` implementations that
252	/// manage their own window/presenter lifecycle.  The configured aspect ratio
253	/// and all title/label bands remain stable on resize.
254	///
255	/// Donor: `oa::plot::Figure::renderFrame`.
256	pub fn render_frame(&self, w: u32, h: u32, ui: &mut Ui<'_>) -> Result<()> {
257		self.record_into(ui, PixelRect::new(0, 0, w, h))
258	}
259
260	/// Replay the figure inside `rect` of an already-open `Ui` GPU frame.
261	///
262	/// Same contract as [`Figure::render_frame`], but the figure layout is
263	/// computed for `rect`'s extent and translated to its origin, so the
264	/// figure can be embedded as a pane inside a composed surface (e.g. a
265	/// [`crate::viewer::Workspace`] leaf).
266	pub fn render_frame_at(&self, rect: PixelRect, ui: &mut Ui<'_>) -> Result<()> {
267		self.record_into(ui, rect)
268	}
269
270	/// Compose the figure into a packed RGBA8 Texture.
271	///
272	/// Commands are lowered through the UI GPU compositor and copied through
273	/// its explicit blocking headless readback boundary.
274	fn render_to_texture(&self, engine: &Engine) -> Result<Texture> {
275		let w = self.config.width;
276		let h = self.config.height;
277		let mut ui = Ui::init(engine, w, h)?;
278		ui.begin_frame(0.0);
279		let mut render_result = (|| -> Result<Vec<u8>> {
280			self.record_into(&mut ui, PixelRect::new(0, 0, w, h))?;
281			ui.end_frame();
282			ui.render_rgba8()
283		})();
284		if let Err(close_error) = ui.close()
285			&& render_result.is_ok()
286		{
287			render_result = Err(close_error);
288		}
289		let rgba = render_result?;
290		crate::render::texture_from_rgba8_on(engine, &rgba, w as usize, h as usize)
291	}
292
293	/// Replay retained artists into an already-open UI frame, translated to
294	/// `rect`'s origin and clipped to it.
295	fn record_into(&self, ui: &mut Ui<'_>, rect: PixelRect) -> Result<()> {
296		let style = self.config.theme.ui_style();
297		let bg = if self.config.background.a > 0.0 {
298			self.config.background
299		} else {
300			style.plot_background
301		};
302		let full = rect;
303		let text_color = style.text;
304		let subtext_color = style.text_secondary;
305		let label_cfg = TextLayoutConfig {
306			size: 11.0,
307			..Default::default()
308		};
309
310		// Compute the shared layout for this output size, then translate all
311		// absolute positions to the target rect's origin.
312		let mut layout = FigureLayout::compute(
313			&self.config,
314			&self.fig_x_label,
315			&self.fig_y_label,
316			rect.w,
317			rect.h,
318		);
319		layout.frame.x += rect.x;
320		layout.frame.y += rect.y;
321		layout.pad = (layout.pad as i64 + rect.x as i64).max(0) as u32;
322		layout.top_band = (layout.top_band as i64 + rect.y as i64).max(0) as u32;
323		if layout.frame.w == 0 || layout.frame.h == 0 {
324			return Ok(());
325		}
326		ui.rect_raw(layout.frame, bg, full, 0.0);
327
328		// Figure-level title.
329		if !self.config.title.is_empty() {
330			ui.text_at(
331				&self.config.title,
332				[
333					(layout.frame.x + layout.outer_pad as i32) as f32,
334					(layout.frame.y + layout.outer_pad as i32 + 22) as f32,
335				],
336				TextLayoutConfig {
337					size: 16.0,
338					..Default::default()
339				},
340				text_color,
341				full,
342			)?;
343		}
344
345		// Figure-level x label (below the grid).
346		if !self.fig_x_label.is_empty() {
347			let text_w = ui.measure_text(&self.fig_x_label, label_cfg)?;
348			let lx = layout.frame.x as f32 + (layout.frame.w as f32 - text_w) / 2.0;
349			let ly = (layout.frame.y + layout.frame.h as i32
350				- layout.outer_pad as i32
351				- (layout.bottom_band / 2) as i32) as f32;
352			ui.text_at(&self.fig_x_label, [lx, ly], label_cfg, subtext_color, full)?;
353		}
354
355		// Figure-level y label (left of the grid), bottom-to-top like
356		// matplotlib's rotated axis title.
357		if !self.fig_y_label.is_empty() {
358			let text_w = ui.measure_text(&self.fig_y_label, label_cfg)?;
359			let baseline_x =
360				(layout.frame.x + layout.outer_pad as i32 + layout.left_band as i32 - 4) as f32;
361			let pen_y = layout.frame.y as f32 + layout.frame.h as f32 / 2.0 + text_w / 2.0;
362			ui.text_vertical_at(
363				&self.fig_y_label,
364				[baseline_x, pen_y],
365				label_cfg,
366				subtext_color,
367				full,
368			)?;
369		}
370
371		let rows = layout.rows;
372		let cols = layout.cols;
373
374		for r in 0..rows {
375			for c in 0..cols {
376				let ax_x = layout.pad + c as u32 * (layout.cell_w + layout.hs);
377				let ax_y = layout.top_band + r as u32 * (layout.cell_h + layout.vs);
378				let cell = PixelRect {
379					x: ax_x as i32,
380					y: ax_y as i32,
381					w: layout.cell_w,
382					h: layout.cell_h,
383				};
384				let axes = &self.axes[r * cols + c];
385				let label_config = TextLayoutConfig {
386					size: 11.0,
387					..Default::default()
388				};
389				let subtext = style.text_secondary;
390				let axes_layout = axes.layout(cell);
391				let rect = axes_layout.plot;
392				let has_ticks = axes.has_ticks();
393
394				// Display-space limits; axis scales fold into every mapping.
395				let limits = axes.scaled_limits();
396				let x_scale = axes.cmds.x_scale;
397				let y_scale = axes.cmds.y_scale;
398
399				// Ticks and grid share one placement so labels and lines always
400				// agree.  Entries are `(fraction of axis range, label)`.
401				let x_ticks: Vec<(f32, String)> = if !has_ticks {
402					Vec::new()
403				} else if !axes.cmds.categories.is_empty() {
404					let slots = axes.cmds.categories.len() as f32;
405					axes
406						.cmds
407						.categories
408						.iter()
409						.enumerate()
410						.map(|(index, label)| ((index as f32 + 0.5) / slots, label.clone()))
411						.collect()
412				} else if let Some(values) = &axes.cmds.x_ticks {
413					explicit_ticks(
414						values,
415						&axes.cmds.x_tick_format,
416						limits.x_min,
417						limits.x_max,
418						x_scale,
419					)
420				} else {
421					axis_ticks(
422						limits.x_min,
423						limits.x_max,
424						x_scale,
425						(rect.w as usize / 68).clamp(2, 8),
426					)
427				};
428				let y_ticks = if !has_ticks {
429					Vec::new()
430				} else if let Some(values) = &axes.cmds.y_ticks {
431					explicit_ticks(
432						values,
433						&axes.cmds.y_tick_format,
434						limits.y_min,
435						limits.y_max,
436						y_scale,
437					)
438				} else {
439					axis_ticks(
440						limits.y_min,
441						limits.y_max,
442						y_scale,
443						(rect.h as usize / 48).clamp(2, 8),
444					)
445				};
446
447				record_axes_text(ui, axes, &axes_layout, &style, &x_ticks, &y_ticks)?;
448				record_plot_background(
449					ui,
450					rect,
451					axes,
452					self.config.theme,
453					&style,
454					&x_ticks,
455					&y_ticks,
456				);
457
458				// Imshow raster base.
459				if let Some(image) = &axes.cmds.imshow {
460					let destination = if has_ticks {
461						rect
462					} else {
463						fit_plot_image(rect, &image.texture)
464					};
465					ui.image_at(&image.texture, destination)?;
466				}
467
468				// Host-recorded dense heatmap — one upload per frame, lowered
469				// to a single `draw_heatmap` dispatch by the compositor.
470				let mut colorbar = None;
471				if let Some(heatmap) = &axes.cmds.heatmap {
472					let (v_min, v_max) = if heatmap.style.auto_scale {
473						let mut lo = f32::INFINITY;
474						let mut hi = f32::NEG_INFINITY;
475						for &v in &heatmap.values {
476							if v.is_finite() {
477								lo = lo.min(v);
478								hi = hi.max(v);
479							}
480						}
481						if lo.is_finite() && hi.is_finite() && lo < hi {
482							(lo, hi)
483						} else {
484							(0.0, 1.0)
485						}
486					} else {
487						(heatmap.style.v_min, heatmap.style.v_max)
488					};
489					let values = crate::Matrix::new_from_f32_on(
490						ui.engine(),
491						[heatmap.rows.max(1) as usize, heatmap.cols.max(1) as usize],
492						&heatmap.values,
493					)?;
494					ui.heatmap_matrix_at(
495						&values,
496						rect,
497						[v_min, v_max],
498						heatmap.style.colormap,
499						heatmap.style.show_grid,
500					)?;
501					if heatmap.style.colorbar {
502						colorbar = Some((v_min, v_max, heatmap.style.colormap));
503					}
504				}
505
506				// Device-resident heatmap — zero-copy dispatch.
507				if let Some(heatmap) = &axes.cmds.heatmap_matrix {
508					if heatmap.style.auto_scale {
509						return Err(Error::invalid_argument(
510							"heatmap_matrix requires an explicit v_min/v_max range",
511						));
512					}
513					ui.heatmap_matrix_at(
514						&heatmap.values,
515						rect,
516						[heatmap.style.v_min, heatmap.style.v_max],
517						heatmap.style.colormap,
518						heatmap.style.show_grid,
519					)?;
520					if heatmap.style.colorbar {
521						colorbar = Some((
522							heatmap.style.v_min,
523							heatmap.style.v_max,
524							heatmap.style.colormap,
525						));
526					}
527				}
528
529				record_plot_axes(ui, rect, axes, &style, &x_ticks, &y_ticks)?;
530
531				let palette = style.data_palette;
532
533				// Map data-space → pixel-space closures (scale-aware; a
534				// scale-dropped value maps to NaN and is skipped by callers).
535				let map_x = |value: f32| {
536					rect.x as f32
537						+ ((scale_value(value, x_scale) - limits.x_min) / (limits.x_max - limits.x_min))
538							.clamp(0.0, 1.0)
539							* rect.w.saturating_sub(1) as f32
540				};
541				let map_y = |value: f32| {
542					rect.y as f32
543						+ (1.0
544							- ((scale_value(value, y_scale) - limits.y_min) / (limits.y_max - limits.y_min))
545								.clamp(0.0, 1.0))
546							* rect.h.saturating_sub(1) as f32
547				};
548
549				// Replay artists in insertion order (donor ArtistRef contract).
550				let mut line_idx = 0usize;
551				let mut scatter_idx = 0usize;
552				let mut bar_idx = 0usize;
553				let mut matrix_idx = 0usize;
554				let mut stream_idx = 0usize;
555				let mut band_idx = 0usize;
556				let mut box_idx = 0usize;
557				// Palette index advances globally across all artist kinds,
558				// hidden artists included, so toggling keeps colors stable.
559				let mut palette_idx = 0usize;
560
561				for (artist_ord, kind) in axes.cmds.artists.iter().enumerate() {
562					let dim = axes.highlight.is_some_and(|h| h != artist_ord);
563					match kind {
564						super::axes::ArtistKind::Line => {
565							let Some(line) = axes.cmds.lines.get(line_idx) else {
566								continue;
567							};
568							line_idx += 1;
569							let color = if line.style.color.a == 0.0 {
570								let c = palette[palette_idx % palette.len()];
571								palette_idx += 1;
572								c
573							} else {
574								line.style.color
575							};
576							if line.style.hidden {
577								continue;
578							}
579							let color = dim_series(color, dim);
580							// One draw_plot_line dispatch per series;
581							// non-finite points break the polyline.
582							if line.style.step || x_scale != Scale::Linear || y_scale != Scale::Linear {
583								let (x, y) =
584									transformed_points(&line.x, &line.y, x_scale, y_scale, line.style.step);
585								ui.plot_xy_at(
586									&x,
587									&y,
588									rect,
589									limits.x_min,
590									limits.x_max,
591									limits.y_min,
592									limits.y_max,
593									color,
594									line.style.antialias_samples,
595									line.style.width,
596								)?;
597							} else {
598								ui.plot_xy_at(
599									&line.x,
600									&line.y,
601									rect,
602									limits.x_min,
603									limits.x_max,
604									limits.y_min,
605									limits.y_max,
606									color,
607									line.style.antialias_samples,
608									line.style.width,
609								)?;
610							}
611						}
612						super::axes::ArtistKind::Scatter => {
613							let Some(scatter) = axes.cmds.scatters.get(scatter_idx) else {
614								continue;
615							};
616							scatter_idx += 1;
617							let color = if scatter.style.color.a == 0.0 {
618								let c = palette[palette_idx % palette.len()];
619								palette_idx += 1;
620								c
621							} else {
622								scatter.style.color
623							};
624							if scatter.style.hidden {
625								continue;
626							}
627							let color = dim_series(color, dim);
628							for (&x, &y) in scatter.x.iter().zip(&scatter.y) {
629								let point = [map_x(x), map_y(y)];
630								if point[0].is_finite() && point[1].is_finite() {
631									ui.line_at(point, point, color, scatter.style.radius * 2.0, rect)?;
632								}
633							}
634						}
635						super::axes::ArtistKind::Bar => {
636							let Some(bars) = axes.cmds.bars.get(bar_idx) else {
637								continue;
638							};
639							bar_idx += 1;
640							let color = if bars.style.color.a == 0.0 {
641								let c = palette[palette_idx % palette.len()];
642								palette_idx += 1;
643								c
644							} else {
645								bars.style.color
646							};
647							if bars.style.hidden {
648								continue;
649							}
650							let color = dim_series(color, dim);
651							let slot = rect.w as f32 / bars.y.len().max(1) as f32;
652							let (group_index, group_size) = bars.group.unwrap_or((0, 1));
653							let sub_slot = slot / group_size.max(1) as f32;
654							let width = (sub_slot * (1.0 - bars.style.gap.clamp(0.0, 0.95))).max(1.0) as u32;
655							// A logarithmic y axis has no zero baseline; bars
656							// grow from the bottom of the data range instead.
657							let zero_base = if y_scale == Scale::Log10 {
658								(rect.y + rect.h.saturating_sub(1) as i32) as f32
659							} else {
660								map_y(0.0)
661							};
662							for (index, &value) in bars.y.iter().enumerate() {
663								let stack = bars.stack_base.as_ref().map_or(0.0, |bases| bases[index]);
664								let y0 = if bars.stack_base.is_some() {
665									map_y(stack)
666								} else {
667									zero_base
668								};
669								let y1 = map_y(stack + value);
670								if !y0.is_finite() || !y1.is_finite() {
671									continue;
672								}
673								let bar = PixelRect {
674									x: (rect.x as f32
675										+ index as f32 * slot
676										+ group_index as f32 * sub_slot
677										+ (sub_slot - width as f32) * 0.5) as i32,
678									y: y0.min(y1) as i32,
679									w: width,
680									h: (y0 - y1).abs().max(1.0) as u32,
681								};
682								ui.rect_raw(bar, color, rect, 0.0);
683							}
684						}
685						super::axes::ArtistKind::LineMatrix => {
686							let Some(series) = axes.cmds.line_matrices.get(matrix_idx) else {
687								continue;
688							};
689							matrix_idx += 1;
690							let color = if series.style.color.a == 0.0 {
691								let c = palette[palette_idx % palette.len()];
692								palette_idx += 1;
693								c
694							} else {
695								series.style.color
696							};
697							if series.style.hidden {
698								continue;
699							}
700							let color = dim_series(color, dim);
701							// Device data cannot be transformed host-side; a
702							// non-linear axis fails rather than drawing the
703							// series against mismatched limits.
704							if x_scale != Scale::Linear || y_scale != Scale::Linear {
705								return Err(Error::invalid_argument(
706									"plot_matrix series require linear axes",
707								));
708							}
709							if series.xy {
710								ui.plot_xy_matrix_at(
711									&series.values,
712									rect,
713									limits.x_min,
714									limits.x_max,
715									limits.y_min,
716									limits.y_max,
717									color,
718									series.style.antialias_samples,
719									series.style.width,
720								)?;
721							} else {
722								ui.plot_line_matrix_at(
723									&series.values,
724									rect,
725									limits.y_min,
726									limits.y_max,
727									color,
728									series.style.width,
729								)?;
730							}
731						}
732						super::axes::ArtistKind::Stream => {
733							let Some(stream) = axes.cmds.streams.get(stream_idx) else {
734								continue;
735							};
736							stream_idx += 1;
737							let color = if stream.style.color.a == 0.0 {
738								let c = palette[palette_idx % palette.len()];
739								palette_idx += 1;
740								c
741							} else {
742								stream.style.color
743							};
744							if stream.style.hidden || stream.len == 0 {
745								continue;
746							}
747							let color = dim_series(color, dim);
748							let y: Vec<f32> = stream.ordered().collect();
749							let x: Vec<f32> = (0..y.len()).map(|i| i as f32).collect();
750							let (x, y) = transformed_points(&x, &y, x_scale, y_scale, stream.style.step);
751							ui.plot_xy_at(
752								&x,
753								&y,
754								rect,
755								limits.x_min,
756								limits.x_max,
757								limits.y_min,
758								limits.y_max,
759								color,
760								stream.style.antialias_samples,
761								stream.style.width,
762							)?;
763						}
764						super::axes::ArtistKind::Band => {
765							let Some(band) = axes.cmds.bands.get(band_idx) else {
766								continue;
767							};
768							band_idx += 1;
769							let color = if band.style.color.a == 0.0 {
770								let c = palette[palette_idx % palette.len()];
771								palette_idx += 1;
772								c
773							} else {
774								band.style.color
775							};
776							if band.style.hidden {
777								continue;
778							}
779							let color = dim_series(color, dim);
780							// Band x positions are uniform sample indices; a
781							// non-linear x axis would need explicit positions
782							// the band path does not carry.
783							if x_scale != Scale::Linear {
784								return Err(Error::invalid_argument(
785									"band artists require a linear x axis",
786								));
787							}
788							let lo: Vec<f32> = band.y_lo.iter().map(|&v| scale_value(v, y_scale)).collect();
789							let hi: Vec<f32> = band.y_hi.iter().map(|&v| scale_value(v, y_scale)).collect();
790							ui.plot_band_at(&lo, &hi, rect, limits.y_min, limits.y_max, color)?;
791						}
792						super::axes::ArtistKind::BoxPlot => {
793							let Some(cmd) = axes.cmds.boxes.get(box_idx) else {
794								continue;
795							};
796							box_idx += 1;
797							let base = if cmd.style.color.a == 0.0 {
798								let c = palette[palette_idx % palette.len()];
799								palette_idx += 1;
800								c
801							} else {
802								cmd.style.color
803							};
804							if cmd.style.hidden {
805								continue;
806							}
807							let color = dim_series(base, dim);
808							let count = cmd.summaries.len().max(1) as f32;
809							let slot = rect.w as f32 / count;
810							let width = (slot * cmd.style.width.clamp(0.0, 0.95)).max(2.0);
811							for &(index, q1, median, q3, lo, hi) in &cmd.summaries {
812								let (y_q1, y_median, y_q3, y_lo, y_hi) =
813									(map_y(q1), map_y(median), map_y(q3), map_y(lo), map_y(hi));
814								if ![y_q1, y_median, y_q3, y_lo, y_hi]
815									.iter()
816									.all(|y| y.is_finite())
817								{
818									continue;
819								}
820								let cx = rect.x as f32 + index * slot + slot * 0.5;
821								let left = cx - width * 0.5;
822								let fill = PixelRect {
823									x: left as i32,
824									y: y_q3.min(y_q1) as i32,
825									w: width as u32,
826									h: (y_q1 - y_q3).abs().max(1.0) as u32,
827								};
828								ui.rect_raw(
829									fill,
830									Color::new(color.r, color.g, color.b, color.a * 0.4),
831									rect,
832									0.0,
833								);
834								ui.rect_outline_raw(fill, color, 1, rect);
835								// Whisker spine and caps.
836								ui.line_at([cx, y_lo], [cx, y_hi], color, 1.0, rect)?;
837								ui.line_at(
838									[cx - width * 0.25, y_lo],
839									[cx + width * 0.25, y_lo],
840									color,
841									1.0,
842									rect,
843								)?;
844								ui.line_at(
845									[cx - width * 0.25, y_hi],
846									[cx + width * 0.25, y_hi],
847									color,
848									1.0,
849									rect,
850								)?;
851								// Median.
852								ui.line_at([left, y_median], [left + width, y_median], color, 1.5, rect)?;
853							}
854						}
855					}
856				}
857
858				// Data-space annotations.
859				for note in &axes.cmds.annotations {
860					let point = [map_x(note.x), map_y(note.y)];
861					if point[0].is_finite() && point[1].is_finite() {
862						ui.text_at(
863							&note.text,
864							[point[0] + 3.0, point[1] - 3.0],
865							label_config,
866							text_color,
867							rect,
868						)?;
869					}
870				}
871
872				// Heatmap colorbar — a vertical value-ramp strip with
873				// min/mid/max labels in the reserved right band.
874				if let Some((v_min, v_max, colormap)) = colorbar
875					&& cell.x + cell.w as i32 - (rect.x + rect.w as i32) >= 20
876				{
877					const RAMP: usize = 32;
878					// Row 0 sits at the top of the strip and shows v_max.
879					let ramp: Vec<f32> = (0..RAMP)
880						.map(|index| v_max - (v_max - v_min) * index as f32 / (RAMP - 1).max(1) as f32)
881						.collect();
882					let strip = PixelRect::new(
883						rect.x + rect.w as i32 + 6,
884						rect.y + 8,
885						10,
886						rect.h.saturating_sub(16).max(1),
887					);
888					let values = crate::Matrix::new_from_f32_on(ui.engine(), [RAMP, 1], &ramp)?;
889					ui.heatmap_matrix_at(&values, strip, [v_min, v_max], colormap, false)?;
890					let step = ((v_max - v_min).abs() / 4.0).max(f32::EPSILON);
891					for (fraction, value) in [(0.0, v_max), (0.5, (v_min + v_max) * 0.5), (1.0, v_min)] {
892						ui.text_at(
893							&format_tick(value, step),
894							[
895								(strip.x + 14) as f32,
896								strip.y as f32 + 8.0 + fraction * strip.h.saturating_sub(16) as f32,
897							],
898							label_config,
899							subtext,
900							cell,
901						)?;
902					}
903				}
904
905				if axes.cmds.show_legend {
906					record_legend(ui, rect, axes, &style, label_config)?;
907				}
908			}
909		}
910		Ok(())
911	}
912}
913
914// ── Figure layout helper ──────────────────────────────────────────────────────
915
916/// Pre-computed layout bands and cell geometry for one output size.
917///
918/// Shared between `record_into` and `cell_rect` so the layout is always
919/// identical regardless of how the figure is consumed.
920struct FigureLayout {
921	frame: PixelRect,
922	rows: usize,
923	cols: usize,
924	outer_pad: u32,
925	pad: u32,
926	hs: u32,
927	vs: u32,
928	top_band: u32,
929	bottom_band: u32,
930	left_band: u32,
931	cell_w: u32,
932	cell_h: u32,
933}
934
935impl FigureLayout {
936	fn compute(config: &FigureConfig, x_label: &str, y_label: &str, w: u32, h: u32) -> Self {
937		let rows = config.rows.max(1) as usize;
938		let cols = config.cols.max(1) as usize;
939		let (frame_w, frame_h) = if w == 0 || h == 0 || config.width == 0 || config.height == 0 {
940			(0, 0)
941		} else {
942			let figure_aspect = config.width as f64 / config.height as f64;
943			let output_aspect = w as f64 / h as f64;
944			if output_aspect > figure_aspect {
945				((h as f64 * figure_aspect) as u32, h)
946			} else {
947				(w, (w as f64 / figure_aspect) as u32)
948			}
949		};
950		let frame = PixelRect::new(
951			(w.saturating_sub(frame_w) / 2) as i32,
952			(h.saturating_sub(frame_h) / 2) as i32,
953			frame_w,
954			frame_h,
955		);
956		let scale = if config.width == 0 {
957			0.0
958		} else {
959			frame_w as f64 / config.width as f64
960		};
961		let scaled = |value: i32| (value.max(0) as f64 * scale) as u32;
962		let outer_pad = scaled(config.padding);
963		let hs = scaled(config.h_spacing);
964		let vs = scaled(config.v_spacing);
965
966		// Reserve bands for figure-level labels.
967		let title_h = if config.title.is_empty() {
968			0
969		} else {
970			(38.0 * scale) as u32
971		};
972		let bottom_band = if x_label.is_empty() {
973			0
974		} else {
975			(30.0 * scale) as u32
976		};
977		let left_band = if y_label.is_empty() {
978			0
979		} else {
980			(30.0 * scale) as u32
981		};
982		let top_band = frame.y.max(0) as u32 + outer_pad + title_h;
983
984		let avail_w = frame_w
985			.saturating_sub(outer_pad.saturating_mul(2) + left_band.saturating_mul(2))
986			.saturating_sub(hs.saturating_mul((cols.saturating_sub(1)) as u32));
987		let cell_w = avail_w.checked_div(cols as u32).unwrap_or(1).max(1);
988
989		let avail_h = frame_h
990			.saturating_sub(outer_pad.saturating_mul(2) + title_h + bottom_band)
991			.saturating_sub(vs.saturating_mul((rows.saturating_sub(1)) as u32));
992		let cell_h = avail_h.checked_div(rows as u32).unwrap_or(1).max(1);
993
994		// Shift cell x-origin right when there's a y label band.
995		let pad = frame.x.max(0) as u32 + outer_pad + left_band;
996
997		Self {
998			frame,
999			rows,
1000			cols,
1001			outer_pad,
1002			pad,
1003			hs,
1004			vs,
1005			top_band,
1006			bottom_band,
1007			left_band,
1008			cell_w,
1009			cell_h,
1010		}
1011	}
1012}
1013
1014// ── Helpers ───────────────────────────────────────────────────────────────────
1015
1016fn fit_plot_image(rect: PixelRect, texture: &Texture) -> PixelRect {
1017	let width = texture.width() as f64;
1018	let height = texture.height() as f64;
1019	let scale = (f64::from(rect.w) / width).min(f64::from(rect.h) / height);
1020	let w = (width * scale).round().clamp(1.0, f64::from(rect.w)) as u32;
1021	let h = (height * scale).round().clamp(1.0, f64::from(rect.h)) as u32;
1022	PixelRect::new(
1023		rect.x + ((rect.w - w) / 2) as i32,
1024		rect.y + ((rect.h - h) / 2) as i32,
1025		w,
1026		h,
1027	)
1028}
1029
1030fn record_legend(
1031	ui: &mut Ui<'_>,
1032	rect: PixelRect,
1033	axes: &Axes,
1034	style: &UiStyle,
1035	config: TextLayoutConfig,
1036) -> Result<()> {
1037	let entries = axes.legend_entries(&style.data_palette);
1038	let visible_rows = entries
1039		.iter()
1040		.filter(|entry| entry.row != usize::MAX && legend_row_rect(rect, entry.row).is_non_empty())
1041		.count();
1042	if visible_rows == 0 {
1043		return Ok(());
1044	}
1045	let first = legend_row_rect(rect, 0);
1046	let panel = PixelRect::new(first.x, first.y, first.w, first.h * visible_rows as u32);
1047	let mut background = style.plot_background;
1048	background.a = 0.94;
1049	ui.rect_raw(panel, background, rect, 3.0);
1050
1051	for entry in entries.iter().filter(|entry| entry.row < visible_rows) {
1052		let row = legend_row_rect(rect, entry.row);
1053		let x = row.x as f32;
1054		let y = row.y as f32 + row.h as f32 / 2.0;
1055		let dim = entry.hidden || axes.highlight.is_some_and(|artist| artist != entry.artist);
1056		ui.line_at(
1057			[x + 5.0, y],
1058			[x + 18.0, y],
1059			dim_series(entry.color, dim),
1060			2.0,
1061			row,
1062		)?;
1063		ui.text_at(
1064			&entry.label,
1065			[x + 23.0, y + 4.0],
1066			config,
1067			dim_series(style.text_secondary, dim),
1068			row,
1069		)?;
1070	}
1071	Ok(())
1072}
1073
1074fn record_axes_text(
1075	ui: &mut Ui<'_>,
1076	axes: &Axes,
1077	layout: &AxesLayout,
1078	style: &UiStyle,
1079	x_ticks: &[(f32, String)],
1080	y_ticks: &[(f32, String)],
1081) -> Result<()> {
1082	let text = TextLayoutConfig {
1083		size: 12.0,
1084		..Default::default()
1085	};
1086	let ticks = TextLayoutConfig {
1087		size: 10.0,
1088		..Default::default()
1089	};
1090	let plot = layout.plot;
1091	let center_x = plot.x as f32 + plot.w as f32 / 2.0;
1092	let center_y = plot.y as f32 + plot.h as f32 / 2.0;
1093	let subtext = style.text_secondary;
1094	for (label, band, config, color) in [
1095		(
1096			&axes.cmds.title,
1097			layout.title,
1098			text,
1099			if axes.cmds.title_color.a > 0.0 {
1100				axes.cmds.title_color
1101			} else {
1102				style.text
1103			},
1104		),
1105		(
1106			&axes.cmds.caption,
1107			layout.caption,
1108			ticks,
1109			if axes.cmds.caption_color.a > 0.0 {
1110				axes.cmds.caption_color
1111			} else {
1112				subtext
1113			},
1114		),
1115		(&axes.cmds.x_label, layout.x_label, text, subtext),
1116	] {
1117		if !label.is_empty() && band.h >= 12 {
1118			let width = ui.measure_text(label, config)?;
1119			let baseline = band.y as f32 + band.h as f32 / 2.0 + 4.0;
1120			ui.text_at(
1121				label,
1122				[center_x - width / 2.0, baseline],
1123				config,
1124				color,
1125				band,
1126			)?;
1127		}
1128	}
1129	if !axes.cmds.y_label.is_empty() && layout.y_label.w >= 12 {
1130		let width = ui.measure_text(&axes.cmds.y_label, text)?;
1131		let x = layout.y_label.x as f32 + layout.y_label.w as f32 / 2.0 + 4.0;
1132		ui.text_vertical_at(
1133			&axes.cmds.y_label,
1134			[x, center_y + width / 2.0],
1135			text,
1136			subtext,
1137			layout.y_label,
1138		)?;
1139	}
1140	// Tick values are centered below X and right-aligned beside Y. Permit
1141	// endpoint labels to extend past the viewport into their own gutters.
1142	if layout.x_ticks.h >= 12 {
1143		let band = layout.x_ticks;
1144		let left = band.x as f32;
1145		let right = left + band.w as f32;
1146		let mut labels = Vec::with_capacity(x_ticks.len());
1147		for (fraction, label) in x_ticks {
1148			let width = ui.measure_text(label, ticks)?;
1149			let center = plot.x as f32 + 0.5 + fraction * plot.w.saturating_sub(1) as f32;
1150			let x = (center - width / 2.0).clamp(left, (right - width).max(left));
1151			labels.push((x, width, label));
1152		}
1153		labels.sort_by(|a, b| a.0.total_cmp(&b.0));
1154		let mut end = left - 4.0;
1155		for (x, width, label) in labels {
1156			if x >= end + 4.0 {
1157				ui.text_at(label, [x, band.y as f32 + 13.0], ticks, subtext, band)?;
1158				end = x + width;
1159			}
1160		}
1161	}
1162	if layout.y_ticks.w >= 12 {
1163		let band = layout.y_ticks;
1164		let right = (plot.x - 6) as f32;
1165		let mut previous = f32::INFINITY;
1166		for (fraction, label) in y_ticks {
1167			let y = plot.y as f32 + (1.0 - fraction) * plot.h.saturating_sub(1) as f32 + 4.0;
1168			if (previous - y).abs() >= 12.0 {
1169				let width = ui.measure_text(label, ticks)?;
1170				ui.text_at(label, [right - width, y], ticks, subtext, band)?;
1171				previous = y;
1172			}
1173		}
1174	}
1175	Ok(())
1176}
1177
1178fn record_plot_background(
1179	ui: &mut Ui<'_>,
1180	rect: PixelRect,
1181	axes: &Axes,
1182	theme: Theme,
1183	style: &UiStyle,
1184	x_ticks: &[(f32, String)],
1185	y_ticks: &[(f32, String)],
1186) {
1187	if theme == Theme::Light {
1188		ui.rect_raw(rect, style.plot_surface, rect, 0.0);
1189		return;
1190	}
1191
1192	// Reuse the donor canvas grid for a neutral gradient and fine subdivisions.
1193	// Add subdivisions only to regular, automatic linear ticks. Major lines
1194	// are recorded separately so custom and nonlinear ticks stay exact.
1195	let surface = style.plot_surface;
1196	let mut grid = UiGridConfig {
1197		background_top: Color::new(surface.r + 0.031, surface.g + 0.031, surface.b + 0.031, 1.0),
1198		background_bottom: Color::new(surface.r - 0.020, surface.g - 0.020, surface.b - 0.020, 1.0),
1199		draw_axes: false,
1200		draw_grid: false,
1201		..Default::default()
1202	};
1203	if axes.cmds.show_grid
1204		&& axes.cmds.categories.is_empty()
1205		&& axes.cmds.x_ticks.is_none()
1206		&& axes.cmds.y_ticks.is_none()
1207		&& axes.cmds.x_scale == Scale::Linear
1208		&& axes.cmds.y_scale == Scale::Linear
1209		&& let [x0, x1, ..] = x_ticks
1210		&& let [y0, y1, ..] = y_ticks
1211	{
1212		let w = rect.w.saturating_sub(1) as f32;
1213		let h = rect.h.saturating_sub(1) as f32;
1214		let dx = (x1.0 - x0.0) * w / 10.0;
1215		let dy = (y1.0 - y0.0) * h / 10.0;
1216		if dx >= 4.0 && dy >= 4.0 {
1217			grid.origin = [
1218				rect.x as f32 + 0.5 + x0.0 * w,
1219				rect.y as f32 + 0.5 + (1.0 - y0.0) * h,
1220			];
1221			grid.minor_spacing = [dx, dy];
1222			grid.major_color = Color::new(1.0, 1.0, 1.0, 0.01);
1223			grid.super_major_color = grid.major_color;
1224			grid.draw_grid = true;
1225		}
1226	}
1227	ui.grid(rect, grid);
1228}
1229
1230fn record_plot_axes(
1231	ui: &mut Ui<'_>,
1232	rect: PixelRect,
1233	axes: &Axes,
1234	style: &UiStyle,
1235	x_ticks: &[(f32, String)],
1236	y_ticks: &[(f32, String)],
1237) -> Result<()> {
1238	let x = rect.x as f32 + 0.5;
1239	let y = rect.y as f32 + 0.5;
1240	let w = rect.w.saturating_sub(1) as f32;
1241	let h = rect.h.saturating_sub(1) as f32;
1242	if axes.cmds.show_grid {
1243		for &(fraction, _) in x_ticks {
1244			if fraction > f32::EPSILON && fraction < 1.0 - f32::EPSILON {
1245				let tick = x + fraction * w;
1246				ui.line_at([tick, y], [tick, y + h], style.plot_grid, 1.0, rect)?;
1247			}
1248		}
1249		for &(fraction, _) in y_ticks {
1250			if fraction > f32::EPSILON && fraction < 1.0 - f32::EPSILON {
1251				let tick = y + (1.0 - fraction) * h;
1252				ui.line_at([x, tick], [x + w, tick], style.plot_grid, 1.0, rect)?;
1253			}
1254		}
1255	}
1256	if let Some(border) = axes.cmds.border_color {
1257		ui.rect_outline_raw(rect, border, 1, rect);
1258	} else if axes.has_ticks() {
1259		let bottom = rect.y + rect.h.saturating_sub(1) as i32;
1260		ui.rect_raw(
1261			PixelRect::new(rect.x, rect.y, 1, rect.h),
1262			style.plot_border,
1263			rect,
1264			0.0,
1265		);
1266		ui.rect_raw(
1267			PixelRect::new(rect.x, bottom, rect.w, 1),
1268			style.plot_border,
1269			rect,
1270			0.0,
1271		);
1272	}
1273	Ok(())
1274}
1275
1276/// Emphasis factor for legend-hover highlighting — the hovered series keeps
1277/// full alpha; the rest fade to a quarter.
1278fn dim_series(color: Color, dim: bool) -> Color {
1279	if dim {
1280		Color::new(color.r, color.g, color.b, color.a * 0.25)
1281	} else {
1282		color
1283	}
1284}
1285
1286/// Tick positions for one axis as `(fraction of range, label)` pairs.
1287///
1288/// Linear axes use nice-number ticks; a `Log10` axis places ticks on whole
1289/// decades with data-space labels (`1e3` at display position `log10(1e3)`),
1290/// falling back to linear ticks when the range covers less than a decade.
1291fn axis_ticks(min: f32, max: f32, scale: Scale, target: usize) -> Vec<(f32, String)> {
1292	if !min.is_finite() || !max.is_finite() || min >= max {
1293		return Vec::new();
1294	}
1295	let span = (max - min).max(f32::EPSILON);
1296	let linear = |min: f32, max: f32| {
1297		let ticks = nice_ticks(min, max, target);
1298		let step = tick_step(&ticks);
1299		ticks
1300			.iter()
1301			.map(|&value| ((value - min) / span, format_tick(value, step)))
1302			.collect()
1303	};
1304	match scale {
1305		Scale::Linear => linear(min, max),
1306		Scale::Log10 => {
1307			let first = min.ceil() as i32;
1308			let last = max.floor() as i32;
1309			if last - first >= 1 {
1310				(first..=last)
1311					.map(|k| ((k as f32 - min) / span, format!("1e{k}")))
1312					.collect()
1313			} else {
1314				linear(min, max)
1315			}
1316		}
1317		Scale::Symlog => {
1318			let mut ticks: Vec<(f32, String)> = Vec::new();
1319			if min <= 0.0 && max >= 0.0 {
1320				ticks.push((-min / span, "0".to_owned()));
1321			}
1322			for sign in [-1f32, 1f32] {
1323				for k in 0..32 {
1324					// Display position `±linthresh·(1+k)` is data `±10^k`.
1325					let pos = sign * super::axes::SYMLOG_LINTHRESH * (1.0 + k as f32);
1326					if pos > max {
1327						break;
1328					}
1329					if pos >= min {
1330						let negative = if sign < 0.0 { "-" } else { "" };
1331						ticks.push(((pos - min) / span, format!("{negative}1e{k}")));
1332					}
1333				}
1334			}
1335			if ticks.len() <= 1 {
1336				linear(min, max)
1337			} else {
1338				ticks.sort_by(|a, b| a.0.total_cmp(&b.0));
1339				ticks
1340			}
1341		}
1342	}
1343}
1344
1345/// Format caller-supplied data-space tick positions as `(fraction, label)`.
1346///
1347/// Positions map through the axis scale into display space; scale-dropped
1348/// and out-of-range values are skipped. Labels show the data-space value.
1349fn explicit_ticks(
1350	values: &[f32],
1351	format: &TickFormat,
1352	min: f32,
1353	max: f32,
1354	scale: Scale,
1355) -> Vec<(f32, String)> {
1356	let span = (max - min).max(f32::EPSILON);
1357	let step = values
1358		.windows(2)
1359		.map(|pair| (pair[1] - pair[0]).abs())
1360		.fold(f32::INFINITY, f32::min)
1361		.max(f32::EPSILON);
1362	let step = if step.is_finite() { step } else { 1.0 };
1363	values
1364		.iter()
1365		.enumerate()
1366		.filter_map(|(index, &value)| {
1367			let position = scale_value(value, scale);
1368			if !position.is_finite() || position < min || position > max {
1369				return None;
1370			}
1371			let label = match format {
1372				TickFormat::Labels(labels) => labels.get(index)?.clone(),
1373				TickFormat::Decimals(d) => format!("{value:.d$}"),
1374				TickFormat::Scientific => format!("{value:.1e}"),
1375				TickFormat::Auto => format_tick(value, step),
1376			};
1377			Some(((position - min) / span, label))
1378		})
1379		.collect()
1380}
1381
1382/// Transform a series' raw samples into display space.
1383///
1384/// `step` expands the polyline into step-post vertices — each y value holds
1385/// until the next x — and the axis scales map every sample afterward;
1386/// scale-dropped values become `NaN` and break the polyline in the shader.
1387fn transformed_points(
1388	x: &[f32],
1389	y: &[f32],
1390	x_scale: Scale,
1391	y_scale: Scale,
1392	step: bool,
1393) -> (Vec<f32>, Vec<f32>) {
1394	let count = if step { x.len() * 2 - 1 } else { x.len() }.max(x.len());
1395	let mut tx = Vec::with_capacity(count);
1396	let mut ty = Vec::with_capacity(count);
1397	if step {
1398		for index in 0..x.len() {
1399			tx.push(x[index]);
1400			ty.push(y[index]);
1401			if index + 1 < x.len() {
1402				tx.push(x[index + 1]);
1403				ty.push(y[index]);
1404			}
1405		}
1406	} else {
1407		tx.extend_from_slice(x);
1408		ty.extend_from_slice(y);
1409	}
1410	for value in &mut tx {
1411		*value = scale_value(*value, x_scale);
1412	}
1413	for value in &mut ty {
1414		*value = scale_value(*value, y_scale);
1415	}
1416	(tx, ty)
1417}
1418
1419/// Nice-number tick values spanning `[min, max]` at roughly `target` count,
1420/// using the 1/2/5 step family.
1421fn nice_ticks(min: f32, max: f32, target: usize) -> Vec<f32> {
1422	if !min.is_finite() || !max.is_finite() || min >= max || target == 0 {
1423		return Vec::new();
1424	}
1425	let range = f64::from(max - min);
1426	let raw = range / target as f64;
1427	let magnitude = 10f64.powf(raw.log10().floor());
1428	let normalized = raw / magnitude;
1429	let step = if normalized < 1.5 {
1430		magnitude
1431	} else if normalized < 3.0 {
1432		2.0 * magnitude
1433	} else if normalized < 7.0 {
1434		5.0 * magnitude
1435	} else {
1436		10.0 * magnitude
1437	};
1438	let start = (f64::from(min) / step).ceil();
1439	let end = (f64::from(max) / step).floor();
1440	let count = (end - start).max(0.0) as usize + 1;
1441	if end < start || count > 64 {
1442		return vec![min, max];
1443	}
1444	(0..count)
1445		.map(|index| ((start + index as f64) * step) as f32)
1446		.collect()
1447}
1448
1449/// Spacing between consecutive nice ticks, used to pick label precision.
1450fn tick_step(ticks: &[f32]) -> f32 {
1451	ticks
1452		.windows(2)
1453		.map(|pair| (pair[1] - pair[0]).abs())
1454		.next()
1455		.unwrap_or(1.0)
1456		.max(f32::EPSILON)
1457}
1458
1459/// Format a tick value with the precision implied by the tick step.
1460///
1461/// Nice steps are 1/2/5 × 10^k, so `max(0, -floor(log10(step)))` decimals
1462/// always render the step exactly.
1463fn format_tick(value: f32, step: f32) -> String {
1464	if value.abs() >= 1.0e6 || (value != 0.0 && value.abs() < 1.0e-4) {
1465		return format!("{value:.1e}");
1466	}
1467	let decimals = (-f64::from(step).abs().log10().floor()).max(0.0) as usize;
1468	format!("{value:.decimals$}")
1469}