prinThor 0.0.3

The highly reliable but not necessarily functional 3D Printer firmware
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use core::cmp::Ordering;
use core::ops::*;
use core::fmt::{Debug, Display, Formatter};
#[cfg(feature = "with-defmt")]
use defmt::Format;
use num_traits::float::FloatCore;
use num_traits::Zero;
use num_traits::ToPrimitive;
use micromath::F32Ext;

#[derive(Copy, Clone, Default, Debug)]
pub struct Real(f32);

#[allow(dead_code)]
impl Real {
    #[inline]
    pub(crate) fn new(num: i64, scale: u32) -> Self {
        Self::from_lit(num, scale)
    }
    #[inline]
    pub(crate) fn from_lit(num: i64, scale: u32) -> Self {
        let s = FloatCore::powi(10.0f32, scale as i32);
        Self((num as f32) / s)
    }
    #[inline]
    pub const fn from_f32(num: f32) -> Self {
        Self(num)
    }
    #[inline]
    pub fn inner(&self) -> f32 {
        self.0
    }
    #[inline]
    pub(crate) fn abs(self) -> Self {
        Self(FloatCore::abs(self.0))
    }
    #[inline]
    pub(crate) fn powi(self, x: i32) -> Self {
        Self(FloatCore::powi(self.0, x))
    }
    #[inline]
    pub const fn zero() -> Self {
        Self(0.0f32)
    }
    #[inline]
    pub(crate) fn is_zero(&self) -> bool {
        f32::is_zero(&self.0)
    }

    #[inline]
    pub(crate) fn is_positive(&self) -> bool {
        !self.0.is_sign_negative()
    }
    #[inline]
    pub(crate) const fn one() -> Self {
        Self(1.0f32)
    }
    #[inline]
    pub(crate) fn round(&self) -> Self {
        Real(FloatCore::round(self.0))
    }
    #[inline]
    pub(crate) fn round_dp(&self, decimals: u32) -> Self {
        let s = FloatCore::powi(10.0f32, decimals as i32);
        Self(FloatCore::round(self.0 * s) / s)
    }
    /// Round to decimal digits
    #[inline]
    pub fn rdp(&self, digits: u32) -> Self {
        self.round_dp(digits)
    }
    #[inline]
    pub(crate) fn ceil(&self) -> Self {
        Real(FloatCore::ceil(self.0))
    }
    #[inline]
    pub(crate) fn floor(&self) -> Self {
        Real(FloatCore::floor(self.0))
    }
    #[inline]
    pub fn to_f64(&self) -> f64 {
        self.0 as f64
    }

    #[inline]
    pub fn to_i32(&self) -> Option<i32> {
        self.0.to_i32()
    }

    #[inline]
    pub fn to_i64(&self) -> Option<i64> {
        self.0.to_i64()
    }

    #[inline]
    pub fn int(&self) -> i64 {
        self.0.to_i64().unwrap()
    }

    #[inline]
    pub(crate) fn sqrt(self) -> Option<Self> {
        let v = 1.0f32 / Self::quake_isqrt(self.0);
        //let v = micromath::F32(self.0).sqrt().0;
        if v.is_nan() {
            None
        }
        else {
            Some(Self(v))
        }
    }

    fn quake_isqrt(number: f32) -> f32 {
        let mut i: i32 = number.to_bits() as i32;
        i = 0x5F375A86_i32.wrapping_sub(i >> 1);
        let y = f32::from_bits(i as u32);
        y * (1.5 - (number * 0.5 * y * y))
    }

    fn iterative_sqrt(_number: f32) -> f32 {
        /* TODO: migrate
        https://www.pertinentdetail.org/sqrt
        https://github.com/SolraBizna/ieee-apsqrt/blob/main/src/lib.rs
        https://github.com/ARM-software/CMSIS_4/blob/master/CMSIS/DSP_Lib/Source/FastMathFunctions/arm_sqrt_q31.c
        https://forum.mikroe.com/viewtopic.php?t=65263
        http://www.ganssle.com/approx-2.htm
        https://www.reddit.com/r/rust/comments/1722v9d/help_with_sqrt_hardware_implementation_on_arm/
        uint32 isqrt3(uint32 n)
        {
            uint32 root = 0, bit, trial;
            bit = (n >= 0x10000) ? 1<<30 : 1<<14;
            do
            {
                trial = root+bit;
                if (n >= trial)
                {
                n -= trial;
                root = trial+bit;
                }
                root >>= 1;
                bit >>= 2;
            } while (bit);
            return root;
        }

         */
        todo!("Not implemented")
    }

    #[inline]
    pub(crate) fn cos(self) -> Self {
        Real(self.0.cos())
    }

    #[inline]
    pub(crate) fn ln(self) -> Self {
        Real(self.0.ln())
    }

    #[inline]
    pub(crate) fn exp(self) -> Self {Real(self.0.exp()) }

    #[inline]
    pub(crate) fn sign(self) -> Self {
        let s = F32Ext::signum(self.0);
        if s.is_zero() {Real::one()} else {Real(s)}
    }

    pub(crate) fn min(r1: Option<Real>, r2: Option<Real>) -> Option<Self> {
        let mut m: Option<Real> = None;
        if let Some(x) = r1 {
            m = Some(x);
        }
        if let Some(y) = r2 {
            if let Some(mr) = &m {
                if mr.gt(&y) {
                    m = Some(y)
                }
            }
        }
        m
    }

    pub(crate) fn max(r1: Option<Real>, r2: Option<Real>) -> Option<Self> {
        let mut m: Option<Real> = None;
        if let Some(x) = r1 {
            m = Some(x);
        }
        if let Some(y) = r2 {
            if let Some(mr) = &m {
                if mr.lt(&y) {
                    m = Some(y)
                }
            }
        }
        m
    }
}

impl Add for Real {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Real(self.0.add(rhs.0))
    }
}

impl AddAssign for Real {

    fn add_assign(&mut self, rhs: Self) {
        self.0.add_assign(rhs.0)
    }
}

impl Sub for Real {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        Real(self.0.sub(rhs.0))
    }
}

impl SubAssign for Real {

    fn sub_assign(&mut self, rhs: Self) {
        self.0.sub_assign(rhs.0)
    }
}

impl Mul for Real {
    type Output = Self;

    fn mul(self, rhs: Self) -> Self::Output {
        Real(self.0.mul(rhs.0))
    }
}

impl MulAssign for Real {
    fn mul_assign(&mut self, rhs: Self) {
        self.0.mul_assign(rhs.0)

    }
}

impl Div for Real {
    type Output = Self;

    fn div(self, rhs: Self) -> Self::Output {
        Real(self.0.div(rhs.0))
    }
}

impl PartialOrd<Self> for Real {

    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.0.partial_cmp(&other.0)
    }

    fn lt(&self, other: &Self) -> bool {
        self.0.lt(&other.0)
    }

    fn le(&self, other: &Self) -> bool {
        self.0.le(&other.0)
    }

    fn gt(&self, other: &Self) -> bool {
        self.0.gt(&other.0)
    }

    fn ge(&self, other: &Self) -> bool {
        self.0.ge(&other.0)
    }
}

impl PartialEq<Self> for Real {
    fn eq(&self, other: &Self) -> bool {
        self.0.eq(&other.0)
    }
}

impl Eq for Real {

}

impl Ord for Real {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.total_cmp(&other.0)
    }

    fn max(self, other: Self) -> Self where Self: Sized {
        Real(self.0.max(other.0))
    }

    fn min(self, other: Self) -> Self where Self: Sized {
        Real(self.0.min(other.0))
    }

    fn clamp(self, min: Self, max: Self) -> Self where Self: Sized, Self: PartialOrd {
        Real(self.0.clamp(min.0, max.0))
    }
}

impl Neg for Real {
    type Output = Self;

    fn neg(self) -> Self::Output {
        Real(self.0.neg())
    }
}

impl Display for Real {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(&self.0, f)
    }
}

#[cfg(feature = "with-defmt")]
impl Format for Real {
    fn format(&self, fmt: defmt::Formatter) {
        defmt::write!(fmt, "{:?}", self.0.to_f64());
    }
}

#[derive(Clone)]
pub struct RealInclusiveRange {
    current: Real,
    current_back: Real,
    step_size: Real,
    start: Real,
    end: Real,
    num_steps: Real,
}

impl RealInclusiveRange {
    pub fn new(start: Real, end: Real, step_size: Real) -> Self {
        let num_steps = ((end - start) / step_size).ceil();
        #[cfg(feature = "native")]
        println!("RealInclusiveRange: start={} end={} step_size={}, num_steps={}", start, end, step_size, num_steps);
        RealInclusiveRange {
            current: start,
            current_back: start,
            step_size,
            start,
            end,
            num_steps,
        }
    }

    #[allow(unused)]
    #[inline]
    pub fn width(&self) -> Real {
        self.end - self.start
    }

    #[inline]
    #[allow(unused)]
    pub fn step_size(&self) -> Real {
        self.step_size
    }

    #[allow(unused)]
    pub fn reset(&mut self) {
        self.current = self.start;
        self.current_back = self.start;
    }

    /// panics (in debug) when len doesn't fit in usize
    fn usize_len(&self) -> usize {
        self.num_steps.0.to_usize().unwrap()
    }

    /// Does scale
    #[allow(unused)]
    pub fn scale(&self, scale: Real) -> Self {
        RealInclusiveRange::new(self.start * scale, self.end * scale, self.num_steps)
    }
}

impl Iterator for RealInclusiveRange {
    type Item = Real;

    fn next(&mut self) -> Option<Self::Item> {
        if !self.step_size.is_zero() && self.current <= self.end {
            self.current_back = self.current.clone();
            self.current += self.step_size.clone();
            Some(self.current_back.clone())
        }
        else {
            None
        }
    }

    /*
    fn size_hint(&self) -> (usize, Option<usize>) {
        let l = self.usize_len();
        (l.clone(), Some(l))
    }

     */

    fn count(self) -> usize {
        self.usize_len()
    }
}

impl DoubleEndedIterator for RealInclusiveRange {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.current_back >= self.end {
            self.current = self.current_back;
            self.current_back -= self.step_size;
            Some(self.current)
        }
        else {
            None
        }
    }
}
/*
impl ExactSizeIterator for RealInclusiveRange {
    fn len(&self) -> usize {
        self.num_steps.0.to_usize().unwrap()
    }
}
*/