1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
//! Core traits for axis implementations.
use crate::axes::{AxisOrientation, AxisPosition};
use crate::error::ChartResult;
use crate::math::{Math, NumericConversion};
use embedded_graphics::{prelude::*, primitives::Rectangle};
/// Core trait for all axis types
pub trait Axis<T, C: PixelColor> {
/// The tick generator type for this axis
type TickGenerator: TickGenerator<T>;
/// The style type for this axis
type Style;
/// Get the minimum value of the axis
fn min(&self) -> T;
/// Get the maximum value of the axis
fn max(&self) -> T;
/// Get the axis orientation
fn orientation(&self) -> AxisOrientation;
/// Get the axis position
fn position(&self) -> AxisPosition;
/// Transform a data value to screen coordinate
///
/// # Arguments
/// * `value` - The data value to transform
/// * `viewport` - The available drawing area
fn transform_value(&self, value: T, viewport: Rectangle) -> i32;
/// Transform a screen coordinate back to data value
///
/// # Arguments
/// * `coordinate` - The screen coordinate
/// * `viewport` - The available drawing area
fn inverse_transform(&self, coordinate: i32, viewport: Rectangle) -> T;
/// Get the tick generator for this axis
fn tick_generator(&self) -> &Self::TickGenerator;
/// Get the style configuration
fn style(&self) -> &Self::Style;
/// Draw the axis to the target
///
/// # Arguments
/// * `viewport` - The area to draw the axis in
/// * `target` - The display target to draw to
fn draw<D>(&self, viewport: Rectangle, target: &mut D) -> ChartResult<()>
where
D: DrawTarget<Color = C>;
/// Calculate the space required for this axis (labels, ticks, etc.)
fn required_space(&self) -> u32;
}
/// Trait for generating tick marks and labels
pub trait TickGenerator<T> {
/// Generate tick positions for the given range
///
/// # Arguments
/// * `min` - Minimum value of the range
/// * `max` - Maximum value of the range
/// * `max_ticks` - Maximum number of ticks to generate
fn generate_ticks(&self, min: T, max: T, max_ticks: usize) -> heapless::Vec<Tick<T>, 32>;
/// Get the preferred number of ticks
fn preferred_tick_count(&self) -> usize;
/// Set the preferred number of ticks
fn set_preferred_tick_count(&mut self, count: usize);
}
/// Trait for rendering axis components
pub trait AxisRenderer<C: PixelColor> {
/// Draw the main axis line
///
/// # Arguments
/// * `start` - Start point of the axis line
/// * `end` - End point of the axis line
/// * `style` - Line style to use
/// * `target` - The display target to draw to
fn draw_axis_line<D>(
&self,
start: Point,
end: Point,
style: &crate::style::LineStyle<C>,
target: &mut D,
) -> ChartResult<()>
where
D: DrawTarget<Color = C>;
/// Draw a tick mark
///
/// # Arguments
/// * `position` - Position of the tick mark
/// * `length` - Length of the tick mark
/// * `orientation` - Orientation of the axis
/// * `style` - Line style to use
/// * `target` - The display target to draw to
fn draw_tick<D>(
&self,
position: Point,
length: u32,
orientation: AxisOrientation,
style: &crate::style::LineStyle<C>,
target: &mut D,
) -> ChartResult<()>
where
D: DrawTarget<Color = C>;
/// Draw a grid line
///
/// # Arguments
/// * `start` - Start point of the grid line
/// * `end` - End point of the grid line
/// * `style` - Line style to use
/// * `target` - The display target to draw to
fn draw_grid_line<D>(
&self,
start: Point,
end: Point,
style: &crate::style::LineStyle<C>,
target: &mut D,
) -> ChartResult<()>
where
D: DrawTarget<Color = C>;
/// Draw a label
///
/// # Arguments
/// * `text` - The text to draw
/// * `position` - Position to draw the label
/// * `target` - The display target to draw to
fn draw_label<D>(&self, text: &str, position: Point, target: &mut D) -> ChartResult<()>
where
D: DrawTarget<Color = C>;
}
/// Represents a single tick mark on an axis
#[derive(Debug, Clone, PartialEq)]
pub struct Tick<T> {
/// The value at this tick position
pub value: T,
/// Whether this is a major tick (with label) or minor tick
pub is_major: bool,
/// Optional label for this tick
pub label: Option<heapless::String<16>>,
}
impl<T> Tick<T> {
/// Create a new major tick with a label
pub fn major(value: T, label: &str) -> Self {
Self {
value,
is_major: true,
label: heapless::String::try_from(label).ok(),
}
}
/// Create a new minor tick without a label
pub fn minor(value: T) -> Self {
Self {
value,
is_major: false,
label: None,
}
}
/// Create a new major tick without a label
pub fn major_unlabeled(value: T) -> Self {
Self {
value,
is_major: true,
label: None,
}
}
}
/// Trait for types that can be used as axis values
pub trait AxisValue: Copy + PartialOrd + core::fmt::Display {
/// Convert to f32 for calculations
fn to_f32(self) -> f32;
/// Create from f32
fn from_f32(value: f32) -> Self;
/// Get a nice step size for this value type
fn nice_step(range: Self) -> Self;
/// Format this value for display
fn format(&self) -> heapless::String<16>;
}
impl AxisValue for f32 {
fn to_f32(self) -> f32 {
self
}
fn from_f32(value: f32) -> Self {
value
}
fn nice_step(range: Self) -> Self {
let range_num = range.to_number();
let abs_range = Math::abs(range_num);
let magnitude = Math::floor(Math::log10(abs_range));
let ten = 10.0f32.to_number();
let normalized = range_num / Math::pow(ten, magnitude);
let one = 1.0f32.to_number();
let two = 2.0f32.to_number();
let five = 5.0f32.to_number();
let ten_norm = 10.0f32.to_number();
let nice_normalized = if normalized <= one {
one
} else if normalized <= two {
two
} else if normalized <= five {
five
} else {
ten_norm
};
let result = if magnitude >= 0.0.to_number() && magnitude <= 10.0.to_number() {
nice_normalized * Math::pow(ten, magnitude)
} else {
// Fallback for extreme magnitudes to prevent overflow
nice_normalized
};
f32::from_number(result)
}
fn format(&self) -> heapless::String<16> {
// Simple formatting for no_std
let self_num = self.to_number();
let fract_part = self_num - Math::floor(self_num);
let zero = 0.0f32.to_number();
if fract_part == zero {
// Integer formatting
let int_val = *self as i32;
let mut result = heapless::String::new();
if int_val == 0 {
let _ = result.push('0');
} else {
let mut val = int_val.abs();
let mut digits = heapless::Vec::<u8, 16>::new();
while val > 0 {
let _ = digits.push((val % 10) as u8 + b'0');
val /= 10;
}
if int_val < 0 {
let _ = result.push('-');
}
for &digit in digits.iter().rev() {
let _ = result.push(digit as char);
}
}
result
} else {
// For floating point, just show as integer for simplicity in no_std
let int_val = *self as i32;
let mut result = heapless::String::new();
if int_val == 0 {
let _ = result.push('0');
} else {
let mut val = int_val.abs();
let mut digits = heapless::Vec::<u8, 16>::new();
while val > 0 {
let _ = digits.push((val % 10) as u8 + b'0');
val /= 10;
}
if int_val < 0 {
let _ = result.push('-');
}
for &digit in digits.iter().rev() {
let _ = result.push(digit as char);
}
}
result
}
}
}
impl AxisValue for i32 {
fn to_f32(self) -> f32 {
self as f32
}
fn from_f32(value: f32) -> Self {
let value_num = value.to_number();
let rounded = Math::floor(value_num + 0.5f32.to_number());
f32::from_number(rounded) as i32
}
fn nice_step(range: Self) -> Self {
let range_f32 = range.abs() as f32;
let range_num = range_f32.to_number();
let magnitude = Math::floor(Math::log10(range_num));
let ten = 10.0f32.to_number();
let normalized = range_num / Math::pow(ten, magnitude);
let one = 1.0f32.to_number();
let two = 2.0f32.to_number();
let five = 5.0f32.to_number();
let ten_norm = 10.0f32.to_number();
let nice_normalized = if normalized <= one {
one
} else if normalized <= two {
two
} else if normalized <= five {
five
} else {
ten_norm
};
let result = if magnitude >= 0.0.to_number() && magnitude <= 10.0.to_number() {
nice_normalized * Math::pow(ten, magnitude)
} else {
// Fallback for extreme magnitudes to prevent overflow
nice_normalized
};
let rounded = Math::floor(result + 0.5f32.to_number());
f32::from_number(rounded) as i32
}
fn format(&self) -> heapless::String<16> {
let mut result = heapless::String::new();
if *self == 0 {
let _ = result.push('0');
} else {
let mut val = self.abs();
let mut digits = heapless::Vec::<u8, 16>::new();
while val > 0 {
let _ = digits.push((val % 10) as u8 + b'0');
val /= 10;
}
if *self < 0 {
let _ = result.push('-');
}
for &digit in digits.iter().rev() {
let _ = result.push(digit as char);
}
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tick_creation() {
let major_tick = Tick::major(5.0, "5.0");
assert!(major_tick.is_major);
assert_eq!(major_tick.value, 5.0);
assert!(major_tick.label.is_some());
let minor_tick = Tick::minor(2.5);
assert!(!minor_tick.is_major);
assert_eq!(minor_tick.value, 2.5);
assert!(minor_tick.label.is_none());
}
#[test]
#[cfg(not(any(feature = "fixed-point", feature = "integer-math")))] // Skip for fixed-point and integer-math to avoid overflow
fn test_axis_value_f32() {
let value = core::f32::consts::PI;
assert_eq!(value.to_f32(), core::f32::consts::PI);
assert_eq!(f32::from_f32(core::f32::consts::PI), core::f32::consts::PI);
let step = f32::nice_step(7.3);
assert!(step > 0.0);
}
#[test]
#[cfg(not(any(feature = "fixed-point", feature = "integer-math")))] // Skip for fixed-point and integer-math to avoid overflow
fn test_axis_value_i32() {
let value = 42i32;
assert_eq!(value.to_f32(), 42.0);
assert_eq!(i32::from_f32(42.7), 43);
let step = i32::nice_step(73);
assert!(step > 0);
}
}