draco_oxide/core/
shared.rs

1use super::attribute::ComponentDataType;
2use crate::core::bit_coder::ReaderErr;
3use draco_nd_vector::impl_ndvector_ops;
4
5use core::fmt;
6use std::{cmp, mem, ops};
7
8#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
9pub struct AttributeValueIdx(usize);
10#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
11pub struct CornerIdx(usize);
12#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
13pub struct EdgeIdx(usize);
14#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
15pub struct FaceIdx(usize);
16#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
17pub struct PointIdx(usize);
18#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
19pub struct VertexIdx(usize);
20
21macro_rules! idx_op_impl {
22    ($($trait_:ident, $method:ident, $op:tt, $t:ty);*) => {
23        $(
24            impl ops::$trait_<$t> for $t {
25                type Output = Self;
26
27                fn $method(self, other: Self) -> Self::Output {
28                    Self( self.0 $op other.0 )
29                }
30            }
31        )*
32    };
33}
34
35macro_rules! all_idx_ops_impl {
36    ($($t:ty),*) => {
37        $(
38            idx_op_impl! {
39                Add, add, +, $t;
40                Sub, sub, -, $t;
41                Mul, mul, *, $t;
42                Div, div, /, $t
43            }
44        )*
45    };
46}
47
48all_idx_ops_impl! {
49    AttributeValueIdx,
50    CornerIdx,
51    EdgeIdx,
52    FaceIdx,
53    PointIdx,
54    VertexIdx
55}
56
57macro_rules! idx_debug_impl {
58    ($($t:ty),*) => {
59        $(
60            impl fmt::Debug for $t {
61                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62                    self.0.fmt(f)
63                }
64            }
65        )*
66    };
67}
68
69idx_debug_impl! {
70    AttributeValueIdx,
71    CornerIdx,
72    EdgeIdx,
73    FaceIdx,
74    PointIdx,
75    VertexIdx
76}
77
78macro_rules! vec_with_new_idx {
79    ($($Idx:ident),*) => {
80        $(
81            paste::paste! {
82                /// Vector wrapper indexed by `$Idx` and named `Vec$Idx` (e.g. `VecIsize`).
83                #[derive(Debug, Clone, Default, PartialEq, Eq)]
84                pub struct [<Vec $Idx:camel>]<T> {
85                    inner: ::std::vec::Vec<T>,
86                }
87
88                impl<T: Clone> [<Vec $Idx:camel>]<T> {
89                    #[allow(unused)]
90                    /// Create an empty vector.
91                    pub fn new() -> Self {
92                        Self { inner: ::std::vec::Vec::new() }
93                    }
94
95                    #[allow(unused)]
96                    /// Create with pre-allocated capacity.
97                    pub fn with_capacity(capacity: usize) -> Self {
98                        Self { inner: ::std::vec::Vec::with_capacity(capacity) }
99                    }
100
101                    #[allow(unused)]
102                    /// Push a value onto the end.
103                    pub fn push(&mut self, value: T) {
104                        self.inner.push(value)
105                    }
106
107                    #[allow(unused)]
108                    pub fn len(&self) -> usize { self.inner.len() }
109                    #[allow(unused)]
110                    pub fn is_empty(&self) -> bool { self.inner.is_empty() }
111                    #[allow(unused)]
112                    pub fn resize(&mut self, new_len: usize, value: T) {
113                        self.inner.resize(new_len, value);
114                    }
115
116                    #[allow(unused)]
117                    pub fn reserve(&mut self, additional: usize) {
118                        self.inner.reserve(additional);
119                    }
120
121                    #[allow(unused)]
122                    /// Take the inner Vec if you need it back.
123                    pub fn into_inner(self) -> ::std::vec::Vec<T> { self.inner }
124
125                    #[allow(unused)]
126                    pub fn iter(&self) -> impl Iterator<Item = &T> {
127                        self.inner.iter()
128                    }
129
130                    #[allow(unused)]
131                    pub fn remove(&mut self, idx: $Idx) -> T {
132                        self.inner.remove(usize::from(idx))
133                    }
134
135                    #[allow(unused)]
136                    pub fn clear(&mut self) {
137                        self.inner.clear();
138                    }
139                }
140
141                impl<T> ::std::ops::Index<$Idx> for [<Vec $Idx:camel>]<T> {
142                    type Output = T;
143                    fn index(&self, idx: $Idx) -> &Self::Output {
144                        // Convert the `$Idx` (e.g., isize) to usize, panicking if negative/overflow.
145                        let i: usize = ::std::convert::TryInto::<usize>::try_into(idx)
146                            .ok()
147                            .expect("index does not fit in usize (negative or too large)");
148                        &self.inner[i]
149                    }
150                }
151
152                impl<T> ::std::ops::IndexMut<$Idx> for [<Vec $Idx:camel>]<T> {
153                    fn index_mut(&mut self, idx: $Idx) -> &mut Self::Output {
154                        let i: usize = ::std::convert::TryInto::<usize>::try_into(idx)
155                            .ok()
156                            .expect("index does not fit in usize (negative or too large)");
157                        &mut self.inner[i]
158                    }
159                }
160
161                impl<T> ::std::convert::From<::std::vec::Vec<T>> for [<Vec $Idx:camel>]<T> {
162                    fn from(inner: ::std::vec::Vec<T>) -> Self {
163                        Self { inner }
164                    }
165                }
166
167                impl<T> ::std::iter::IntoIterator for [<Vec $Idx:camel>]<T> {
168                    type Item = T;
169                    type IntoIter = ::std::vec::IntoIter<T>;
170
171                    fn into_iter(self) -> Self::IntoIter {
172                        self.inner.into_iter()
173                    }
174                }
175            }
176        )*
177    };
178}
179
180vec_with_new_idx!(
181    AttributeValueIdx,
182    CornerIdx,
183    EdgeIdx,
184    FaceIdx,
185    PointIdx,
186    VertexIdx
187);
188
189macro_rules! idx_impl {
190    ($($t:ty),*) => {
191        $(
192            impl From<usize> for $t {
193                fn from(idx: usize) -> Self {
194                    Self(idx)
195                }
196            }
197
198            impl From<$t> for usize {
199                fn from(idx: $t) -> Self {
200                    idx.0
201                }
202            }
203        )*
204    };
205}
206
207idx_impl! {
208    AttributeValueIdx,
209    CornerIdx,
210    EdgeIdx,
211    FaceIdx,
212    PointIdx,
213    VertexIdx
214}
215
216pub trait Float: DataValue + ops::Div<Output = Self> + ops::Neg<Output = Self> {
217    fn sqrt(self) -> Self;
218}
219
220impl Float for f32 {
221    fn sqrt(self) -> Self {
222        self.sqrt()
223    }
224}
225
226impl Float for f64 {
227    fn sqrt(self) -> Self {
228        self.sqrt()
229    }
230}
231
232pub trait ConfigType {
233    fn default() -> Self;
234}
235
236pub trait ToUsize {
237    #[allow(unused)]
238    fn to_usize(self) -> usize;
239}
240
241macro_rules! impl_to_usize_float {
242    ($($t:ty),*) => {
243        $(
244            impl ToUsize for $t {
245                fn to_usize(self)-> usize {
246                    self.to_bits() as usize
247                }
248            }
249        )*
250    };
251}
252
253impl_to_usize_float!(f32, f64);
254
255macro_rules! impl_to_usize_float {
256    ($($t:ty),*) => {
257        $(
258            impl ToUsize for $t {
259                fn to_usize(self)-> usize {
260                    self as usize
261                }
262            }
263        )*
264    };
265}
266
267impl_to_usize_float!(u8, u16, u32, u64, i8, i16, i32, i64);
268
269pub trait Abs {
270    fn abs(self) -> Self;
271}
272macro_rules! impl_abs {
273    (negatable: $($t:ty),*) => {
274        $(
275            impl Abs for $t {
276                fn abs(self) -> Self {
277                    self.abs()
278                }
279            }
280        )*
281    };
282    (non_negatable: $($t:ty),*) => {
283        $(
284            impl Abs for $t {
285                fn abs(self) -> Self {
286                    self
287                }
288            }
289        )*
290    };
291}
292
293impl_abs!(negatable: f32, f64, i8, i16, i32, i64);
294impl_abs!(non_negatable: u8, u16, u32, u64);
295
296pub trait Acos {
297    #[allow(unused)]
298    fn acos(self) -> Self;
299}
300
301macro_rules! impl_acos {
302    (float: $($t:ty),*) => {
303        $(
304            impl Acos for $t {
305                fn acos(self) -> Self {
306                    self.acos()
307                }
308            }
309        )*
310    };
311    (non_float: $($t:ty),*) => {
312        $(
313            impl Acos for $t {
314                fn acos(self) -> Self {
315                    panic!("Acos is not defined for non-float types")
316                }
317            }
318        )*
319    };
320}
321impl_acos!(float: f32, f64);
322impl_acos!(non_float: u8, u16, u32, u64, i8, i16, i32, i64);
323
324pub trait Max {
325    const MAX_VALUE: Self;
326}
327
328macro_rules! impl_max {
329    ($($t:ty),*) => {
330        $(
331            impl Max for $t {
332                const MAX_VALUE: Self = Self::MAX;
333            }
334        )*
335    };
336}
337impl_max!(f32, f64);
338impl_max!(u8, u16, u32, u64, i8, i16, i32, i64);
339
340/// A trait that defines the basic mathematical operations and properties for the elements of the vector.
341pub trait DataValue:
342    Clone
343    + Copy
344    + fmt::Debug
345    + PartialEq
346    + PartialOrd
347    + Portable
348    + Into<serde_json::Value>
349    + Abs
350    + Max
351    + ops::Add<Output = Self>
352    + ops::Sub<Output = Self>
353    + ops::Mul<Output = Self>
354    + ops::Div<Output = Self>
355    + ops::AddAssign
356    + ops::SubAssign
357    + ops::MulAssign
358    + ops::DivAssign
359{
360    fn get_dyn() -> ComponentDataType;
361    fn zero() -> Self;
362    fn one() -> Self;
363    fn from_u64(data: u64) -> Self;
364    fn to_u64(self) -> u64;
365    fn to_i64(self) -> i64;
366    fn from_i64(data: i64) -> Self;
367    fn from_f64(data: f64) -> Self;
368    fn to_f64(self) -> f64;
369}
370
371macro_rules! impl_data_value {
372    (int: $(($t:ty, $component_type: expr)),*) => {
373        $(
374            impl DataValue for $t {
375                fn get_dyn() -> ComponentDataType {
376                    $component_type
377                }
378                fn zero() -> Self {
379                    0 as $t
380                }
381
382                fn one() -> Self {
383                    1 as $t
384                }
385
386                fn from_u64(data: u64) -> Self {
387                    data as $t
388                }
389
390                fn to_u64(self) -> u64 {
391                    self as u64
392                }
393
394                fn to_i64(self) -> i64 {
395                    self as i64
396                }
397
398                fn from_i64(data: i64) -> Self {
399                    data as $t
400                }
401
402                fn from_f64(data: f64) -> Self {
403                    data as $t
404                }
405
406                fn to_f64(self) -> f64 {
407                    self as f64
408                }
409            }
410
411            impl Portable for $t {
412                fn to_bytes(self) -> Vec<u8> {
413                    self.to_le_bytes().to_vec()
414                }
415
416                fn write_to<W>(self, writer: &mut W) where W: ByteWriter {
417                    for b in self.to_le_bytes().iter() {
418                        writer.write_u8(*b);
419                    }
420                }
421
422                fn read_from<R>(reader: &mut R) -> Result<Self, ReaderErr>
423                    where R: ByteReader
424                {
425                    let mut bytes = [0u8; mem::size_of::<Self>()];
426                    for i in 0..bytes.len() {
427                        bytes[i] = reader.read_u8()?;
428                    }
429                    Ok(Self::from_le_bytes(bytes))
430                }
431            }
432        )*
433    };
434
435    (float: $(($t:ty, $uint_t:ty, $component_type: expr)),*) => {
436        $(
437            impl DataValue for $t {
438                fn get_dyn() -> ComponentDataType {
439                    $component_type
440                }
441                fn zero() -> Self {
442                    0 as $t
443                }
444
445                fn one() -> Self {
446                    1 as $t
447                }
448
449                fn from_u64(data: u64) -> Self {
450                    data as $t
451                }
452
453                fn to_u64(self) -> u64 {
454                    self as u64
455                }
456
457                fn to_i64(self) -> i64 {
458                    self as i64
459                }
460
461                fn from_i64(data: i64) -> Self {
462                    data as $t
463                }
464
465                fn from_f64(data: f64) -> Self {
466                    data as $t
467                }
468
469                fn to_f64(self) -> f64 {
470                    self as f64
471                }
472            }
473
474            impl Portable for $t {
475                fn to_bytes(self) -> Vec<u8> {
476                    self.to_le_bytes().to_vec()
477                }
478
479                fn write_to<W>(self, writer: &mut W) where W: ByteWriter {
480                    let bits = self.to_bits();
481                    for b in bits.to_le_bytes().iter() {
482                        writer.write_u8(*b);
483                    }
484                }
485
486                fn read_from<R>(reader: &mut R) -> Result<Self, ReaderErr>
487                    where R: ByteReader
488                {
489                    let mut bytes = [0u8; mem::size_of::<Self>()];
490                    for i in 0..bytes.len() {
491                        bytes[i] = reader.read_u8()?;
492                    }
493                    Ok(Self::from_bits(<$uint_t>::from_le_bytes(bytes)))
494                }
495            }
496        )*
497    };
498}
499
500impl_data_value!(int:
501    (u8, ComponentDataType::U8),
502    (u16, ComponentDataType::U16),
503    (u32, ComponentDataType::U32),
504    (u64, ComponentDataType::U64),
505    (i8, ComponentDataType::I8),
506    (i16, ComponentDataType::I16),
507    (i32, ComponentDataType::I32),
508    (i64, ComponentDataType::I64)
509);
510
511impl_data_value!(float:
512    (f32, u32, ComponentDataType::F32),
513    (f64, u64, ComponentDataType::F64)
514);
515
516/// An array of `N` elements of type `T`, where `T` is often a [DataValue],
517/// which is a trait that defines the basic mathematical operations
518/// and properties for the elements of the vector. This means that
519/// `NdVector` can be used to represent vectors in `N`-dimensional space (or a free module)
520///  over `T`. The vector operations for this type are implemented on a static basis,
521/// meaning that the operations are defined for a fixed number of dimensions at compile time
522/// without looping over `N` elements.
523#[derive(Clone, Copy)]
524pub struct NdVector<const N: usize, T> {
525    data: [T; N],
526}
527
528impl<const N: usize, T: Float> NdVector<N, T> {
529    pub fn normalize(self) -> Self {
530        let mut out = self;
531        let norm_inverse = T::one() / self.norm();
532        for i in 0..N {
533            unsafe {
534                *out.data.get_unchecked_mut(i) *= norm_inverse;
535            }
536        }
537        out
538    }
539
540    pub fn norm(self) -> T {
541        let mut norm = T::zero();
542        for i in 0..N {
543            unsafe {
544                norm += *self.data.get_unchecked(i) * *self.data.get_unchecked(i);
545            }
546        }
547        norm.sqrt()
548    }
549}
550
551impl<const N: usize, T> From<[T; N]> for NdVector<N, T> {
552    fn from(data: [T; N]) -> Self {
553        NdVector { data }
554    }
555}
556
557impl<const N: usize, T> fmt::Debug for NdVector<N, T>
558where
559    T: fmt::Debug,
560{
561    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562        write!(f, "{:?}", self.data)
563    }
564}
565
566impl<const N: usize, T> From<NdVector<N, T>> for serde_json::Value
567where
568    [T; N]: Into<serde_json::Value>,
569{
570    fn from(vector: NdVector<N, T>) -> Self {
571        vector.data.into()
572    }
573}
574
575use crate::prelude::{ByteReader, ByteWriter};
576use crate::shared::attribute::Portable;
577use std::ops::Index;
578use std::ops::IndexMut;
579impl_ndvector_ops!();
580
581pub trait Vector<const N: usize>:
582    Clone
583    + Copy
584    + fmt::Debug
585    + PartialEq
586    + Into<serde_json::Value>
587    + ops::Add<Output = Self>
588    + ops::Sub<Output = Self>
589    + ops::Mul<Self::Component, Output = Self>
590    + ops::Div<Self::Component, Output = Self>
591    + ops::AddAssign
592    + ops::SubAssign
593    + ops::Mul<Self::Component, Output = Self>
594    + ops::Div<Self::Component, Output = Self>
595    + ElementWiseMul<Output = Self>
596    + ElementWiseDiv<Output = Self>
597    + Dot<Product = Self::Component>
598    + Cross
599{
600    type Component: DataValue;
601    fn zero() -> Self;
602    fn get(&self, index: usize) -> &Self::Component;
603    fn get_mut(&mut self, index: usize) -> &mut Self::Component;
604    unsafe fn get_unchecked(&self, index: usize) -> &Self::Component;
605    unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut Self::Component;
606}
607
608pub trait Dot {
609    type Product;
610    fn dot(self, other: Self) -> Self::Product;
611}
612
613pub trait Cross {
614    fn cross(self, other: Self) -> Self;
615}
616
617pub trait ElementWiseMul<Rhs = Self> {
618    type Output;
619    fn elem_mul(self, other: Rhs) -> Self::Output;
620}
621
622pub trait ElementWiseDiv<Rhs = Self> {
623    type Output;
624    fn elem_div(self, other: Rhs) -> Self::Output;
625}
626
627impl<const N: usize, T> Cross for NdVector<N, T>
628where
629    T: DataValue,
630{
631    fn cross(self, other: Self) -> Self {
632        if N == 3 {
633            unsafe {
634                let mut out = [T::zero(); N];
635                *out.get_unchecked_mut(0) = *self.data.get_unchecked(1)
636                    * *other.data.get_unchecked(2)
637                    - *self.data.get_unchecked(2) * *other.data.get_unchecked(1);
638                *out.get_unchecked_mut(1) = *self.data.get_unchecked(2)
639                    * *other.data.get_unchecked(0)
640                    - *self.data.get_unchecked(0) * *other.data.get_unchecked(2);
641                *out.get_unchecked_mut(2) = *self.data.get_unchecked(0)
642                    * *other.data.get_unchecked(1)
643                    - *self.data.get_unchecked(1) * *other.data.get_unchecked(0);
644                NdVector { data: out }
645            }
646        } else {
647            unreachable!("Cross product is only defined for 3D vectors")
648        }
649    }
650}
651
652#[cfg(test)]
653mod tests {
654    use super::*;
655
656    #[test]
657    fn test_ndvector_add() {
658        let vector1 = NdVector {
659            data: [1.0, 2.0, 3.0],
660        };
661        let vector2 = NdVector {
662            data: [4.0, 5.0, 6.0],
663        };
664        let result: NdVector<3, f32> = vector1 + vector2;
665        assert_eq!(result.data, [5.0, 7.0, 9.0]);
666    }
667
668    #[test]
669    fn test_ndvector_sub() {
670        let vector1 = NdVector {
671            data: [4.0, 5.0, 6.0],
672        };
673        let vector2 = NdVector {
674            data: [1.0, 2.0, 3.0],
675        };
676        let result: NdVector<3, f32> = vector1 - vector2;
677        assert_eq!(result.data, [3.0, 3.0, 3.0]);
678    }
679
680    #[test]
681    fn test_ndvector_dot() {
682        let vector1 = NdVector {
683            data: [1_f64, 2.0, 3.0],
684        };
685        let vector2 = NdVector {
686            data: [4.0, 5.0, 6.0],
687        };
688        let result = vector1.dot(vector2);
689        assert_eq!(result, 32.0);
690    }
691
692    #[test]
693    fn test_ndvector_elem_mul() {
694        let vector1 = NdVector {
695            data: [1.0, 2.0, 3.0],
696        };
697        let vector2 = NdVector {
698            data: [4.0, 5.0, 6.0],
699        };
700        let result = vector1.elem_mul(vector2);
701        assert_eq!(result.data, [4.0, 10.0, 18.0]);
702    }
703
704    #[test]
705    fn test_ndvector_elem_div() {
706        let vector1 = NdVector {
707            data: [4.0, 10.0, 18.0, 2.0],
708        };
709        let vector2 = NdVector {
710            data: [2.0, 5.0, 3.0, 4.0],
711        };
712        let result = vector1.elem_div(vector2);
713        assert_eq!(result.data, [2.0, 2.0, 6.0, 0.5]);
714    }
715}