Skip to main content

spirv_std/
float.rs

1//! Traits and helper functions related to floats.
2
3use crate::glam::{Vec2, Vec4};
4#[cfg(target_arch = "spirv")]
5use core::arch::asm;
6#[cfg(target_arch = "spirv")]
7use core::intrinsics;
8
9#[cfg(target_arch = "spirv")]
10impl f32 {
11    /// Returns the largest integer that is less than or equal to `self`.
12    #[inline]
13    #[rustc_allow_incoherent_impl]
14    pub fn floor(self) -> f32 {
15        intrinsics::floorf32(self)
16    }
17
18    /// Returns the smallest integer that is greater than or equal to `self`.
19    #[inline]
20    #[rustc_allow_incoherent_impl]
21    pub fn ceil(self) -> f32 {
22        intrinsics::ceilf32(self)
23    }
24
25    /// Returns the nearest integer to `self`.
26    #[inline]
27    #[rustc_allow_incoherent_impl]
28    pub fn round(self) -> f32 {
29        intrinsics::roundf32(self)
30    }
31
32    /// Returns the nearest integer to a number.
33    #[inline]
34    #[rustc_allow_incoherent_impl]
35    pub fn round_ties_even(self) -> f32 {
36        intrinsics::round_ties_even_f32(self)
37    }
38
39    /// Returns the integer part of `self`.
40    #[inline]
41    #[rustc_allow_incoherent_impl]
42    pub fn trunc(self) -> f32 {
43        intrinsics::truncf32(self)
44    }
45
46    /// Returns the fractional part of `self`.
47    #[inline]
48    #[rustc_allow_incoherent_impl]
49    pub fn fract(self) -> f32 {
50        self - self.trunc()
51    }
52
53    /// Fused multiply-add.
54    #[inline]
55    #[rustc_allow_incoherent_impl]
56    pub fn mul_add(self, a: f32, b: f32) -> f32 {
57        intrinsics::fmaf32(self, a, b)
58    }
59
60    /// Calculates Euclidean division, the matching method for `rem_euclid`.
61    #[inline]
62    #[rustc_allow_incoherent_impl]
63    pub fn div_euclid(self, rhs: f32) -> f32 {
64        let q = (self / rhs).trunc();
65        if self % rhs < 0.0 {
66            return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
67        }
68        q
69    }
70
71    /// Calculates the least nonnegative remainder of `self` when divided by `rhs`.
72    #[inline]
73    #[rustc_allow_incoherent_impl]
74    pub fn rem_euclid(self, rhs: f32) -> f32 {
75        let r = self % rhs;
76        if r < 0.0 { r + rhs.abs() } else { r }
77    }
78
79    /// Raises a number to an integer power.
80    #[inline]
81    #[rustc_allow_incoherent_impl]
82    pub fn powi(self, n: i32) -> f32 {
83        intrinsics::powif32(self, n)
84    }
85
86    /// Returns the square root of a number.
87    #[inline]
88    #[rustc_allow_incoherent_impl]
89    pub fn sqrt(self) -> f32 {
90        intrinsics::sqrtf32(self)
91    }
92
93    /// Returns the cube root of a number.
94    #[inline]
95    #[rustc_allow_incoherent_impl]
96    pub fn cbrt(self) -> f32 {
97        intrinsics::powf32(self, 1.0 / 3.0)
98    }
99
100    /// The positive difference of two numbers.
101    #[inline]
102    #[rustc_allow_incoherent_impl]
103    #[deprecated(
104        since = "0.10.0",
105        note = "you probably meant `(self - other).abs()`: \
106            this operation is `(self - other).max(0.0)` \
107            except that `abs_sub` also propagates NaNs (also \
108            known as `fdimf` in C). If you truly need the positive \
109            difference, consider using that expression or the C function \
110            `fdimf`, depending on how you wish to handle NaN (please consider \
111            filing an issue describing your use-case too)."
112    )]
113    pub fn abs_sub(self, other: f32) -> f32 {
114        let r = self - other;
115        if r.is_nan() {
116            r
117        } else if r > 0.0 {
118            r
119        } else {
120            0.0
121        }
122    }
123}
124
125#[cfg(target_arch = "spirv")]
126impl f64 {
127    /// Returns the largest integer that is less than or equal to `self`.
128    #[inline]
129    #[rustc_allow_incoherent_impl]
130    pub fn floor(self) -> f64 {
131        intrinsics::floorf64(self)
132    }
133
134    /// Returns the smallest integer that is greater than or equal to `self`.
135    #[inline]
136    #[rustc_allow_incoherent_impl]
137    pub fn ceil(self) -> f64 {
138        intrinsics::ceilf64(self)
139    }
140
141    /// Returns the nearest integer to `self`.
142    #[inline]
143    #[rustc_allow_incoherent_impl]
144    pub fn round(self) -> f64 {
145        intrinsics::roundf64(self)
146    }
147
148    /// Returns the nearest integer to a number.
149    #[inline]
150    #[rustc_allow_incoherent_impl]
151    pub fn round_ties_even(self) -> f64 {
152        intrinsics::round_ties_even_f64(self)
153    }
154
155    /// Returns the integer part of `self`.
156    #[inline]
157    #[rustc_allow_incoherent_impl]
158    pub fn trunc(self) -> f64 {
159        intrinsics::truncf64(self)
160    }
161
162    /// Returns the fractional part of `self`.
163    #[inline]
164    #[rustc_allow_incoherent_impl]
165    pub fn fract(self) -> f64 {
166        self - self.trunc()
167    }
168
169    /// Fused multiply-add.
170    #[inline]
171    #[rustc_allow_incoherent_impl]
172    pub fn mul_add(self, a: f64, b: f64) -> f64 {
173        intrinsics::fmaf64(self, a, b)
174    }
175
176    /// Calculates Euclidean division, the matching method for `rem_euclid`.
177    #[inline]
178    #[rustc_allow_incoherent_impl]
179    pub fn div_euclid(self, rhs: f64) -> f64 {
180        let q = (self / rhs).trunc();
181        if self % rhs < 0.0 {
182            return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
183        }
184        q
185    }
186
187    /// Calculates the least nonnegative remainder of `self` when divided by `rhs`.
188    #[inline]
189    #[rustc_allow_incoherent_impl]
190    pub fn rem_euclid(self, rhs: f64) -> f64 {
191        let r = self % rhs;
192        if r < 0.0 { r + rhs.abs() } else { r }
193    }
194
195    /// Raises a number to an integer power.
196    #[inline]
197    #[rustc_allow_incoherent_impl]
198    pub fn powi(self, n: i32) -> f64 {
199        intrinsics::powif64(self, n)
200    }
201
202    /// Returns the square root of a number.
203    #[inline]
204    #[rustc_allow_incoherent_impl]
205    pub fn sqrt(self) -> f64 {
206        intrinsics::sqrtf64(self)
207    }
208
209    /// Returns the cube root of a number.
210    #[inline]
211    #[rustc_allow_incoherent_impl]
212    pub fn cbrt(self) -> f64 {
213        intrinsics::powf64(self, 1.0 / 3.0)
214    }
215
216    /// The positive difference of two numbers.
217    #[inline]
218    #[rustc_allow_incoherent_impl]
219    #[deprecated(
220        since = "0.10.0",
221        note = "you probably meant `(self - other).abs()`: \
222            this operation is `(self - other).max(0.0)` \
223            except that `abs_sub` also propagates NaNs (also \
224            known as `fdim` in C). If you truly need the positive \
225            difference, consider using that expression or the C function \
226            `fdim`, depending on how you wish to handle NaN (please consider \
227            filing an issue describing your use-case too)."
228    )]
229    pub fn abs_sub(self, other: f64) -> f64 {
230        let r = self - other;
231        if r.is_nan() {
232            r
233        } else if r > 0.0 {
234            r
235        } else {
236            0.0
237        }
238    }
239}
240
241/// Converts two f32 values (floats) into two f16 values (halfs). The result is a u32, with the low
242/// 16 bits being the first f16, and the high 16 bits being the second f16.
243#[spirv_std_macros::gpu_only]
244pub fn vec2_to_f16x2(vec: Vec2) -> u32 {
245    let result;
246    unsafe {
247        asm!(
248            "%glsl = OpExtInstImport \"GLSL.std.450\"",
249            "%uint = OpTypeInt 32 0",
250            "%vec = OpLoad _ {vec}",
251            // 58 = PackHalf2x16
252            "{result} = OpExtInst %uint %glsl 58 %vec",
253            vec = in(reg) &vec,
254            result = out(reg) result,
255        );
256    }
257    result
258}
259
260/// Converts two f16 values (halfs) into two f32 values (floats). The parameter is a u32, with the
261/// low 16 bits being the first f16, and the high 16 bits being the second f16.
262#[spirv_std_macros::gpu_only]
263pub fn f16x2_to_vec2(int: u32) -> Vec2 {
264    let mut result = Default::default();
265    unsafe {
266        asm!(
267            "%glsl = OpExtInstImport \"GLSL.std.450\"",
268            // 62 = UnpackHalf2x16
269            "%result = OpExtInst typeof*{result} %glsl 62 {int}",
270            "OpStore {result} %result",
271            int = in(reg) int,
272            result = in(reg) &mut result,
273        );
274    }
275    result
276}
277
278/// Converts an f32 (float) into an f16 (half). The result is a u32, not a u16, due to GPU support
279/// for u16 not being universal - the upper 16 bits will always be zero.
280#[spirv_std_macros::gpu_only]
281pub fn f32_to_f16(float: f32) -> u32 {
282    vec2_to_f16x2(crate::glam::Vec2::new(float, 0.))
283}
284
285/// Converts an f16 (half) into an f32 (float). The parameter is a u32, due to GPU support for u16
286/// not being universal - the upper 16 bits are ignored.
287#[spirv_std_macros::gpu_only]
288pub fn f16_to_f32(packed: u32) -> f32 {
289    f16x2_to_vec2(packed).x
290}
291
292/// Packs a vec4 into 4 8-bit signed integers. See
293/// [PackSnorm4x8](https://www.khronos.org/registry/SPIR-V/specs/1.0/GLSL.std.450.html) for exact
294/// semantics.
295#[spirv_std_macros::gpu_only]
296pub fn vec4_to_u8x4_snorm(vec: Vec4) -> u32 {
297    let result;
298    unsafe {
299        asm!(
300            "%glsl = OpExtInstImport \"GLSL.std.450\"",
301            "%uint = OpTypeInt 32 0",
302            "%vec = OpLoad _ {vec}",
303            // 54 = PackSnorm4x8
304            "{result} = OpExtInst %uint %glsl 54 %vec",
305            vec = in(reg) &vec,
306            result = out(reg) result,
307        );
308    }
309    result
310}
311
312/// Packs a vec4 into 4 8-bit unsigned integers. See
313/// [PackUnorm4x8](https://www.khronos.org/registry/SPIR-V/specs/1.0/GLSL.std.450.html) for exact
314/// semantics.
315#[spirv_std_macros::gpu_only]
316pub fn vec4_to_u8x4_unorm(vec: Vec4) -> u32 {
317    let result;
318    unsafe {
319        asm!(
320            "%glsl = OpExtInstImport \"GLSL.std.450\"",
321            "%uint = OpTypeInt 32 0",
322            "%vec = OpLoad _ {vec}",
323            // 55 = PackUnorm4x8
324            "{result} = OpExtInst %uint %glsl 55 %vec",
325            vec = in(reg) &vec,
326            result = out(reg) result,
327        );
328    }
329    result
330}
331
332/// Packs a vec2 into 2 16-bit signed integers. See
333/// [PackSnorm2x16](https://www.khronos.org/registry/SPIR-V/specs/1.0/GLSL.std.450.html) for exact
334/// semantics.
335#[spirv_std_macros::gpu_only]
336pub fn vec2_to_u16x2_snorm(vec: Vec2) -> u32 {
337    let result;
338    unsafe {
339        asm!(
340            "%glsl = OpExtInstImport \"GLSL.std.450\"",
341            "%uint = OpTypeInt 32 0",
342            "%vec = OpLoad _ {vec}",
343            // 56 = PackSnorm2x16
344            "{result} = OpExtInst %uint %glsl 56 %vec",
345            vec = in(reg) &vec,
346            result = out(reg) result,
347        );
348    }
349    result
350}
351
352/// Packs a vec2 into 2 16-bit unsigned integers. See
353/// [PackUnorm2x16](https://www.khronos.org/registry/SPIR-V/specs/1.0/GLSL.std.450.html) for exact
354/// semantics.
355#[spirv_std_macros::gpu_only]
356pub fn vec2_to_u16x2_unorm(vec: Vec2) -> u32 {
357    let result;
358    unsafe {
359        asm!(
360            "%glsl = OpExtInstImport \"GLSL.std.450\"",
361            "%uint = OpTypeInt 32 0",
362            "%vec = OpLoad _ {vec}",
363            // 57 = PackUnorm2x16
364            "{result} = OpExtInst %uint %glsl 57 %vec",
365            vec = in(reg) &vec,
366            result = out(reg) result,
367        );
368    }
369    result
370}
371
372/// Unpacks 4 8-bit signed integers into a vec4. See
373/// [UnpackSnorm4x8](https://www.khronos.org/registry/SPIR-V/specs/1.0/GLSL.std.450.html) for exact
374/// semantics.
375#[spirv_std_macros::gpu_only]
376pub fn u8x4_to_vec4_snorm(int: u32) -> Vec4 {
377    let mut result = Default::default();
378    unsafe {
379        asm!(
380            "%glsl = OpExtInstImport \"GLSL.std.450\"",
381            // 63 = UnpackSnorm4x8
382            "%result = OpExtInst typeof*{result} %glsl 63 {int}",
383            "OpStore {result} %result",
384            int = in(reg) int,
385            result = in(reg) &mut result,
386        );
387    }
388    result
389}
390
391/// Unpacks 4 8-bit unsigned integers into a vec4. See
392/// [UnpackSnorm4x8](https://www.khronos.org/registry/SPIR-V/specs/1.0/GLSL.std.450.html) for exact
393/// semantics.
394#[spirv_std_macros::gpu_only]
395pub fn u8x4_to_vec4_unorm(int: u32) -> Vec4 {
396    let mut result = Default::default();
397    unsafe {
398        asm!(
399            "%glsl = OpExtInstImport \"GLSL.std.450\"",
400            // 64 = UnpackUnorm4x8
401            "%result = OpExtInst typeof*{result} %glsl 64 {int}",
402            "OpStore {result} %result",
403            int = in(reg) int,
404            result = in(reg) &mut result,
405        );
406    }
407    result
408}
409
410/// Unpacks 2 16-bit signed integers into a vec2. See
411/// [UnpackSnorm2x16](https://www.khronos.org/registry/SPIR-V/specs/1.0/GLSL.std.450.html) for
412/// exact semantics.
413#[spirv_std_macros::gpu_only]
414pub fn u16x2_to_vec2_snorm(int: u32) -> Vec2 {
415    let mut result = Default::default();
416    unsafe {
417        asm!(
418            "%glsl = OpExtInstImport \"GLSL.std.450\"",
419            // 60 = UnpackSnorm2x16
420            "%result = OpExtInst typeof*{result} %glsl 60 {int}",
421            "OpStore {result} %result",
422            int = in(reg) int,
423            result = in(reg) &mut result,
424        );
425    }
426    result
427}
428
429/// Unpacks 2 16-bit unsigned integers into a vec2. See
430/// [UnpackUnorm2x16](https://www.khronos.org/registry/SPIR-V/specs/1.0/GLSL.std.450.html) for
431/// exact semantics.
432#[spirv_std_macros::gpu_only]
433pub fn u16x2_to_vec2_unorm(int: u32) -> Vec2 {
434    let mut result = Default::default();
435    unsafe {
436        asm!(
437            "%glsl = OpExtInstImport \"GLSL.std.450\"",
438            // 61 = UnpackUnorm2x16
439            "%result = OpExtInst typeof*{result} %glsl 61 {int}",
440            "OpStore {result} %result",
441            int = in(reg) int,
442            result = in(reg) &mut result,
443        );
444    }
445    result
446}