1use crate::chart::{Chart, Data, Entry, Mark, YRange};
4use crate::color::Rgba;
5use crate::scale::{LinearScale, format_value, nice_ticks, time_ticks};
6use crate::series::{Candle, Point, aggregate_candles, downsample_min_max};
7use crate::time::Timestamp;
8
9#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct Pos {
12 pub x: f32,
14 pub y: f32,
16}
17
18impl Pos {
19 pub const fn new(x: f32, y: f32) -> Pos {
21 Pos { x, y }
22 }
23}
24
25#[derive(Clone, Copy, Debug, PartialEq)]
27pub struct Rect {
28 pub x: f32,
30 pub y: f32,
32 pub w: f32,
34 pub h: f32,
36}
37
38impl Rect {
39 pub const fn new(x: f32, y: f32, w: f32, h: f32) -> Rect {
41 Rect { x, y, w, h }
42 }
43
44 pub fn right(&self) -> f32 {
46 self.x + self.w
47 }
48
49 pub fn bottom(&self) -> f32 {
51 self.y + self.h
52 }
53
54 pub fn contains(&self, p: Pos) -> bool {
56 p.x >= self.x && p.x <= self.right() && p.y >= self.y && p.y <= self.bottom()
57 }
58}
59
60#[derive(Clone, Copy, Debug, PartialEq)]
62pub struct Size {
63 pub width: f32,
65 pub height: f32,
67}
68
69impl Size {
70 pub const fn new(width: f32, height: f32) -> Size {
72 Size { width, height }
73 }
74}
75
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum Align {
79 Start,
81 Center,
83 End,
85}
86
87#[derive(Clone, Debug, PartialEq)]
89pub enum Primitive {
90 Rect {
92 rect: Rect,
94 color: Rgba,
96 },
97 Line {
99 from: Pos,
101 to: Pos,
103 color: Rgba,
105 width: f32,
107 dashed: bool,
109 },
110 Polyline {
112 points: Vec<Pos>,
114 color: Rgba,
116 width: f32,
118 },
119 Area {
121 points: Vec<Pos>,
123 baseline: f32,
125 color: Rgba,
127 },
128 Text {
130 pos: Pos,
132 text: String,
134 color: Rgba,
136 h_align: Align,
138 v_align: Align,
140 },
141}
142
143#[derive(Clone, Debug, PartialEq)]
145pub struct Layer {
146 pub clip: Option<Rect>,
148 pub primitives: Vec<Primitive>,
150}
151
152#[derive(Clone, Copy, Debug, PartialEq)]
154pub struct PaneLayout {
155 pub rect: Rect,
157 pub y: LinearScale,
159}
160
161#[derive(Clone, Copy, Debug, PartialEq)]
164pub struct Metrics {
165 pub char_width: f32,
167 pub line_height: f32,
169 pub padding: f32,
171 pub min_stroke: f32,
173}
174
175impl Metrics {
176 pub const PIXELS: Metrics = Metrics { char_width: 7.0, line_height: 16.0, padding: 4.0, min_stroke: 1.0 };
178}
179
180impl Default for Metrics {
181 fn default() -> Self {
182 Metrics::PIXELS
183 }
184}
185
186#[derive(Clone, Debug, PartialEq)]
188pub struct Scene {
189 pub size: Size,
191 pub background: Rgba,
193 pub plot: Rect,
195 pub x: LinearScale,
197 pub panes: Vec<PaneLayout>,
199 pub layers: Vec<Layer>,
201}
202
203impl Scene {
204 pub fn primitives(&self) -> impl Iterator<Item = &Primitive> {
206 self.layers.iter().flat_map(|l| l.primitives.iter())
207 }
208
209 pub fn time_at(&self, x: f32) -> Timestamp {
211 self.x.invert(x as f64).round() as Timestamp
212 }
213
214 pub fn value_at(&self, p: Pos) -> Option<(usize, f64)> {
216 self.panes.iter().enumerate().find(|(_, pl)| pl.rect.contains(p)).map(|(i, pl)| (i, pl.y.invert(p.y as f64)))
217 }
218}
219
220struct PaneRange {
221 lo: f64,
222 hi: f64,
223 ticks: Vec<f64>,
224 step: f64,
225}
226
227impl Chart {
228 pub fn layout(&self, size: Size, metrics: &Metrics) -> Scene {
230 let m = metrics;
231 let theme = &self.theme;
232 let (start, end) = (self.viewport.start(), self.viewport.end());
233 let mut scene = Scene {
234 size,
235 background: theme.background,
236 plot: Rect::new(0.0, 0.0, 0.0, 0.0),
237 x: self.viewport.scale(0.0, 0.0),
238 panes: Vec::new(),
239 layers: Vec::new(),
240 };
241 let x_axis_h = m.line_height + m.padding;
242 if size.width < m.char_width * 12.0 || size.height < x_axis_h + m.line_height * 2.0 {
243 return scene;
244 }
245
246 let gap = (m.line_height / 2.0).max(m.min_stroke);
248 let n = self.panes.len();
249 let avail = size.height - x_axis_h - m.padding - gap * (n.saturating_sub(1)) as f32;
250 let total_w: f32 = self.panes.iter().map(|p| p.weight.max(0.0)).sum::<f32>().max(f32::EPSILON);
251 let mut heights: Vec<f32> = self.panes.iter().map(|p| avail * p.weight.max(0.0) / total_w).collect();
252 if heights.iter().all(|h| *h <= 0.0) {
253 heights = vec![avail / n as f32; n];
254 }
255
256 let ranges: Vec<PaneRange> = self
258 .panes
259 .iter()
260 .enumerate()
261 .map(|(i, pane)| {
262 let entries = self.entries.iter().filter(|e| e.visible && e.pane.0 == i);
263 let extent = crate::series::fold_extent(entries.filter_map(|e| self.entry_extent(e, start, end)));
264 let (mut lo, mut hi) = match (pane.y_range, extent) {
265 (YRange::Fixed(a, b), _) => (a.min(b), a.max(b)),
266 (_, Some((a, b))) => (a, b),
267 (_, None) => (0.0, 1.0),
268 };
269 if matches!(pane.y_range, YRange::AutoFromZero) {
270 lo = lo.min(0.0);
271 hi = hi.max(0.0);
272 }
273 if hi - lo <= f64::EPSILON * hi.abs().max(1.0) {
274 let pad = if lo == 0.0 { 1.0 } else { lo.abs() * 0.01 };
275 lo -= pad;
276 hi += pad;
277 }
278 if !matches!(pane.y_range, YRange::Fixed(..)) {
279 let pad = (hi - lo) * 0.08;
280 if !(matches!(pane.y_range, YRange::AutoFromZero) && lo >= 0.0) {
281 lo -= pad;
282 }
283 hi += pad;
284 }
285 let target = ((heights[i] / (m.line_height * 2.5)).floor() as usize).max(2);
286 let (ticks, step) = nice_ticks(lo, hi, target);
287 PaneRange { lo, hi, ticks, step }
288 })
289 .collect();
290
291 let mut label_chars = 4;
292 for r in &ranges {
293 for t in &r.ticks {
294 label_chars = label_chars.max(format_value(*t, r.step).chars().count());
295 }
296 }
297 for e in self.entries.iter().filter(|e| e.visible && e.style.show_last_value) {
298 if let Some(v) = self.last_value(e) {
299 label_chars = label_chars.max(format_value(v, ranges[e.pane.0].step / 10.0).chars().count());
300 }
301 }
302 let axis_w = label_chars as f32 * m.char_width + m.padding * 3.0;
303 let plot = Rect::new(m.padding, m.padding, (size.width - axis_w - m.padding).max(1.0), avail + gap * (n.saturating_sub(1)) as f32);
304 scene.plot = plot;
305 scene.x = self.viewport.scale(plot.x as f64, plot.right() as f64);
306
307 let mut y = plot.y;
308 for (i, r) in ranges.iter().enumerate() {
309 let rect = Rect::new(plot.x, y, plot.w, heights[i].max(0.0));
310 scene.panes.push(PaneLayout { rect, y: LinearScale::new((r.lo, r.hi), (rect.bottom() as f64, rect.y as f64)) });
311 y += heights[i] + gap;
312 }
313
314 let x_ticks = time_ticks(start, end, ((plot.w / (m.char_width * 10.0)).floor() as usize).max(2), self.tz);
316 let mut grid = Vec::new();
317 let mut labels = Vec::new();
318 let stroke = m.min_stroke;
319 for (pl, r) in scene.panes.iter().zip(&ranges) {
320 for t in &r.ticks {
321 let py = pl.y.map(*t) as f32;
322 grid.push(Primitive::Line {
323 from: Pos::new(pl.rect.x, py),
324 to: Pos::new(pl.rect.right(), py),
325 color: theme.grid,
326 width: stroke,
327 dashed: true,
328 });
329 labels.push(Primitive::Text {
330 pos: Pos::new(plot.right() + m.padding * 2.0, py),
331 text: format_value(*t, r.step),
332 color: theme.text,
333 h_align: Align::Start,
334 v_align: Align::Center,
335 });
336 }
337 for tick in &x_ticks {
338 let px = scene.x.map(tick.time as f64) as f32;
339 grid.push(Primitive::Line {
340 from: Pos::new(px, pl.rect.y),
341 to: Pos::new(px, pl.rect.bottom()),
342 color: theme.grid,
343 width: stroke,
344 dashed: true,
345 });
346 }
347 grid.push(Primitive::Line {
348 from: Pos::new(pl.rect.x, pl.rect.bottom()),
349 to: Pos::new(pl.rect.right(), pl.rect.bottom()),
350 color: theme.axis,
351 width: stroke,
352 dashed: false,
353 });
354 }
355 grid.push(Primitive::Line {
356 from: Pos::new(plot.right(), plot.y),
357 to: Pos::new(plot.right(), plot.bottom()),
358 color: theme.axis,
359 width: stroke,
360 dashed: false,
361 });
362 let mut last_right = f32::NEG_INFINITY;
363 for tick in &x_ticks {
364 let px = scene.x.map(tick.time as f64) as f32;
365 let half = tick.label.chars().count() as f32 * m.char_width / 2.0;
366 if px - half < last_right + m.char_width || px - half < 0.0 || px + half > plot.right() {
367 continue;
368 }
369 last_right = px + half;
370 labels.push(Primitive::Text {
371 pos: Pos::new(px, plot.bottom() + m.padding),
372 text: tick.label.clone(),
373 color: theme.text,
374 h_align: Align::Center,
375 v_align: Align::Start,
376 });
377 }
378 if theme.background.a > 0.0 {
379 scene.layers.push(Layer {
380 clip: None,
381 primitives: vec![Primitive::Rect { rect: Rect::new(0.0, 0.0, size.width, size.height), color: theme.background }],
382 });
383 }
384 scene.layers.push(Layer { clip: None, primitives: grid });
385
386 for (i, pl) in scene.panes.iter().enumerate() {
388 let mut prims = Vec::new();
389 for e in self.entries.iter().filter(|e| e.visible && e.pane.0 == i) {
390 self.draw_entry(e, &scene.x, pl, m, &mut prims);
391 }
392 if let Some(title) = &self.panes[i].title {
393 prims.push(Primitive::Text {
394 pos: Pos::new(pl.rect.x + m.padding, pl.rect.y + m.padding),
395 text: title.clone(),
396 color: theme.text,
397 h_align: Align::Start,
398 v_align: Align::Start,
399 });
400 }
401 scene.layers.push(Layer { clip: Some(pl.rect), primitives: prims });
402 }
403
404 for e in self.entries.iter().filter(|e| e.visible && e.style.show_last_value) {
406 let (Some(v), Some(pl)) = (self.last_value(e), scene.panes.get(e.pane.0)) else { continue };
407 let py = pl.y.map(v) as f32;
408 if py < pl.rect.y || py > pl.rect.bottom() {
409 continue;
410 }
411 let color = self.last_color(e);
412 let text = format_value(v, ranges[e.pane.0].step / 10.0);
413 labels.retain(
414 |p| !matches!(p, Primitive::Text { pos, h_align: Align::Start, .. } if (pos.y - py).abs() < m.line_height && pos.x > plot.right()),
415 );
416 labels.push(Primitive::Rect {
417 rect: Rect::new(plot.right() + m.padding, py - m.line_height / 2.0, axis_w - m.padding, m.line_height),
418 color,
419 });
420 labels.push(Primitive::Text {
421 pos: Pos::new(plot.right() + m.padding * 2.0, py),
422 text,
423 color: theme.tag_text,
424 h_align: Align::Start,
425 v_align: Align::Center,
426 });
427 }
428 scene.layers.push(Layer { clip: None, primitives: labels });
429 scene
430 }
431
432 fn last_value(&self, e: &Entry) -> Option<f64> {
433 match &e.data {
434 Data::Points(s) => s.last().map(|p| p.value),
435 Data::Candles(s) => s.last().map(|c| c.close),
436 Data::VolumeOf(src) => self.candles(*src)?.last().map(|c| c.volume),
437 }
438 .filter(|v| v.is_finite())
439 }
440
441 fn last_color(&self, e: &Entry) -> Rgba {
442 let up = |c: Option<&Candle>| if c.is_none_or(|c| c.is_up()) { self.theme.up } else { self.theme.down };
443 match &e.data {
444 Data::Points(_) => e.style.color,
445 Data::Candles(s) => up(s.last()),
446 Data::VolumeOf(src) => up(self.candles(*src).and_then(|s| s.last())),
447 }
448 }
449
450 fn draw_entry(&self, e: &Entry, x: &LinearScale, pl: &PaneLayout, m: &Metrics, out: &mut Vec<Primitive>) {
451 let (start, end) = (self.viewport.start(), self.viewport.end());
452 let px_per_ms = (pl.rect.w as f64 / (end - start).max(1) as f64).max(0.0);
453 let columns = pl.rect.w.max(1.0) as usize;
454 let ymap = |v: f64| pl.y.map(v) as f32;
455 let zero_y = ymap(0.0f64.clamp(pl.y.domain.0, pl.y.domain.1));
456 match (&e.data, e.mark) {
457 (Data::Points(s), Mark::Line | Mark::Area) => {
458 let pts = downsample_min_max(s.range_padded(start, end), start, end, columns);
459 for run in finite_runs(&pts) {
460 let poly: Vec<Pos> = run.iter().map(|p| Pos::new(x.map(p.time as f64) as f32, ymap(p.value))).collect();
461 if e.mark == Mark::Area && poly.len() >= 2 {
462 out.push(Primitive::Area {
463 points: poly.clone(),
464 baseline: pl.rect.bottom(),
465 color: e.style.color.with_alpha(e.style.color.a * 0.25),
466 });
467 }
468 if poly.len() >= 2 {
469 out.push(Primitive::Polyline { points: poly, color: e.style.color, width: e.style.width.max(m.min_stroke) });
470 } else if let Some(p) = poly.first() {
471 let w = e.style.width.max(m.min_stroke);
472 out.push(Primitive::Rect { rect: Rect::new(p.x - w / 2.0, p.y - w / 2.0, w, w), color: e.style.color });
473 }
474 }
475 }
476 (Data::Points(s), _) => {
477 let interval = s.interval().unwrap_or((end - start) / columns.max(1) as i64).max(1);
478 let w = ((interval as f64 * px_per_ms * 0.8) as f32).max(m.min_stroke);
479 for p in s.range(start, end).filter(|p| p.value.is_finite()) {
480 let cx = x.map(p.time as f64) as f32;
481 let (a, b) = (zero_y, ymap(p.value));
482 out.push(Primitive::Rect { rect: Rect::new(cx - w / 2.0, a.min(b), w, (a - b).abs().max(m.min_stroke)), color: e.style.color });
483 }
484 }
485 (Data::Candles(_), _) | (Data::VolumeOf(_), _) => {
486 let Some(s) = self.candles_of(e) else { return };
487 let base_interval = s.interval().unwrap_or(60_000).max(1);
488 let mut interval = base_interval;
489 let slot_px = interval as f64 * px_per_ms;
490 let min_slot = (m.min_stroke * 3.0) as f64;
491 let candles: Vec<Candle> = if slot_px < min_slot {
492 let buckets = ((pl.rect.w as f64 / min_slot).floor() as usize).max(1);
493 interval = ((end - start) / buckets as i64).max(interval);
494 aggregate_candles(s.range_padded(start, end), start, end, buckets)
495 } else {
496 s.range_padded(start, end).copied().collect()
497 };
498 let slot = (interval as f64 * px_per_ms) as f32;
499 let body_w = (slot * 0.7).max(m.min_stroke);
500 let volume_scale = base_interval as f64 / interval as f64;
502 for c in candles.iter().filter(|c| c.open.is_finite() && c.high.is_finite() && c.low.is_finite() && c.close.is_finite()) {
503 let color = if c.is_up() { self.theme.up } else { self.theme.down };
504 let cx = x.map(c.time as f64 + interval as f64 / 2.0) as f32;
505 match e.mark {
506 Mark::Volume => {
507 if !c.volume.is_finite() {
508 continue;
509 }
510 let top = ymap(c.volume * volume_scale);
511 out.push(Primitive::Rect {
512 rect: Rect::new(cx - body_w / 2.0, top.min(zero_y), body_w, (zero_y - top).abs().max(m.min_stroke)),
513 color: color.with_alpha(0.6),
514 });
515 }
516 Mark::Ohlc => {
517 let line = |a: Pos, b: Pos| Primitive::Line { from: a, to: b, color, width: m.min_stroke, dashed: false };
518 out.push(line(Pos::new(cx, ymap(c.high)), Pos::new(cx, ymap(c.low))));
519 out.push(line(Pos::new(cx - body_w / 2.0, ymap(c.open)), Pos::new(cx, ymap(c.open))));
520 out.push(line(Pos::new(cx, ymap(c.close)), Pos::new(cx + body_w / 2.0, ymap(c.close))));
521 }
522 _ => {
523 out.push(Primitive::Line {
524 from: Pos::new(cx, ymap(c.high)),
525 to: Pos::new(cx, ymap(c.low)),
526 color,
527 width: m.min_stroke,
528 dashed: false,
529 });
530 let (a, b) = (ymap(c.open), ymap(c.close));
531 out.push(Primitive::Rect {
532 rect: Rect::new(cx - body_w / 2.0, a.min(b), body_w, (a - b).abs().max(m.min_stroke)),
533 color,
534 });
535 }
536 }
537 }
538 }
539 }
540 }
541
542 fn candles_of<'a>(&'a self, e: &'a Entry) -> Option<&'a crate::series::Series<Candle>> {
543 match &e.data {
544 Data::Candles(s) => Some(s),
545 Data::VolumeOf(src) => self.candles(*src),
546 Data::Points(_) => None,
547 }
548 }
549}
550
551fn finite_runs(points: &[Point]) -> impl Iterator<Item = &[Point]> {
552 points.split(|p| !p.value.is_finite()).filter(|r| !r.is_empty())
553}
554
555#[cfg(test)]
556mod tests {
557 use super::*;
558 use crate::chart::{Pane, SeriesStyle};
559 use crate::time::MINUTE;
560
561 fn sample_chart() -> (Chart, crate::SeriesId) {
562 let mut c = Chart::new();
563 let candles = c.add_candles(Chart::MAIN, "XYZ").unwrap();
564 let vol_pane = c.add_pane(Pane { weight: 1.0, y_range: YRange::AutoFromZero, title: Some("Volume".into()) });
565 c.add_volume(vol_pane, candles).unwrap();
566 let data: Vec<Candle> = (0..120)
567 .map(|i| {
568 let o = 100.0 + (i as f64 * 0.3).sin() * 5.0;
569 let cl = o + if i % 3 == 0 { -1.0 } else { 1.0 };
570 Candle::new(i * MINUTE, o, o.max(cl) + 0.5, o.min(cl) - 0.5, cl, 10.0 + i as f64)
571 })
572 .collect();
573 c.set_candles(candles, data).unwrap();
574 c.show_latest(60 * MINUTE);
575 (c, candles)
576 }
577
578 #[test]
579 fn lays_out_panes_axes_and_candles() {
580 let (c, _) = sample_chart();
581 let scene = c.layout(Size::new(800.0, 400.0), &Metrics::PIXELS);
582 assert_eq!(scene.panes.len(), 2);
583 let (a, b) = (scene.panes[0].rect, scene.panes[1].rect);
584 assert!(a.h > b.h * 2.5 && a.h < b.h * 3.5, "{a:?} {b:?}");
585 assert!(b.y > a.bottom());
586 assert!(scene.plot.right() < 800.0 - 7.0 * 4.0);
587 let texts: Vec<&str> =
588 scene.primitives().filter_map(|p| if let Primitive::Text { text, .. } = p { Some(text.as_str()) } else { None }).collect();
589 assert!(texts.contains(&"Volume"));
590 assert!(texts.iter().any(|t| t.contains(':')), "{texts:?}");
591 let rects =
592 scene.layers.iter().filter(|l| l.clip == Some(a)).flat_map(|l| &l.primitives).filter(|p| matches!(p, Primitive::Rect { .. })).count();
593 assert!((55..=64).contains(&rects), "{rects} candle bodies");
594 for l in scene.layers.iter().filter(|l| l.clip.is_some()) {
596 for p in &l.primitives {
597 if let Primitive::Rect { rect, .. } = p {
598 let clip = l.clip.unwrap();
599 assert!(rect.y >= clip.y - 0.01 && rect.bottom() <= clip.bottom() + 0.01, "{rect:?} outside {clip:?}");
600 }
601 }
602 }
603 }
604
605 #[test]
606 fn zoomed_out_candles_are_aggregated() {
607 let (mut c, _) = sample_chart();
608 c.fit_all();
609 let scene = c.layout(Size::new(200.0, 300.0), &Metrics::PIXELS);
610 let bodies = scene
611 .layers
612 .iter()
613 .filter(|l| l.clip == Some(scene.panes[0].rect))
614 .flat_map(|l| &l.primitives)
615 .filter(|p| matches!(p, Primitive::Rect { .. }))
616 .count();
617 let max = (scene.panes[0].rect.w / 3.0) as usize + 2;
618 assert!(bodies <= max && bodies > 10, "{bodies} > {max}");
619 }
620
621 #[test]
622 fn last_value_tag_and_lines() {
623 let mut c = Chart::new();
624 let id = c.add_series(Chart::MAIN, "p", Mark::Area, SeriesStyle::new(Rgba::hex(0x3366ff)).with_last_value()).unwrap();
625 for t in 0..10_000 {
626 c.push_point(id, Point::new(t * 1000, if t == 5000 { f64::NAN } else { (t % 100) as f64 })).unwrap();
627 }
628 c.fit_all();
629 let scene = c.layout(Size::new(640.0, 320.0), &Metrics::PIXELS);
630 let polys: Vec<usize> =
631 scene.primitives().filter_map(|p| if let Primitive::Polyline { points, .. } = p { Some(points.len()) } else { None }).collect();
632 assert_eq!(polys.len(), 2, "the NaN splits the line");
633 assert!(polys.iter().sum::<usize>() <= 640 * 4);
634 assert!(scene.primitives().any(|p| matches!(p, Primitive::Area { .. })));
635 assert!(scene.primitives().any(|p| matches!(p, Primitive::Text { text, .. } if text.starts_with("99"))), "last value tag");
636 let mid = scene.time_at(scene.plot.x + scene.plot.w / 2.0);
637 assert!((mid - c.viewport().start() - c.viewport().span() / 2).abs() < 1000);
638 }
639
640 #[test]
641 fn tiny_or_empty_surfaces_do_not_panic() {
642 let c = Chart::new();
643 assert!(c.layout(Size::new(10.0, 10.0), &Metrics::PIXELS).layers.is_empty());
644 let s = c.layout(Size::new(300.0, 200.0), &Metrics::PIXELS);
645 assert_eq!(s.panes.len(), 1);
646 }
647}