zmatrix 0.4.0

Compile-time dimensional analysis & physics-aware linear algebra for aerospace and robotics
Documentation
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
//! 物理量系统:25 种物理量及其量纲安全运算。
//!
//! # 物理量与裸 `f64` 的运算
//!
//! `X + f64`、`X - f64`、`X * f64`、`X / f64` 这类实现,语义都是:
//! **裸数直接作用于物理量的内部存储值,按其当前单位理解,不做任何单位换算。**
//!
//! 这是**有意设计**,不是缺陷。`f64` 自身不带单位,库无从判断它代表 1 m 还是 1 km;
//! 若擅自按基准单位换算,等于替调用方做了一个它并未表达的假设。
//!
//! ```
//! use zmatrix::physics::basic::Distance;
//!
//! // 由 from_km 构造:内部单位是 km,+ 1.0 即在 km 上加 1
//! let a = Distance::from_km(1.0) + 1.0;
//! // 由 from_m 构造:内部单位是 m,+ 1.0 即在 m 上加 1
//! let b = Distance::from_m(1000.0) + 1.0;
//!
//! assert_eq!(a.as_km(), 2.0);
//! assert_eq!(b.as_m(), 1001.0);
//! ```
//!
//! 注意 `a` 与 `b` 在加 `1.0` **之前**是相等的(都是 1000 m),加完之后不等。
//! 这就是"裸数与物理量混算"必须付出的代价 —— 单位信息在运算符里丢失了。
//!
//! **需要单位安全时,请让两个物理量直接运算**,把单位写进类型:
//!
//! ```
//! use zmatrix::physics::basic::Distance;
//!
//! let a = Distance::from_km(1.0);
//! let b = Distance::from_m(1000.0);
//! let c = a + b;                  // 由编译器统一换算到 m,再相加
//!
//! assert_eq!(c.as_m(), 2000.0);
//! ```
//!
//! 判定口径:只要参与运算的两侧有一侧是裸数,就没有单位保证;
//! 两侧都是物理量时,单位由类型系统负责。

use std::any::Any;
use std::fmt::{Display, Formatter};
use std::ops::Div;

mod acceleration;
mod angular;
mod angular_acceleration;
mod angular_momentum;
mod angular_velocity;
mod area;
mod coef;
mod distance;
mod electric_capacitance;
mod electric_charge;
mod electric_conductance;
mod electric_current;
mod electric_potential;
mod electric_resistance;
mod energy;
mod force;
mod magnetic_angular_velocity;
mod magnetic_induction;
mod magnetic_moment;
pub mod mass;
mod momentum;
mod power;
mod torque;
pub mod vector;
mod velocity;
mod volume;

//支持向量的物理量
pub trait VectorQuantity: PhysicalQuantity {}

pub trait PhysicalQuantity: Any {
    fn as_any(&self) -> &dyn Any;

    fn is_zero(&self) -> bool;

    fn default_unit_value(&self) -> f64;

    fn set_value(&mut self, value: f64);

    /// 返回物理量名称和单位,如 "Distance (m)", "Velocity (m/s)"
    fn unit_display_name(&self) -> String;
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DistanceType {
    M,
    KM,
    LightYear,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VelocityType {
    MPerSecond,
    KmPerHour,
    KmPerSecond,
    LightSpeed,
}
/// 距离物理量结构体
///
/// 表示空间中的距离,支持多种单位制
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Distance;
///
/// let distance = Distance::from_m(100.0);
/// println!("距离: {} 米", distance.as_m());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Distance {
    default_type: DistanceType,
    v: f64,
}

/// 速度物理量结构体
///
/// 表示物体运动的快慢和方向,支持多种单位制
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Velocity;
///
/// let velocity = Velocity::from_m_per_sec(10.0);
/// println!("速度: {} m/s", velocity.as_m_per_sec());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Velocity {
    default_type: VelocityType,
    v: f64,
}


/// 加速度物理量结构体
///
/// 表示速度变化的快慢,支持多种单位制
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Acceleration;
///
/// let acceleration = Acceleration::from_g(1.0);
/// println!("加速度: {} g", acceleration.as_g());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Acceleration {
    default_type: AccelerationType,
    v: f64,
}

#[derive(Clone, Debug, PartialEq, Copy)]
pub enum AccelerationType {
    MPerSecond2,
    KmPerHour2,
    G,
}

#[derive(Clone, Debug, PartialEq, Copy)]
pub enum AngularType {
    Rad,
    Deg,
}

/// 角度物理量结构体
///
/// 表示角度大小,支持弧度和度数单位
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Angular;
///
/// let angle = Angular::from_rad(std::f64::consts::PI);
/// println!("角度: {} 弧度", angle.as_rad());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Angular {
    default_type: AngularType,
    v: f64,
}

#[derive(Clone, Debug, PartialEq, Copy, Default)]
pub enum AngularVelocityType {
    #[default]
    RadperSecond,
    DegPerSecond,
    RadperHour,
    DegperHour,
}

/// 角速度物理量结构体
///
/// 表示角度变化的快慢,支持多种单位制
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::AngularVelocity;
///
/// let angular_velocity = AngularVelocity::from_rad_per_second(1.0);
/// println!("角速度: {} rad/s", angular_velocity.as_rad_per_second());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct AngularVelocity {
    default_type: AngularVelocityType,
    v: f64,
}


#[derive(Clone, Debug, PartialEq, Copy)]
pub enum AngularAccelerationType {
    RadperSecond2,
    DegPerSecond2,
}

/// 角加速度物理量结构体
///
/// 表示角速度变化的快慢,支持多种单位制
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::AngularAcceleration;
///
/// let angular_acceleration = AngularAcceleration::from_rad_per_second2(1.0);
/// println!("角加速度: {} rad/s²", angular_acceleration.as_rad_per_second2());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct AngularAcceleration {
    default_type: AngularAccelerationType,
    v: f64,
}

/// 系数物理量结构体
///
/// 表示无量纲的系数或比例因子
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Coef;
///
/// let coefficient = Coef::new(0.5);
/// println!("系数: {}", coefficient.get_value());
/// ```
#[derive(Clone, Debug, PartialEq, PartialOrd, Copy)]
pub struct Coef {
    v: f64,
}

#[derive(Clone, Debug, PartialEq, Copy)]
pub enum MassType {
    Kg,
    g,
}

/// 质量物理量结构体
///
/// 表示物体的质量,支持千克和克单位
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Mass;
///
/// let mass = Mass::from_kg(1.0);
/// println!("质量: {} kg", mass.as_kg());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Mass {
    default_type: MassType,
    pub v: f64,
}

#[derive(Clone, Debug, PartialEq, Copy)]
pub enum AngularMomentumType {
    KgM2perSecond,  // 每秒1千克1平方米
    KgKm2perSecond, // 每秒1千克1平方公里
    Nms,            // 牛顿·米·秒 (N·m·s)
    MillNms,        // 毫牛顿·米·秒 (mN·m·s)
    MicroNms,       // 微牛顿·米·秒 (μN·m·s)
    NanoNms,        // 纳牛顿·米·秒 (nN·m·s)
}
/// 角动量物理量结构体
///
/// 表示物体绕轴旋转的动量,是质量、速度和距离的乘积
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::AngularMomentum;
///
/// let angular_momentum = AngularMomentum::from_kg_m2_per_second(1.0);
/// println!("角动量: {} kg·m²/s", angular_momentum.as_kg_m2_per_second());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct AngularMomentum {
    default_type: AngularMomentumType,
    pub v: f64,
}

#[derive(Clone, Debug, PartialEq, Copy)]
pub enum MomentumType {
    KgMperSecond,  // 每秒1千克1米
    KgKmperSecond, // 每秒1千克1千米
}
/// 动量物理量结构体
///
/// 表示物体运动的动量,是质量和速度的乘积
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Momentum;
///
/// let momentum = Momentum::from_kg_m_s(1.0);
/// println!("动量: {} kg·m/s", momentum.as_kg_m_s());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Momentum {
    default_type: MomentumType,
    pub v: f64,
}


/// 三维向量结构体
///
/// 表示三维空间中的向量,包含x、y、z三个分量
///
/// # 类型参数
/// * `T` - 向量分量的物理量类型,必须实现 `VectorQuantity` 和 `Default` trait
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::{Vector3, Distance};
///
/// let position = Vector3 {
///     x: Distance::from_m(1.0),
///     y: Distance::from_m(2.0),
///     z: Distance::from_m(3.0),
/// };
/// println!("位置: ({}, {}, {})", position.x.as_m(), position.y.as_m(), position.z.as_m());
/// ```
#[derive(Clone, Debug, PartialEq, Copy)]
pub struct Vector3<T: VectorQuantity + Default> {
    pub x: T,
    pub y: T,
    pub z: T,
}

impl<T: VectorQuantity + Default + Display> Display for Vector3<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "({}, {}, {})", self.x, self.y, self.z)
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AreaType {
    M2,
    KM2,
}

/// 面积物理量结构体
///
/// 表示二维空间的面积大小,支持平方米和平方千米单位
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Area;
///
/// let area = Area::from_m2(100.0);
/// println!("面积: {} m²", area.as_m2());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Area {
    default_type: AreaType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum MagneticInductionType {
    Gauss,
    #[default]
    Tesla,
    MillTesla,  // 毫
    MicroTesla, // 微
    NanoTesla,  //; 纳
    MillGauss,  // 毫
    KiloGauss,  // 千
}
/// 磁感应强度物理量结构体
///
/// 表示磁场强度,单位是特斯拉或高斯
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::MagneticInduction;
///
/// let magnetic_field = MagneticInduction::from_tesla(1.0);
/// println!("磁感应强度: {} T", magnetic_field.as_tesla());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MagneticInduction {
    default_type: MagneticInductionType,
    pub v: f64,
}


#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MagneticMomentType {
    AM2,            // 安培·平方米 (A·m²)
    MillAM2,        // 毫安培·平方米 (mA·m²)
    MicroAM2,       // 微安培·平方米 (μA·m²)
    NanoAM2,        // 纳安培·平方米 (nA·m²)
    JPerTesla,      // 焦耳/特斯拉 (J/T)
    MillJPerTesla,  // 毫焦耳/特斯拉 (mJ/T)
    MicroJPerTesla, // 微焦耳/特斯拉 (μJ/T)
    NanoJPerTesla,  // 纳焦耳/特斯拉 (nJ/T)
}

/// 磁矩物理量结构体
///
/// 表示磁偶极子的磁矩,单位是安培·平方米或焦耳/特斯拉
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::MagneticMoment;
///
/// let magnetic_moment = MagneticMoment::from_am2(1.0);
/// println!("磁矩: {} A·m²", magnetic_moment.as_am2());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MagneticMoment {
    default_type: MagneticMomentType,
    pub v: f64,
}


#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TorqueType {
    NM,      // 牛顿·米 (N·m)
    MillNM,  // 毫牛顿·米 (mN·m)
    MicroNM, // 微牛顿·米 (μN·m)
    NanoNM,  // 纳牛顿·米 (nN·m)
    KNM,     // 千牛顿·米 (kN·m)
    MNM,     // 兆牛顿·米 (MN·m)
}

/// 力矩物理量结构体
///
/// 表示力对物体产生的转动效应,单位是牛顿·米
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Torque;
///
/// let torque = Torque::from_nm(10.0);
/// println!("力矩: {} N·m", torque.as_nm());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Torque {
    default_type: TorqueType,
    pub v: f64,
}


#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EnergyType {
    Joule,            // 焦耳 (J)
    MillJoule,        // 毫焦耳 (mJ)
    MicroJoule,       // 微焦耳 (μJ)
    NanoJoule,        // 纳焦耳 (nJ)
    KiloJoule,        // 千焦耳 (kJ)
    MegaJoule,        // 兆焦耳 (MJ)
    ElectronVolt,     // 电子伏特 (eV)
    KiloElectronVolt, // 千电子伏特 (keV)
    MegaElectronVolt, // 兆电子伏特 (MeV)
}

/// 能量物理量结构体
///
/// 表示物体做功的能力,单位是焦耳
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Energy;
///
/// let energy = Energy::from_joule(100.0);
/// println!("能量: {} J", energy.as_joule());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Energy {
    default_type: EnergyType,
    pub v: f64,
}


#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ForceType {
    Newton,      // 牛顿 (N)
    MillNewton,  // 毫牛顿 (mN)
    MicroNewton, // 微牛顿 (μN)
    NanoNewton,  // 纳牛顿 (nN)
    KiloNewton,  // 千牛顿 (kN)
    MegaNewton,  // 兆牛顿 (MN)
}

/// 力物理量结构体
///
/// 表示物体间的相互作用,单位是牛顿
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Force;
///
/// let force = Force::from_newton(10.0);
/// println!("力: {} N", force.as_newton());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Force {
    default_type: ForceType,
    pub v: f64,
}


#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PowerType {
    Watt,       // 瓦特 (W)
    MillWatt,   // 毫瓦特 (mW)
    MicroWatt,  // 微瓦特 (μW)
    NanoWatt,   // 纳瓦特 (nW)
    KiloWatt,   // 千瓦特 (kW)
    MegaWatt,   // 兆瓦特 (MW)
    HorsePower, // 马力 (hp)
}

/// 功率物理量结构体
///
/// 表示单位时间内做功的多少,单位是瓦特
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Power;
///
/// let power = Power::from_watt(100.0);
/// println!("功率: {} W", power.as_watt());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Power {
    default_type: PowerType,
    pub v: f64,
}


#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MagneticAngularVelocityType {
    TeslaRadPerSecond,      // 特斯拉·弧度/秒 (T·rad/s)
    MillTeslaRadPerSecond,  // 毫特斯拉·弧度/秒 (mT·rad/s)
    MicroTeslaRadPerSecond, // 微特斯拉·弧度/秒 (μT·rad/s)
    NanoTeslaRadPerSecond,  // 纳特斯拉·弧度/秒 (nT·rad/s)
    GaussRadPerSecond,      // 高斯·弧度/秒 (G·rad/s)
    MillGaussRadPerSecond,  // 毫高斯·弧度/秒 (mG·rad/s)
    KiloGaussRadPerSecond,  // 千高斯·弧度/秒 (kG·rad/s)
}

/// 磁角速度物理量结构体
///
/// 表示磁场中的角速度,单位是特斯拉·弧度/秒或高斯·弧度/秒
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::MagneticAngularVelocity;
///
/// let magnetic_angular_velocity = MagneticAngularVelocity::from_tesla_rad_per_second(1.0);
/// println!("磁角速度: {} T·rad/s", magnetic_angular_velocity.as_tesla_rad_per_second());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MagneticAngularVelocity {
    default_type: MagneticAngularVelocityType,
    pub v: f64,
}


#[derive(Clone, Debug, PartialEq, Copy)]
pub enum VolumeType {
    M3,
    KM3,
}
/// 体积物理量结构体
///
/// 表示三维空间的体积大小,支持立方米和立方千米单位
///
/// # 示例
/// ```
/// use zmatrix::physics::basic::Volume;
///
/// let volume = Volume::from_m3(1000.0);
/// println!("体积: {} m³", volume.as_m3());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Volume {
    default_type: VolumeType,
    pub v: f64,
}

// ── 电学物理量 ───────────────────────────────────────────────────────────────

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ElectricCurrentType {
    A,
    MilliA,
    MicroA,
    KiloA,
}

/// 电流物理量结构体
///
/// 表示电荷流动的速率,单位是安培 (A)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ElectricCurrent {
    default_type: ElectricCurrentType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ElectricPotentialType {
    V,
    MilliV,
    MicroV,
    KiloV,
}

/// 电压(电势差)物理量结构体
///
/// 表示两点间的电势差,单位是伏特 (V)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ElectricPotential {
    default_type: ElectricPotentialType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ElectricResistanceType {
    Ohm,
    MillOhm,
    KiloOhm,
    MegaOhm,
}

/// 电阻物理量结构体
///
/// 表示导体对电流的阻碍能力,单位是欧姆 (Ω)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ElectricResistance {
    default_type: ElectricResistanceType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ElectricChargeType {
    Coulomb,
    MilliCoulomb,
    MicroCoulomb,
    NanoCoulomb,
}

/// 电荷量物理量结构体
///
/// 表示物体所带的电荷量,单位是库仑 (C)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ElectricCharge {
    default_type: ElectricChargeType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ElectricCapacitanceType {
    Farad,
    MilliFarad,
    MicroFarad,
    NanoFarad,
    PicoFarad,
}

/// 电容物理量结构体
///
/// 表示存储电荷的能力,单位是法拉 (F)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ElectricCapacitance {
    default_type: ElectricCapacitanceType,
    pub v: f64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ElectricConductanceType {
    Siemens,
    MilliSiemens,
    MicroSiemens,
}

/// 电导物理量结构体
///
/// 表示导体导电的能力(电阻的倒数),单位是西门子 (S)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ElectricConductance {
    default_type: ElectricConductanceType,
    pub v: f64,
}


impl Default for Distance {
    fn default() -> Self {
        Distance::from_m(0.0)
    }
}

impl PhysicalQuantity for Distance {
    fn as_any(&self) -> &dyn Any {
        self
}
    fn is_zero(&self) -> bool {
        self.v == 0.0
    }

    fn default_unit_value(&self) -> f64 {
        self.as_m()
    }

    fn set_value(&mut self, value: f64) {
        self.v = value;
    }
    fn unit_display_name(&self) -> String {
        "Distance (m)".to_string()
    }
}

impl Default for Angular {
    fn default() -> Self {
        Angular::from_rad(0.0)
    }
}

impl PhysicalQuantity for Angular {
    fn as_any(&self) -> &dyn Any {
        self
}
    fn is_zero(&self) -> bool {
        self.v == 0.0
    }
    fn default_unit_value(&self) -> f64 {
        self.as_rad()
    }

    fn set_value(&mut self, value: f64) {
        self.v = value;
    }
    fn unit_display_name(&self) -> String {
        "Angular (rad)".to_string()
    }
}

impl Default for AngularVelocity {
    fn default() -> Self {
        AngularVelocity::from_rad_per_second(0.0)
    }
}

impl Div for AngularMomentum {
    type Output = Coef;
    fn div(self, rhs: Self) -> Self::Output {
        let v = self.default_unit_value() / rhs.default_unit_value();
        Coef::new(v)
    }
}

impl Default for Coef {
    fn default() -> Self {
        Coef::new(1.0)
    }
}

impl Default for AngularAcceleration {
    fn default() -> Self {
        AngularAcceleration::from_rad_per_second2(0.0)
    }
}

impl<T: VectorQuantity + Default> Default for Vector3<T> {
    fn default() -> Self {
        Vector3 {
            x: T::default(),
            y: T::default(),
            z: T::default(),
        }
    }
}

/// 从 f64 秒数创建 chrono::TimeDelta(支持负数)
pub fn time_delta_from_secs_f64(secs: f64) -> chrono::TimeDelta {
    let nanos = (secs * 1_000_000_000.0) as i64;
    chrono::TimeDelta::nanoseconds(nanos)
}

/// 将 chrono::TimeDelta 转换为 f64 秒数
pub fn time_delta_to_secs_f64(td: &chrono::TimeDelta) -> f64 {
    td.num_seconds() as f64 + td.subsec_nanos() as f64 * 1e-9
}


// Display impls for physical quantities — show f64 value only (unit is available via unit_display_name)

// Display impls for physical quantities — show f64 value (unit available via unit_display_name)
macro_rules! impl_display_physics {
    ($type:ty) => {
        impl std::fmt::Display for $type {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", self.default_unit_value())
            }
        }
    };
}

impl_display_physics!(Distance);
impl_display_physics!(Velocity);
impl_display_physics!(Acceleration);
impl_display_physics!(Angular);
impl_display_physics!(AngularVelocity);
impl_display_physics!(AngularAcceleration);
impl_display_physics!(Coef);
impl_display_physics!(Mass);
impl_display_physics!(Momentum);
impl_display_physics!(AngularMomentum);
impl_display_physics!(Area);
impl_display_physics!(Volume);
impl_display_physics!(MagneticInduction);
impl_display_physics!(MagneticMoment);
impl_display_physics!(Torque);
impl_display_physics!(Energy);
impl_display_physics!(Force);
impl_display_physics!(Power);
impl_display_physics!(MagneticAngularVelocity);
impl_display_physics!(ElectricCurrent);
impl_display_physics!(ElectricPotential);
impl_display_physics!(ElectricResistance);
impl_display_physics!(ElectricCharge);
impl_display_physics!(ElectricCapacitance);
impl_display_physics!(ElectricConductance);
#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;
    #[test]
    fn test_as_any() {
        let g: &dyn PhysicalQuantity = &Acceleration::from_g(1.23);
        let _d = g.as_any().downcast_ref::<Acceleration>().unwrap();

        let g: &dyn PhysicalQuantity = &Area::from_m2(10.0);
        let _d = g.as_any().downcast_ref::<Area>().unwrap();

        let g: &dyn PhysicalQuantity = &Distance::from_m(10.0);
        let d = g.as_any().downcast_ref::<Distance>().unwrap();
        assert_eq!(d.default_type, DistanceType::M);

        let g: &dyn PhysicalQuantity = &Velocity::from_m_per_sec(10.0);
        let d = g.as_any().downcast_ref::<Velocity>().unwrap();
        assert_eq!(d.default_type, VelocityType::MPerSecond);

        let g: &dyn PhysicalQuantity = &Acceleration::from_g(1.23);
        let d = g.as_any().downcast_ref::<Acceleration>().unwrap();
        assert_eq!(d.default_type, AccelerationType::G);

        let g: &dyn PhysicalQuantity = &Angular::from_rad(1.23);
        let d = g.as_any().downcast_ref::<Angular>().unwrap();
        assert_eq!(d.default_type, AngularType::Rad);

        let g: &dyn PhysicalQuantity = &AngularVelocity::from_rad_per_hour(1.23);
        let d = g.as_any().downcast_ref::<AngularVelocity>().unwrap();
        assert_eq!(d.default_type, AngularVelocityType::RadperHour);

        let g: &dyn PhysicalQuantity = &Coef::new(1.23);
        let d = g.as_any().downcast_ref::<Coef>().unwrap();
        assert_eq!(d.v, 1.23);

        let g: &dyn PhysicalQuantity = &AngularAcceleration::from_rad_per_second2(1.23);
        let d = g.as_any().downcast_ref::<AngularAcceleration>().unwrap();
        assert_eq!(d.default_type, AngularAccelerationType::RadperSecond2);
    }

    #[test]
    fn test_acceleration_default() {
        let a = Acceleration::default();
        assert_eq!(0.0, a.as_m_per_s2());
    }

    #[test]
    fn test_angular_velocity_default() {
        let a = AngularVelocity::default();
        assert_eq!(0.0, a.as_rad_per_hour());

        let a = AngularAcceleration::default();
        assert_eq!(0.0, a.as_rad_per_second2());
    }

    #[test]
    fn test_angular_is_zero() {
        let a = Angular::from_rad(0.0);
        assert_eq!(true, a.is_zero());
        let a = Angular::from_rad(1.0);
        assert_eq!(false, a.is_zero());
    }

    #[test]
    fn test_volume_clone() {
        let a = Volume::from_m3(3.8);
        let b = a.clone();
        assert_relative_eq!(a.as_km3(), b.as_km3(), epsilon = 1e-8);
    }

    #[test]
    fn test_magnetic_moment_as_any() {
        let g: &dyn PhysicalQuantity = &MagneticMoment::from_am2(1.23);
        let d = g.as_any().downcast_ref::<MagneticMoment>().unwrap();
        assert_eq!(d.default_type, MagneticMomentType::AM2);
    }

    #[test]
    fn test_magnetic_moment_default() {
        let mm = MagneticMoment::default();
        assert_eq!(0.0, mm.as_am2());
    }

    #[test]
    fn test_magnetic_moment_is_zero() {
        let mm = MagneticMoment::from_am2(0.0);
        assert_eq!(true, mm.is_zero());
        let mm = MagneticMoment::from_am2(1.0);
        assert_eq!(false, mm.is_zero());
    }

    #[test]
    fn test_torque_as_any() {
        let g: &dyn PhysicalQuantity = &Torque::from_nm(1.23);
        let d = g.as_any().downcast_ref::<Torque>().unwrap();
        assert_eq!(d.default_type, TorqueType::NM);
    }

    #[test]
    fn test_torque_default() {
        let t = Torque::default();
        assert_eq!(0.0, t.as_nm());
    }

    #[test]
    fn test_torque_is_zero() {
        let t = Torque::from_nm(0.0);
        assert_eq!(true, t.is_zero());
        let t = Torque::from_nm(1.0);
        assert_eq!(false, t.is_zero());
    }

    #[test]
    fn test_energy_as_any() {
        let g: &dyn PhysicalQuantity = &Energy::from_joule(1.23);
        let d = g.as_any().downcast_ref::<Energy>().unwrap();
        assert_eq!(d.default_type, EnergyType::Joule);
    }

    #[test]
    fn test_energy_default() {
        let e = Energy::default();
        assert_eq!(0.0, e.as_joule());
    }

    #[test]
    fn test_energy_is_zero() {
        let e = Energy::from_joule(0.0);
        assert_eq!(true, e.is_zero());
        let e = Energy::from_joule(1.0);
        assert_eq!(false, e.is_zero());
    }

    #[test]
    fn test_angular_default_unit_value_is_rad() {
        // 默认单位为弧度时,default_unit_value 应等于 as_rad()
        let a_rad = Angular::from_rad(std::f64::consts::PI);
        assert_relative_eq!(a_rad.default_unit_value(), a_rad.as_rad(), epsilon = 1e-12);

        // 默认单位为度时,default_unit_value 也应返回弧度
        let a_deg = Angular::from_deg(180.0);
        assert_relative_eq!(a_deg.default_unit_value(), a_deg.as_rad(), epsilon = 1e-12);

        // 随机值覆盖(包括负值和小数),确保统一弧度输出
        let cases = vec![
            -720.0, -360.0, -45.5, 0.0, 12.34, 90.0, 123.456, 360.0, 720.0,
        ];
        for deg in cases {
            let a = Angular::from_deg(deg);
            assert_relative_eq!(a.default_unit_value(), a.as_rad(), epsilon = 1e-12);
        }
    }

    #[test]
    fn test_unit_display_name_and_display() {
        // 验证所有物理量的 unit_display_name 与 Display 实现

        assert_eq!(Distance::from_m(1.5).unit_display_name(), "Distance (m)");
        assert_eq!(format!("{}", Distance::from_m(2.5)), "2.5");

        assert_eq!(Velocity::from_m_per_sec(3.0).unit_display_name(), "Velocity (m/s)");
        assert_eq!(format!("{}", Velocity::from_km_per_h(36.0)), "10");

        assert_eq!(Acceleration::from_m_per_s2(9.8).unit_display_name(), "Acceleration (m/s²)");
        assert_eq!(format!("{}", Acceleration::from_g(1.0)), format!("{}", 9.80665));

        assert_eq!(Angular::from_rad(1.0).unit_display_name(), "Angular (rad)");
        assert_eq!(format!("{}", Angular::from_deg(180.0)), format!("{}", std::f64::consts::PI));

        assert_eq!(AngularVelocity::from_rad_per_second(2.0).unit_display_name(), "AngularVelocity (rad/s)");
        assert_eq!(format!("{}", AngularVelocity::from_rad_per_second(2.0)), "2");

        assert_eq!(AngularAcceleration::from_rad_per_second2(1.0).unit_display_name(), "AngularAcceleration (rad/s²)");
        assert_eq!(format!("{}", AngularAcceleration::from_rad_per_second2(3.0)), "3");

        assert_eq!(Coef::new(3.14).unit_display_name(), "Coef");
        assert_eq!(format!("{}", Coef::new(3.14)), "3.14");

        assert_eq!(Mass::from_kg(1.0).unit_display_name(), "Mass (kg)");
        assert_eq!(format!("{}", Mass::from_kg(5.0)), "5");

        assert_eq!(Momentum::from_kg_m_s(10.0).unit_display_name(), "Momentum (kg·m/s)");
        assert_eq!(format!("{}", Momentum::from_kg_m_s(10.0)), "10");

        assert_eq!(AngularMomentum::from_kg_m2_per_second(100.0).unit_display_name(), "AngularMomentum (kg·m²/s)");
        assert_eq!(format!("{}", AngularMomentum::from_nms(50.0)), "50");

        assert_eq!(Area::from_m2(4.0).unit_display_name(), "Area (m²)");
        assert_eq!(format!("{}", Area::from_m2(12.0)), "12");

        assert_eq!(Volume::from_m3(8.0).unit_display_name(), "Volume (m³)");
        assert_eq!(format!("{}", Volume::from_m3(8.0)), "8");

        assert_eq!(MagneticInduction::from_tesla(1.0).unit_display_name(), "MagneticInduction (T)");
        assert_eq!(format!("{}", MagneticInduction::from_gauss(10000.0)), "1");

        assert_eq!(MagneticMoment::from_am2(1.0).unit_display_name(), "MagneticMoment (A·m²)");
        assert_eq!(format!("{}", MagneticMoment::from_am2(2.0)), "2");

        assert_eq!(Torque::from_nm(10.0).unit_display_name(), "Torque (N·m)");
        assert_eq!(format!("{}", Torque::from_nm(0.0)), "0");

        assert_eq!(Energy::from_joule(42.0).unit_display_name(), "Energy (J)");
        assert_eq!(format!("{}", Energy::from_joule(0.0)), "0");

        assert_eq!(Force::from_newton(100.0).unit_display_name(), "Force (N)");
        assert_eq!(format!("{}", Force::from_newton(100.0)), "100");

        assert_eq!(Power::from_watt(60.0).unit_display_name(), "Power (W)");
        assert_eq!(format!("{}", Power::from_watt(60.0)), "60");

        assert_eq!(MagneticAngularVelocity::from_tesla_rad_per_second(1.0).unit_display_name(), "MagneticAngularVelocity (T·rad/s)");
        assert_eq!(format!("{}", MagneticAngularVelocity::from_tesla_rad_per_second(1.0)), "1");

        // 电学物理量
        assert_eq!(ElectricCurrent::from_a(2.5).unit_display_name(), "ElectricCurrent (A)");
        assert_eq!(format!("{}", ElectricCurrent::from_a(2.5)), "2.5");

        assert_eq!(ElectricPotential::from_v(12.0).unit_display_name(), "ElectricPotential (V)");
        assert_eq!(format!("{}", ElectricPotential::from_v(12.0)), "12");

        assert_eq!(ElectricResistance::from_ohm(100.0).unit_display_name(), "ElectricResistance (Ohm)");
        assert_eq!(format!("{}", ElectricResistance::from_ohm(100.0)), "100");

        assert_eq!(ElectricCharge::from_coulomb(5.0).unit_display_name(), "ElectricCharge (C)");
        assert_eq!(format!("{}", ElectricCharge::from_coulomb(5.0)), "5");

        assert_eq!(ElectricCapacitance::from_farad(0.001).unit_display_name(), "ElectricCapacitance (F)");
        assert_eq!(format!("{}", ElectricCapacitance::from_farad(0.001)), "0.001");

        assert_eq!(ElectricConductance::from_siemens(0.01).unit_display_name(), "ElectricConductance (S)");
        assert_eq!(format!("{}", ElectricConductance::from_siemens(0.01)), "0.01");
    }

    #[test]
    fn test_vector3_display() {
        let v: Vector3<Distance> = Vector3::new(
            Distance::from_m(1.0),
            Distance::from_m(2.0),
            Distance::from_m(3.0),
        );
        assert_eq!(format!("{}", v), "(1, 2, 3)");
    }
}

// 手动实现 VectorQuantity trait 给所有支持向量的物理量
impl VectorQuantity for Distance {}
impl VectorQuantity for Velocity {}
impl VectorQuantity for Acceleration {}
impl VectorQuantity for Angular {}
impl VectorQuantity for AngularVelocity {}
impl VectorQuantity for AngularAcceleration {}
impl VectorQuantity for Coef {}
impl VectorQuantity for AngularMomentum {}
impl VectorQuantity for Momentum {}
impl VectorQuantity for MagneticInduction {}
impl VectorQuantity for MagneticMoment {}
impl VectorQuantity for Torque {}
impl VectorQuantity for Force {}
impl VectorQuantity for MagneticAngularVelocity {}