dualis_units/lib.rs
1//! Dimensional analysis: physical quantities that refuse to be added wrongly.
2//!
3//! ```
4//! use dualis_units::{Area, Energy, Length, Mass, Power, SpecificHeat, Temperature, Time};
5//!
6//! // A unit-bearing constructor is the only place a factor of a thousand may appear.
7//! let side = Length::mm(10.0);
8//! let area: Area = side * side; // the dimension follows the product
9//! assert!((area.to_si() - 1e-4).abs() < 1e-18);
10//!
11//! // Absorbed power over a time is an energy, and the type says so without being told.
12//! let absorbed = Power::mw(96.0);
13//! let heat: Energy = absorbed * Time::s(1.0);
14//!
15//! // Divide it by a heat capacity and a temperature comes out.
16//! let capacity = Mass::g(2.0) * SpecificHeat::j_per_kg_k(858.0);
17//! let rise: Temperature = heat / capacity;
18//! assert!((rise.to_si() - 0.05594).abs() < 1e-4);
19//! ```
20//!
21//! And the mistake the whole crate exists to prevent does not compile:
22//!
23//! ```compile_fail
24//! use dualis_units::{Length, Time};
25//! let nonsense = Length::mm(3.0) + Time::s(1.0);
26//! ```
27//!
28//! One domain can get away with a convention. `dualis-core` began as optics and
29//! said "millimetres, nanometres and seconds, everywhere" in a doc comment, and
30//! that held because every number in the crate was a length, a wavelength or a
31//! fraction. It stops holding the moment a second domain arrives: a kelvin, a
32//! newton and a watt are all `f64`, they all add, and the compiler and the tests
33//! both stay green while the physics goes wrong.
34//!
35//! So dimension lives in the type. [`Qty`] carries the seven SI base exponents as
36//! const generic parameters, which makes `Length + Time` a compile error and
37//! `Force * Length` an [`Energy`] — and costs nothing at runtime, since a `Qty`
38//! is an `f64` and every operation on it is the `f64` operation.
39//!
40//! # Storage is always SI base units
41//!
42//! A `Qty` holds metres, kilograms, seconds, amperes, kelvin, moles, candela —
43//! never millimetres, never nanometres. Those are *entry and exit* forms:
44//!
45//! ```
46//! use dualis_units::{Length, Time, Velocity};
47//!
48//! let d = Length::mm(120.0);
49//! let t = Time::ms(4.0);
50//! let v: Velocity = d / t;
51//! assert!((v.to_si() - 30.0).abs() < 1e-12); // 30 m/s
52//! assert!((d.in_nm() - 1.2e8).abs() < 1.0);
53//! ```
54//!
55//! That way there is exactly one representation to reason about, and the
56//! unit-bearing constructors are the only place a factor of 1000 can hide.
57//!
58//! # What this cannot do
59//!
60//! **Angles are dimensionless**, so [`Frequency`] and an angular velocity are the
61//! same type — SI says radians are m/m, and no dimensional system can separate
62//! them. Same for torque and energy. Where that distinction matters, it has to be
63//! carried by a newtype in the domain crate, not here.
64//!
65//! **Only declared products compose.** `Length * Length` is an [`Area`] because
66//! that pair is written down below. Deriving arbitrary products would need
67//! arithmetic on const generic parameters, which is unstable, so the alternative
68//! to a declared list is a dependency on `uom`. The list is cheap to extend, and
69//! anything undeclared can always go through [`Qty::from_si`].
70
71// Every public item carries a doc comment. Denied rather than warned: a public physics API
72// whose `Length::mm` shows a blank summary in rustdoc is documented in the sense that a
73// paragraph exists somewhere, and not in the sense a reader needs.
74#![deny(missing_docs)]
75#![forbid(unsafe_code)]
76
77use core::fmt;
78use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
79
80use serde::{Deserialize, Deserializer, Serialize, Serializer};
81
82pub mod vector;
83pub use vector::{AccelerationVec, ForceVec, LengthVec, MomentumVec, QVec3, VelocityVec};
84
85/// A quantity, with the seven SI base dimensions in its type.
86///
87/// The parameters are the exponents of metre, kilogram, second, ampere, kelvin,
88/// mole and candela, in that order, so a velocity (m·s⁻¹) is `Qty<1,0,-1,0,0,0,0>`
89/// — which is what [`Velocity`] names.
90///
91/// Addition, subtraction, negation, comparison and scaling by a plain `f64` work
92/// for every dimension. Multiplication and division between two quantities work
93/// for the pairs declared in this module.
94#[derive(Clone, Copy, PartialEq, PartialOrd, Default)]
95pub struct Qty<
96 const L: i8,
97 const M: i8,
98 const T: i8,
99 const I: i8,
100 const K: i8,
101 const N: i8,
102 const J: i8,
103>(f64);
104
105impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
106 Qty<L, M, T, I, K, N, J>
107{
108 /// Zero, which is the one value every dimension shares.
109 pub const ZERO: Self = Qty(0.0);
110
111 /// Wrap a number already in SI base units. The escape hatch: use it when a
112 /// dimension has no name here, and name it if you use it twice.
113 ///
114 /// `const`, so a dimensioned constant can be written without a lazy static.
115 pub const fn from_si(value: f64) -> Self {
116 Qty(value)
117 }
118
119 /// The value in SI base units.
120 pub const fn to_si(self) -> f64 {
121 self.0
122 }
123
124 /// The seven exponents, for diagnostics and for a runtime dimension check at
125 /// a boundary the type system does not cross (deserialisation, FFI).
126 pub const fn dimension() -> [i8; 7] {
127 [L, M, T, I, K, N, J]
128 }
129
130 /// Magnitude without its sign, in the same dimension.
131 pub fn abs(self) -> Self {
132 Qty(self.0.abs())
133 }
134
135 /// The smaller of two quantities of the same dimension.
136 pub fn min(self, other: Self) -> Self {
137 Qty(self.0.min(other.0))
138 }
139
140 /// The larger of two quantities of the same dimension.
141 pub fn max(self, other: Self) -> Self {
142 Qty(self.0.max(other.0))
143 }
144
145 /// Whether the magnitude is neither infinite nor NaN.
146 ///
147 /// Worth checking where a limit is reported rather than computed: several methods here
148 /// return an infinity to mean "no limit", which is honest but arithmetic on it is not.
149 pub fn is_finite(self) -> bool {
150 self.0.is_finite()
151 }
152
153 /// Sign of the magnitude, as a plain number — a sign has no dimension.
154 pub fn signum(self) -> f64 {
155 self.0.signum()
156 }
157
158 /// Linear interpolation, which stays within the dimension.
159 pub fn lerp(self, other: Self, t: f64) -> Self {
160 Qty(self.0 + (other.0 - self.0) * t)
161 }
162}
163
164// ---------------------------------------------------------------------------
165// Dimension-preserving arithmetic: works for every dimension at once, because
166// none of it changes the exponents.
167// ---------------------------------------------------------------------------
168
169macro_rules! generic_op {
170 ($trait:ident, $method:ident, $op:tt) => {
171 impl<
172 const L: i8,
173 const M: i8,
174 const T: i8,
175 const I: i8,
176 const K: i8,
177 const N: i8,
178 const J: i8,
179 > $trait for Qty<L, M, T, I, K, N, J>
180 {
181 type Output = Self;
182 fn $method(self, rhs: Self) -> Self {
183 Qty(self.0 $op rhs.0)
184 }
185 }
186 };
187}
188
189generic_op!(Add, add, +);
190generic_op!(Sub, sub, -);
191
192impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
193 AddAssign for Qty<L, M, T, I, K, N, J>
194{
195 fn add_assign(&mut self, rhs: Self) {
196 self.0 += rhs.0;
197 }
198}
199
200impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
201 SubAssign for Qty<L, M, T, I, K, N, J>
202{
203 fn sub_assign(&mut self, rhs: Self) {
204 self.0 -= rhs.0;
205 }
206}
207
208impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8> Neg
209 for Qty<L, M, T, I, K, N, J>
210{
211 type Output = Self;
212 fn neg(self) -> Self {
213 Qty(-self.0)
214 }
215}
216
217impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
218 Mul<f64> for Qty<L, M, T, I, K, N, J>
219{
220 type Output = Self;
221 fn mul(self, k: f64) -> Self {
222 Qty(self.0 * k)
223 }
224}
225
226impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
227 Div<f64> for Qty<L, M, T, I, K, N, J>
228{
229 type Output = Self;
230 fn div(self, k: f64) -> Self {
231 Qty(self.0 / k)
232 }
233}
234
235impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
236 Mul<Qty<L, M, T, I, K, N, J>> for f64
237{
238 type Output = Qty<L, M, T, I, K, N, J>;
239 fn mul(self, q: Qty<L, M, T, I, K, N, J>) -> Qty<L, M, T, I, K, N, J> {
240 Qty(self * q.0)
241 }
242}
243
244/// Dividing two quantities of the *same* dimension gives a plain number — which
245/// is the one product rule that needs no exponent arithmetic, and the one every
246/// tolerance check uses.
247impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8> Div
248 for Qty<L, M, T, I, K, N, J>
249{
250 type Output = f64;
251 fn div(self, rhs: Self) -> f64 {
252 self.0 / rhs.0
253 }
254}
255
256impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
257 fmt::Debug for Qty<L, M, T, I, K, N, J>
258{
259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260 write!(f, "{}", self.0)?;
261 for (symbol, exponent) in [
262 ("m", L),
263 ("kg", M),
264 ("s", T),
265 ("A", I),
266 ("K", K),
267 ("mol", N),
268 ("cd", J),
269 ] {
270 match exponent {
271 0 => {}
272 1 => write!(f, "·{symbol}")?,
273 e => write!(f, "·{symbol}^{e}")?,
274 }
275 }
276 Ok(())
277 }
278}
279
280impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
281 fmt::Display for Qty<L, M, T, I, K, N, J>
282{
283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284 fmt::Debug::fmt(self, f)
285 }
286}
287
288// Serialised as the bare SI number: a scene file stays readable, and the
289// dimension is carried by the field's type rather than repeated in the data.
290impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
291 Serialize for Qty<L, M, T, I, K, N, J>
292{
293 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
294 self.0.serialize(s)
295 }
296}
297
298impl<
299 'de,
300 const L: i8,
301 const M: i8,
302 const T: i8,
303 const I: i8,
304 const K: i8,
305 const N: i8,
306 const J: i8,
307 > Deserialize<'de> for Qty<L, M, T, I, K, N, J>
308{
309 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
310 f64::deserialize(d).map(Qty)
311 }
312}
313
314// ---------------------------------------------------------------------------
315// The dimensions themselves.
316// ---------------------------------------------------------------------------
317
318/// A pure ratio: reflectance, duty cycle, refractive index, Strehl.
319pub type Dimensionless = Qty<0, 0, 0, 0, 0, 0, 0>;
320
321/// Metres.
322pub type Length = Qty<1, 0, 0, 0, 0, 0, 0>;
323/// Kilograms.
324pub type Mass = Qty<0, 1, 0, 0, 0, 0, 0>;
325/// Seconds.
326pub type Time = Qty<0, 0, 1, 0, 0, 0, 0>;
327/// Amperes.
328pub type Current = Qty<0, 0, 0, 1, 0, 0, 0>;
329/// Absolute temperature. Kelvin only — see [`Temperature::celsius`].
330pub type Temperature = Qty<0, 0, 0, 0, 1, 0, 0>;
331/// Moles.
332pub type Amount = Qty<0, 0, 0, 0, 0, 1, 0>;
333/// Candelas.
334pub type LuminousIntensity = Qty<0, 0, 0, 0, 0, 0, 1>;
335
336/// Square metres.
337pub type Area = Qty<2, 0, 0, 0, 0, 0, 0>;
338/// Cubic metres.
339pub type Volume = Qty<3, 0, 0, 0, 0, 0, 0>;
340/// Metres per second.
341pub type Velocity = Qty<1, 0, -1, 0, 0, 0, 0>;
342/// Metres per second squared.
343pub type Acceleration = Qty<1, 0, -2, 0, 0, 0, 0>;
344/// kg·m·s⁻¹ — mass times velocity, and the thing a closed system conserves
345/// exactly rather than nearly.
346pub type Momentum = Qty<1, 1, -1, 0, 0, 0, 0>;
347/// Newtons.
348pub type Force = Qty<1, 1, -2, 0, 0, 0, 0>;
349/// Pascals. Also the unit of an energy density and of a stress, which are the same
350/// dimension and not a coincidence.
351pub type Pressure = Qty<-1, 1, -2, 0, 0, 0, 0>;
352/// Joules.
353pub type Energy = Qty<2, 1, -2, 0, 0, 0, 0>;
354/// Watts.
355pub type Power = Qty<2, 1, -3, 0, 0, 0, 0>;
356/// kg·m⁻³. Note that a glass catalogue quotes g/cm³, a factor of a thousand away —
357/// see [`Density::g_per_cm3`].
358pub type Density = Qty<-3, 1, 0, 0, 0, 0, 0>;
359/// Cycles per second. Dimensionally identical to an angular velocity, since a
360/// radian is m/m — the type system cannot and should not pretend otherwise.
361pub type Frequency = Qty<0, 0, -1, 0, 0, 0, 0>;
362/// Power per unit area, W·m⁻². What a detector face actually receives.
363pub type Irradiance = Qty<0, 1, -3, 0, 0, 0, 0>;
364/// W·m⁻¹·K⁻¹ — the `k` of Fourier's law.
365pub type ThermalConductivity = Qty<1, 1, -3, 0, -1, 0, 0>;
366/// W·K⁻¹ — how fast heat crosses a joint, `UA`.
367///
368/// Dimensionally [`Power`] per [`Temperature`], and equivalently [`ThermalConductivity`] times
369/// a [`Length`], which is the physically meaningful reading: `kA/L`. It is what a *contact*
370/// resistance is measured in — a bolted joint, a winding pressed into a stator — and those have
371/// no bulk conductivity to be derived from, which is why the quantity exists in its own right.
372pub type Conductance = Qty<2, 1, -3, 0, -1, 0, 0>;
373/// J·kg⁻¹·K⁻¹ — the `c_p` that says how much heat a gram of glass can hide.
374pub type SpecificHeat = Qty<2, 0, -2, 0, -1, 0, 0>;
375/// m²·s⁻¹ — thermal diffusivity `α = k/(ρ c_p)`, and also mass diffusivity.
376pub type Diffusivity = Qty<2, 0, -1, 0, 0, 0, 0>;
377/// K⁻¹ — the coefficient that turns absorbed light into a focus shift.
378pub type ThermalExpansion = Qty<0, 0, 0, 0, -1, 0, 0>;
379/// kg·m² — how hard a body is to spin up about an axis.
380///
381/// The rotational counterpart of mass, and unlike mass it depends on the axis: a
382/// pencil is trivial to spin about its length and awkward about its middle. That
383/// direction-dependence is why it is a tensor and why a free body's rotation is
384/// interesting rather than uniform.
385pub type MomentOfInertia = Qty<2, 1, 0, 0, 0, 0, 0>;
386/// kg·m²·s⁻¹ — the rotational counterpart of momentum, and conserved for the same
387/// reason.
388pub type AngularMomentum = Qty<2, 1, -1, 0, 0, 0, 0>;
389/// N·m⁻¹ — a spring's `k`, and the penalty stiffness a contact is modelled with.
390///
391/// This is what sets a mechanical solver's stability limit: a mass on a spring
392/// oscillates with period `2π√(m/k)`, and an explicit integrator has to resolve that
393/// period whether or not anyone cares about it. Stiff contact is expensive for
394/// exactly this reason.
395pub type Stiffness = Qty<0, 1, -2, 0, 0, 0, 0>;
396/// N·s·m⁻¹ — a dashpot's `c`. Force proportional to velocity, and the only place a
397/// mechanical simulation loses energy on purpose.
398pub type Damping = Qty<0, 1, -1, 0, 0, 0, 0>;
399/// Coulombs.
400pub type Charge = Qty<0, 0, 1, 1, 0, 0, 0>;
401/// Volts.
402pub type Voltage = Qty<2, 1, -3, -1, 0, 0, 0>;
403/// Ohms — volts per ampere.
404pub type Resistance = Qty<2, 1, -3, -2, 0, 0, 0>;
405/// J·K⁻¹ — mass times specific heat. How much heat a thing can hide before it
406/// shows up as a temperature.
407pub type HeatCapacity = Qty<2, 1, -2, 0, -1, 0, 0>;
408
409// ---------------------------------------------------------------------------
410// Declared products. Each line also gives the two divisions that undo it.
411// ---------------------------------------------------------------------------
412
413macro_rules! product {
414 ($a:ty, $b:ty => $c:ty) => {
415 impl Mul<$b> for $a {
416 type Output = $c;
417 fn mul(self, rhs: $b) -> $c {
418 Qty(self.0 * rhs.0)
419 }
420 }
421 impl Mul<$a> for $b {
422 type Output = $c;
423 fn mul(self, rhs: $a) -> $c {
424 Qty(self.0 * rhs.0)
425 }
426 }
427 impl Div<$b> for $c {
428 type Output = $a;
429 fn div(self, rhs: $b) -> $a {
430 Qty(self.0 / rhs.0)
431 }
432 }
433 impl Div<$a> for $c {
434 type Output = $b;
435 fn div(self, rhs: $a) -> $b {
436 Qty(self.0 / rhs.0)
437 }
438 }
439 };
440}
441
442macro_rules! square {
443 ($a:ty => $c:ty) => {
444 impl Mul<$a> for $a {
445 type Output = $c;
446 fn mul(self, rhs: $a) -> $c {
447 Qty(self.0 * rhs.0)
448 }
449 }
450 impl Div<$a> for $c {
451 type Output = $a;
452 fn div(self, rhs: $a) -> $a {
453 Qty(self.0 / rhs.0)
454 }
455 }
456 };
457}
458
459square!(Length => Area);
460product!(Area, Length => Volume);
461product!(Velocity, Time => Length);
462product!(Acceleration, Time => Velocity);
463product!(Mass, Acceleration => Force);
464product!(Mass, Velocity => Momentum);
465product!(Force, Length => Energy);
466product!(Force, Time => Momentum);
467product!(Pressure, Area => Force);
468product!(Power, Time => Energy);
469product!(Irradiance, Area => Power);
470product!(Density, Volume => Mass);
471product!(Current, Time => Charge);
472product!(Voltage, Current => Power);
473// Ohm's law, declared rather than asserted: this line compiling is the check that ohms times
474// amperes are volts, and with the line above it that `I²R` comes out in watts.
475product!(Resistance, Current => Voltage);
476product!(Mass, Area => MomentOfInertia);
477product!(MomentOfInertia, Frequency => AngularMomentum);
478product!(Stiffness, Length => Force);
479product!(Damping, Velocity => Force);
480product!(Mass, SpecificHeat => HeatCapacity);
481// UA·ΔT is watts, and C/UA is a time — the two identities a thermal network is built out of,
482// so the type system checks them rather than a comment claiming them.
483product!(Conductance, Temperature => Power);
484product!(Conductance, Time => HeatCapacity);
485product!(HeatCapacity, Temperature => Energy);
486product!(Frequency, Time => Dimensionless);
487
488impl Volume {
489 /// Cubic metres.
490 pub fn m3(v: f64) -> Volume {
491 Qty(v)
492 }
493 /// Cubic centimetres — the unit a person actually has for a part.
494 pub fn cm3(v: f64) -> Volume {
495 Qty(v * 1e-6)
496 }
497 /// Cubic millimetres.
498 pub fn mm3(v: f64) -> Volume {
499 Qty(v * 1e-9)
500 }
501 /// Litres.
502 pub fn litres(v: f64) -> Volume {
503 Qty(v * 1e-3)
504 }
505}
506
507impl Area {
508 /// Square metres.
509 pub fn m2(v: f64) -> Area {
510 Qty(v)
511 }
512 /// Square centimetres.
513 pub fn cm2(v: f64) -> Area {
514 Qty(v * 1e-4)
515 }
516 /// Square millimetres — wire cross-sections live here.
517 pub fn mm2(v: f64) -> Area {
518 Qty(v * 1e-6)
519 }
520}
521
522impl Area {
523 /// The side of a square of this area. The one root worth naming, because it
524 /// is how a beam radius comes back out of a spot area.
525 pub fn sqrt(self) -> Length {
526 Qty(self.0.sqrt())
527 }
528}
529
530// ---------------------------------------------------------------------------
531// Unit-bearing entry and exit. The only place a factor of 1000 may appear.
532// ---------------------------------------------------------------------------
533
534impl Resistance {
535 /// Ohms.
536 pub fn ohm(v: f64) -> Resistance {
537 Qty(v)
538 }
539 /// Milliohms — the range a motor winding or a shunt actually lives in.
540 pub fn milliohm(v: f64) -> Resistance {
541 Qty(v * 1e-3)
542 }
543}
544
545impl Current {
546 /// Amperes.
547 pub fn a(v: f64) -> Current {
548 Qty(v)
549 }
550 /// Milliamperes.
551 pub fn ma(v: f64) -> Current {
552 Qty(v * 1e-3)
553 }
554}
555
556impl Voltage {
557 /// Volts.
558 pub fn v(v: f64) -> Voltage {
559 Qty(v)
560 }
561 /// Millivolts.
562 pub fn mv(v: f64) -> Voltage {
563 Qty(v * 1e-3)
564 }
565}
566
567impl Length {
568 /// Metres.
569 pub fn m(v: f64) -> Length {
570 Qty(v)
571 }
572 /// Millimetres.
573 pub fn mm(v: f64) -> Length {
574 Qty(v * 1e-3)
575 }
576 /// Micrometres.
577 pub fn um(v: f64) -> Length {
578 Qty(v * 1e-6)
579 }
580 /// Nanometres. The wavelength unit, and why every `Spectrum` field is named `_nm`.
581 pub fn nm(v: f64) -> Length {
582 Qty(v * 1e-9)
583 }
584 /// As millimetres.
585 pub fn in_mm(self) -> f64 {
586 self.0 * 1e3
587 }
588 /// As micrometres.
589 pub fn in_um(self) -> f64 {
590 self.0 * 1e6
591 }
592 /// As nanometres.
593 pub fn in_nm(self) -> f64 {
594 self.0 * 1e9
595 }
596}
597
598impl Time {
599 /// Seconds.
600 pub fn s(v: f64) -> Time {
601 Qty(v)
602 }
603 /// Milliseconds.
604 pub fn ms(v: f64) -> Time {
605 Qty(v * 1e-3)
606 }
607 /// Microseconds.
608 pub fn us(v: f64) -> Time {
609 Qty(v * 1e-6)
610 }
611 /// Nanoseconds.
612 pub fn ns(v: f64) -> Time {
613 Qty(v * 1e-9)
614 }
615 /// As milliseconds.
616 pub fn in_ms(self) -> f64 {
617 self.0 * 1e3
618 }
619 /// As microseconds.
620 pub fn in_us(self) -> f64 {
621 self.0 * 1e6
622 }
623}
624
625impl Temperature {
626 /// Kelvin, which is what is stored.
627 pub fn kelvin(v: f64) -> Temperature {
628 Qty(v)
629 }
630 /// Celsius is an *offset* scale, not a scaled one, which is why it gets a
631 /// named constructor rather than a factor: 20 °C is 293.15 K, and a
632 /// temperature *difference* of 20 K is a different thing entirely.
633 pub fn celsius(v: f64) -> Temperature {
634 Qty(v + 273.15)
635 }
636 /// As degrees Celsius. Subtracts the offset; see [`Temperature::celsius`].
637 pub fn in_celsius(self) -> f64 {
638 self.0 - 273.15
639 }
640}
641
642impl Mass {
643 /// Kilograms.
644 pub fn kg(v: f64) -> Mass {
645 Qty(v)
646 }
647 /// Grams.
648 pub fn g(v: f64) -> Mass {
649 Qty(v * 1e-3)
650 }
651}
652
653impl Density {
654 /// The way a glass catalogue quotes it: N-BK7 is 2.51 g/cm³.
655 pub fn g_per_cm3(v: f64) -> Density {
656 Qty(v * 1e3)
657 }
658 /// Kilograms per cubic metre, which is what is stored.
659 pub fn kg_per_m3(v: f64) -> Density {
660 Qty(v)
661 }
662}
663
664impl Power {
665 /// Watts.
666 pub fn w(v: f64) -> Power {
667 Qty(v)
668 }
669 /// Milliwatts.
670 pub fn mw(v: f64) -> Power {
671 Qty(v * 1e-3)
672 }
673 /// Microwatts.
674 pub fn uw(v: f64) -> Power {
675 Qty(v * 1e-6)
676 }
677 /// As milliwatts.
678 pub fn in_mw(self) -> f64 {
679 self.0 * 1e3
680 }
681}
682
683impl Energy {
684 /// Joules.
685 pub fn j(v: f64) -> Energy {
686 Qty(v)
687 }
688 /// Millijoules.
689 pub fn mj(v: f64) -> Energy {
690 Qty(v * 1e-3)
691 }
692}
693
694impl Frequency {
695 /// Hertz.
696 pub fn hz(v: f64) -> Frequency {
697 Qty(v)
698 }
699 /// Kilohertz.
700 pub fn khz(v: f64) -> Frequency {
701 Qty(v * 1e3)
702 }
703 /// Megahertz.
704 pub fn mhz(v: f64) -> Frequency {
705 Qty(v * 1e6)
706 }
707 /// Period: one over the frequency. Named because `1.0 / f` cannot typecheck.
708 pub fn period(self) -> Time {
709 Qty(1.0 / self.0)
710 }
711}
712
713impl Velocity {
714 /// Metres per second.
715 pub fn m_per_s(v: f64) -> Velocity {
716 Qty(v)
717 }
718 /// Millimetres per second.
719 pub fn mm_per_s(v: f64) -> Velocity {
720 Qty(v * 1e-3)
721 }
722}
723
724impl Irradiance {
725 /// Watts per square metre, which is what is stored.
726 pub fn w_per_m2(v: f64) -> Irradiance {
727 Qty(v)
728 }
729 /// How an illumination spec is usually written: mW/cm².
730 pub fn mw_per_cm2(v: f64) -> Irradiance {
731 Qty(v * 10.0)
732 }
733}
734
735impl ThermalConductivity {
736 /// W·m⁻¹·K⁻¹, the unit a materials table uses.
737 pub fn w_per_m_k(v: f64) -> ThermalConductivity {
738 Qty(v)
739 }
740}
741
742impl SpecificHeat {
743 /// J·kg⁻¹·K⁻¹, the unit a materials table uses.
744 pub fn j_per_kg_k(v: f64) -> SpecificHeat {
745 Qty(v)
746 }
747}
748
749impl Conductance {
750 /// Watts per kelvin.
751 pub fn w_per_k(v: f64) -> Conductance {
752 Qty(v)
753 }
754}
755
756impl HeatCapacity {
757 /// Joules per kelvin. The companion to [`Conductance::w_per_k`]: their ratio is a time
758 /// constant, and the type system says so.
759 pub fn j_per_k(v: f64) -> HeatCapacity {
760 Qty(v)
761 }
762}
763
764impl ThermalExpansion {
765 /// Catalogues quote it in parts per million per kelvin: N-BK7 is 7.1.
766 pub fn ppm_per_k(v: f64) -> ThermalExpansion {
767 Qty(v * 1e-6)
768 }
769}
770
771impl Dimensionless {
772 /// A bare ratio, for the one case where a number genuinely has no dimension:
773 /// a reflectance, a duty cycle, a refractive index.
774 pub fn ratio(v: f64) -> Dimensionless {
775 Qty(v)
776 }
777}
778
779// ---------------------------------------------------------------------------
780// Physical constants, in SI base units, so that a formula written with them
781// carries its own dimensional proof.
782// ---------------------------------------------------------------------------
783
784/// Speed of light in vacuum, m·s⁻¹ (exact by definition).
785pub const C: Velocity = Qty(299_792_458.0);
786/// Planck constant, J·s (exact by definition).
787pub const PLANCK: Qty<2, 1, -1, 0, 0, 0, 0> = Qty(6.626_070_15e-34);
788/// Boltzmann constant, J·K⁻¹ (exact by definition).
789pub const BOLTZMANN: HeatCapacity = Qty(1.380_649e-23);
790/// Stefan-Boltzmann constant, W·m⁻²·K⁻⁴ — radiative exchange lives on this.
791pub const STEFAN_BOLTZMANN: Qty<0, 1, -3, 0, -4, 0, 0> = Qty(5.670_374_419e-8);
792/// Standard gravity, m·s⁻².
793pub const G0: Acceleration = Qty(9.806_65);
794
795/// Energy of one photon at a vacuum wavelength: `E = hc/λ`.
796///
797/// The bridge between a spectrum and a photon count, and the reason a detector's
798/// response is not the same shape as a lamp's output.
799pub fn photon_energy(wavelength: Length) -> Energy {
800 Qty(PLANCK.0 * C.0 / wavelength.0)
801}
802
803#[cfg(test)]
804mod tests {
805 use super::*;
806
807 /// The point of the crate: a product of dimensions lands on the type that
808 /// names it, whichever route it took there.
809 #[test]
810 fn products_land_on_the_named_dimension() {
811 let m = Mass::kg(2.0);
812 let a = Acceleration::from_si(3.0);
813 let f: Force = m * a;
814 assert!((f.to_si() - 6.0).abs() < 1e-12);
815
816 // Two different routes to the same energy, and they unify.
817 let by_work: Energy = f * Length::m(4.0);
818 let by_power: Energy = Power::w(24.0) * Time::s(1.0);
819 assert!((by_work - by_power).abs().to_si() < 1e-12);
820
821 // And multiplication commutes, as it must.
822 let swapped: Force = a * m;
823 assert_eq!(f, swapped);
824 }
825
826 /// Millimetres and nanometres are entry forms only; storage is metres. A
827 /// wavelength and a lens diameter therefore compare correctly without anyone
828 /// remembering which convention each was written in.
829 #[test]
830 fn unit_prefixes_are_only_a_doorway() {
831 let lens = Length::mm(25.4);
832 let green = Length::nm(550.0);
833 assert!(lens > green);
834 assert!((lens.to_si() - 0.0254).abs() < 1e-15);
835 assert!((green.in_nm() - 550.0).abs() < 1e-9);
836 // 25.4 mm is 46181.8... wavelengths of green light.
837 let waves = lens / green;
838 assert!((waves - 46_181.8).abs() < 0.1, "got {waves}");
839 }
840
841 /// Dividing like by like gives a plain number, which is what every
842 /// tolerance and every reflectance is.
843 #[test]
844 fn like_over_like_is_a_bare_number() {
845 let reflected = Power::mw(0.42);
846 let incident = Power::mw(10.0);
847 let r: f64 = reflected / incident;
848 assert!((r - 0.042).abs() < 1e-12);
849 }
850
851 /// Celsius offsets rather than scales, and getting that wrong is a 273 K
852 /// error that no dimensional check would ever catch.
853 #[test]
854 fn celsius_is_an_offset_not_a_factor() {
855 assert!((Temperature::celsius(20.0).to_si() - 293.15).abs() < 1e-12);
856 assert!((Temperature::kelvin(293.15).in_celsius() - 20.0).abs() < 1e-12);
857 // A *difference* of 20 K is not 293.15 K, and only one of these is a
858 // temperature you can put in Stefan-Boltzmann.
859 let rise = Temperature::kelvin(313.15) - Temperature::kelvin(293.15);
860 assert!((rise.to_si() - 20.0).abs() < 1e-12);
861 }
862
863 /// The optics-to-thermal chain this whole crate exists to make safe: a
864 /// surface absorbs a fraction of an irradiance over an area, and the watts
865 /// that result heat a mass with a known specific heat.
866 #[test]
867 fn absorbed_light_becomes_a_temperature_rise() {
868 let irradiance = Irradiance::mw_per_cm2(50.0); // 500 W/m²
869 let area: Area = Length::mm(10.0) * Length::mm(10.0); // 1e-4 m²
870 let absorptance = 0.02; // what SurfaceOptics::absorptance returns
871 let absorbed: Power = irradiance * area * absorptance;
872 assert!((absorbed.to_si() - 0.001).abs() < 1e-12, "{absorbed:?}");
873
874 // 1 mW into a 2 g piece of glass for 1 s.
875 let glass = Mass::g(2.0);
876 let c_p = SpecificHeat::j_per_kg_k(858.0); // N-BK7
877 let capacity: HeatCapacity = glass * c_p;
878 let heat: Energy = absorbed * Time::s(1.0);
879 let rise: Temperature = heat / capacity;
880 assert!(
881 (rise.to_si() - 0.000_582_7).abs() < 1e-7,
882 "expected about 0.58 mK, got {rise:?}"
883 );
884 }
885
886 /// A photon at 550 nm carries 3.6e-19 J, and the count per watt follows.
887 /// This is the number that separates radiometry from photon counting.
888 #[test]
889 fn photon_energy_matches_the_textbook_figure() {
890 let e = photon_energy(Length::nm(550.0));
891 assert!((e.to_si() - 3.612e-19).abs() < 1e-21, "{e:?}");
892 // 2.26 eV, and about 2.77e18 photons in a joule.
893 let per_joule = Energy::j(1.0) / e;
894 assert!((per_joule - 2.768e18).abs() < 1e15, "got {per_joule:e}");
895 }
896
897 /// Debug prints the dimension, so a mismatch found at a boundary can be
898 /// reported in a form a human recognises.
899 #[test]
900 fn debug_shows_the_dimension() {
901 assert_eq!(format!("{:?}", Force::from_si(6.0)), "6·m·kg·s^-2");
902 assert_eq!(format!("{:?}", Dimensionless::ratio(0.5)), "0.5");
903 assert_eq!(Force::dimension(), [1, 1, -2, 0, 0, 0, 0]);
904 }
905
906 /// Serialised as the bare SI number: the dimension is in the field's type,
907 /// not repeated in every scene file.
908 #[test]
909 fn serialises_as_a_bare_si_number() {
910 let json = serde_json::to_string(&Length::mm(25.4)).unwrap();
911 assert_eq!(json, "0.0254");
912 let back: Length = serde_json::from_str(&json).unwrap();
913 assert_eq!(back, Length::mm(25.4));
914 }
915}