crisol_plot/plot/measure/
curve.rs1use egui::{Pos2, Rect, pos2, vec2};
4
5use super::{DistanceSummary, MeasurementAreaStyle, PlotMeasurement};
6use crate::plot::scene::{Dash, Measure, Prim, Scene};
7use crate::plot::transform::Transform;
8use crate::plot::{Plot, PlotState};
9use crisol_ui_kit::theme::Theme;
10
11#[derive(Clone, Debug, PartialEq)]
13pub struct CurveAreaSummary {
14 pub series: String,
16 pub area: f64,
18 pub absolute_area: f64,
20 pub chord: DistanceSummary,
22 pub arc_length: f64,
24 pub max_deviation: f64,
26 pub max_deviation_at: [f64; 2],
28}
29
30pub fn curve_area_summary(
32 plot: &Plot<'_>,
33 state: &PlotState,
34 measurement: &PlotMeasurement,
35) -> Option<CurveAreaSummary> {
36 let PlotMeasurement::CurveArea {
37 series,
38 start,
39 end,
40 start_index,
41 end_index,
42 } = measurement
43 else {
44 return None;
45 };
46 let series = plot.visible(state).find(|candidate| candidate.name() == series)?;
47 let data = series.data();
48 if data.len() < 2 {
49 return None;
50 }
51 let max = data.len() - 1;
52 let (low, high) = if start_index <= end_index {
53 ((*start_index).min(max), (*end_index).min(max))
54 } else {
55 ((*end_index).min(max), (*start_index).min(max))
56 };
57 let mut points = data[low..=high]
58 .iter()
59 .copied()
60 .filter(|point| point[0].is_finite() && point[1].is_finite())
61 .collect::<Vec<_>>();
62 if points.len() < 2 {
63 return None;
64 }
65 points.sort_by(|a, b| a[0].total_cmp(&b[0]));
66 let (chord_start, chord_end) = if start[0] <= end[0] { (start, end) } else { (end, start) };
67 let chord = PlotMeasurement::distance(*chord_start, *chord_end).distance_summary()?;
68 let chord_dx = chord_end[0] - chord_start[0];
69 let chord_y = |x: f64| {
70 if chord_dx.abs() <= f64::EPSILON {
71 chord_start[1]
72 } else {
73 chord_start[1] + (x - chord_start[0]) * (chord_end[1] - chord_start[1]) / chord_dx
74 }
75 };
76 let mut area = 0.0;
77 let mut absolute_area = 0.0;
78 let mut arc_length = 0.0;
79 for pair in points.windows(2) {
80 let (a, b) = (pair[0], pair[1]);
81 let dx = b[0] - a[0];
82 let da = a[1] - chord_y(a[0]);
83 let db = b[1] - chord_y(b[0]);
84 let strip = dx * (da + db) * 0.5;
85 area += strip;
86 absolute_area += strip.abs();
87 arc_length += (dx * dx + (b[1] - a[1]).powi(2)).sqrt();
88 }
89 let mut max_deviation = 0.0;
90 let mut max_deviation_at = points[0];
91 for point in &points {
92 let deviation = (point[1] - chord_y(point[0])).abs();
93 if deviation > max_deviation {
94 max_deviation = deviation;
95 max_deviation_at = *point;
96 }
97 }
98 Some(CurveAreaSummary {
99 series: series.name().to_owned(),
100 area,
101 absolute_area,
102 chord,
103 arc_length,
104 max_deviation,
105 max_deviation_at,
106 })
107}
108
109pub(super) fn paint(
110 scene: &mut Scene,
111 measure: &Measure,
112 transform: &Transform,
113 plot: &Plot<'_>,
114 state: &PlotState,
115 theme: &Theme,
116 measurement: &PlotMeasurement,
117) {
118 let PlotMeasurement::CurveArea {
119 start_index, end_index, ..
120 } = measurement
121 else {
122 return;
123 };
124 let Some(summary) = curve_area_summary(plot, state, measurement) else {
125 return;
126 };
127 let chord_start_data = summary.chord.start;
128 let chord_end_data = summary.chord.end;
129 let chord_dx = chord_end_data[0] - chord_start_data[0];
130 let chord_at = |x: f64| {
131 if chord_dx.abs() <= f64::EPSILON {
132 chord_start_data[1]
133 } else {
134 chord_start_data[1] + (x - chord_start_data[0]) * (chord_end_data[1] - chord_start_data[1]) / chord_dx
135 }
136 };
137 let Some(series) = plot.visible(state).find(|series| series.name() == summary.series) else {
138 return;
139 };
140 let data = series.data();
141 let max = data.len().saturating_sub(1);
142 let (low, high) = if start_index <= end_index {
143 ((*start_index).min(max), (*end_index).min(max))
144 } else {
145 ((*end_index).min(max), (*start_index).min(max))
146 };
147 let points = data[low..=high]
148 .iter()
149 .filter(|point| point[0].is_finite() && point[1].is_finite())
150 .map(|point| transform.to_screen(*point))
151 .collect::<Vec<_>>();
152 if points.len() < 2 {
153 return;
154 }
155 let chord_start = transform.to_screen(summary.chord.start);
156 let chord_end = transform.to_screen(summary.chord.end);
157 let mut polygon = points.clone();
158 polygon.push(chord_end);
159 polygon.push(chord_start);
160 scene.data.push(Prim::Polygon {
161 points: polygon,
162 color: theme.link.gamma_multiply(0.16),
163 });
164 scene.data.push(Prim::Line {
165 points: points.clone(),
166 width: 2.0,
167 color: theme.link,
168 dash: Dash::Solid,
169 });
170 scene.data.push(Prim::Line {
171 points: vec![chord_start, chord_end],
172 width: 1.2,
173 color: theme.warning,
174 dash: Dash::Dashed(5.0, 4.0),
175 });
176 for point in [chord_start, chord_end, transform.to_screen(summary.max_deviation_at)] {
177 scene.data.push(Prim::Circle {
178 center: point,
179 radius: 2.5,
180 fill: theme.warning,
181 stroke: None,
182 });
183 }
184
185 if summary.max_deviation > f64::EPSILON {
188 let peak = summary.max_deviation_at;
189 let base = [peak[0], chord_at(peak[0])];
190 double_arrow(
191 scene,
192 transform.to_screen(base),
193 transform.to_screen(peak),
194 theme.warning,
195 );
196 }
197 if !state.measurement.show_labels {
198 return;
199 }
200 let area = match state.measurement.area_style {
201 MeasurementAreaStyle::Signed => summary.area,
202 MeasurementAreaStyle::Absolute => summary.absolute_area,
203 };
204 let label = format!(
205 "{} area={} u² |area|={} u²",
206 summary.series,
207 number(area),
208 number(summary.absolute_area)
209 );
210 let chord = format!(
211 "Δx={} Δy={} peak height={} u",
212 number(summary.chord.dx),
213 number(summary.chord.dy),
214 number(summary.max_deviation)
215 );
216 let detail = format!(
217 "peak=({}, {}) chord={} slope={} {}° arc={}",
218 number(summary.max_deviation_at[0]),
219 number(summary.max_deviation_at[1]),
220 number(summary.chord.distance),
221 summary.chord.slope.map_or_else(|| "∞".to_owned(), number),
222 number(summary.chord.angle_deg),
223 number(summary.arc_length)
224 );
225 let at = label_anchor(&points).unwrap_or_else(|| transform.frame.left_top()) + vec2(6.0, 6.0);
226 super::label_block(scene, measure, at, &[label, chord, detail], theme.link, theme);
227}
228
229fn double_arrow(scene: &mut Scene, from: egui::Pos2, to: egui::Pos2, color: egui::Color32) {
230 let direction = to - from;
231 if direction.length_sq() <= 1.0e-6 {
232 return;
233 }
234 scene.data.push(Prim::Line {
235 points: vec![from, to],
236 width: 1.4,
237 color,
238 dash: Dash::Solid,
239 });
240 arrow_head(scene, from, direction.normalized(), color);
241 arrow_head(scene, to, -direction.normalized(), color);
242}
243
244fn arrow_head(scene: &mut Scene, tip: egui::Pos2, direction: egui::Vec2, color: egui::Color32) {
245 let base = tip - direction * 7.0;
246 let side = egui::vec2(-direction.y, direction.x) * 3.0;
247 scene.data.push(Prim::Polygon {
248 points: vec![tip, base + side, base - side],
249 color,
250 });
251}
252
253fn label_anchor(points: &[Pos2]) -> Option<Pos2> {
254 let (mut min, mut max) = (points[0], points[0]);
255 for point in points {
256 min.x = min.x.min(point.x);
257 min.y = min.y.min(point.y);
258 max.x = max.x.max(point.x);
259 max.y = max.y.max(point.y);
260 }
261 let rect = Rect::from_min_max(min, max);
262 Some(pos2(rect.left(), rect.top()))
263}
264
265fn number(value: f64) -> String {
266 super::number(value)
267}