| 1 | // Copyright 2024 the Fearless_SIMD Authors |
| 2 | // SPDX-License-Identifier: Apache-2.0 OR MIT |
| 3 | |
| 4 | #![expect( |
| 5 | missing_docs, |
| 6 | reason = "TODO: https://github.com/linebender/fearless_simd/issues/40" |
| 7 | )] |
| 8 | |
| 9 | use fearless_simd::{Level, dispatch, f32x4, prelude::*}; |
| 10 | |
| 11 | // This block shows how to use safe wrappers for compile-time enforcement |
| 12 | // of using valid SIMD intrinsics. |
| 13 | #[cfg(feature = "safe_wrappers")] |
| 14 | #[inline(always)] |
| 15 | fn copy_alpha<S: Simd>(a: f32x4<S>, b: f32x4<S>) -> f32x4<S> { |
| 16 | // #[cfg(target_arch = "x86_64")] |
| 17 | // if let Some(avx2) = a.simd.level().as_avx2() { |
| 18 | // return avx2 |
| 19 | // .sse4_1 |
| 20 | // ._mm_blend_ps::<8>(a.into(), b.into()) |
| 21 | // .simd_into(a.simd); |
| 22 | // } |
| 23 | #[cfg(target_arch = "aarch64")] |
| 24 | if let Some(neon) = a.simd.level().as_neon() { |
| 25 | return neon |
| 26 | .neon |
| 27 | .vcopyq_laneq_f32::<3, 3>(a.into(), b.into()) |
| 28 | .simd_into(a.simd); |
| 29 | } |
| 30 | let mut result = a; |
| 31 | result[3] = b[3]; |
| 32 | result |
| 33 | } |
| 34 | |
| 35 | // This block lets the example compile without safe wrappers. |
| 36 | #[cfg(not(feature = "safe_wrappers"))] |
| 37 | #[inline(always)] |
| 38 | fn copy_alpha<S: Simd>(a: f32x4<S>, b: f32x4<S>) -> f32x4<S> { |
| 39 | #[cfg(target_arch = "aarch64")] |
| 40 | if let Some(_neon) = a.simd.level().as_neon() { |
| 41 | unsafe { |
| 42 | return core::arch::aarch64::vcopyq_laneq_f32::<3, 3>(a.into(), b.into()) |
| 43 | .simd_into(a.simd); |
| 44 | } |
| 45 | } |
| 46 | let mut result = a; |
| 47 | result[3] = b[3]; |
| 48 | result |
| 49 | } |
| 50 | |
| 51 | #[inline(always)] |
| 52 | fn to_srgb<S: Simd>(simd: S, rgba: [f32; 4]) -> [f32; 4] { |
| 53 | let v: f32x4<S> = rgba.simd_into(simd); |
| 54 | let vabs = v.abs(); |
| 55 | let x = vabs - 5.358_626_4e-4; |
| 56 | let x2 = x * x; |
| 57 | let even1 = x * -9.127_959e-1 + -2.881_431_4e-2; |
| 58 | let even2 = x2 * -7.291_929e-1 + even1; |
| 59 | let odd1 = x * 1.061_331_7 + 1.401_945_4; |
| 60 | let odd2 = x2 * 2.077_583e-1 + odd1; |
| 61 | let poly = odd2 * x.sqrt() + even2; |
| 62 | let lin = vabs * 12.92; |
| 63 | let z = vabs.simd_gt(0.0031308).select(poly, lin); |
| 64 | let z_signed = z.copysign(v); |
| 65 | let result = copy_alpha(z_signed, v); |
| 66 | result.into() |
| 67 | } |
| 68 | |
| 69 | fn main() { |
| 70 | let level = Level::new(); |
| 71 | let rgba = [0.1, -0.2, 0.001, 0.4]; |
| 72 | let srgb = dispatch!(level, simd=> to_srgb(simd, rgba)); |
| 73 | println!("{srgb:?}"); |
| 74 | } |