EmbarkStudios / mirror-mirror

🪞 Powerful reflection library for Rust
Apache License 2.0
79 stars 2 forks source link

`glam::Quat/Vec4/Mat4` support #134

Open Athosvk opened 6 months ago

Athosvk commented 6 months ago

Problem Currently the glam support does not include types that are architecture dependent, e.g. Quat and Vec4. This is due to Vec4 either being a [float; 4] or m128 depending on the target architecture and glam using wrappers and using Deref to allow trivial access to each vector's components.

Unfortunately the lack of reflection supports means either skipping those fields with #[reflect(skip)], manually implementing Reflect, FromReflect and DescribeType for the type containing these fields in some way, or supporting a wrapper type around glam::Vec4 and equivalents which then requires replacements in all of the codebase. Hopefully this can start a discussion on potential ways to tackle this.

Preferred Solution As the current comment in mirror-mirror's glam implementation states, manually re-implementing config checks and hacks that are done by glam doesn't seem great. Ideally we can still use glam's types without wrappers (within structs), whether that as Struct or maybe as Scalar (?).

I've tried implementing Struct for Vec4 and this seems to be almost possible from what I've found, with the only problem being fields_mut. fields_mut ends up requiring a borrow to each field, but Vec4 is a m128 with SIMD on which is only a single field. Even if we were to thread the land of unsafe, I'd bet it's undefined behaviour to read/write into the same m128 at different offsets simultaneously, so fields_mut would never work without potential UB. The other trait functions are trivial, though this is a manual implementation rather than just use the #[derive] syntax as one would expect.

I'd argue Vec4 as a Scalar type makes sense (probably with Vec2/3 to match), also because the (often) underlying m128 is scalar-like, but it perhaps does litter the code with [cfg]s to check if glam support should be on. Perhaps there's also limitations that I'm not aware of for Scalar types.

Alternatives Maybe an alternative is to just provide a wrapper type for these that easily allow conversions from/to glam::Vec4/Mat4/Quat if the above options aren't really feasible.

fu5ha commented 4 months ago

Even if we were to thread the land of unsafe, I'd bet it's undefined behaviour to read/write into the same m128 at different offsets simultaneously, so fields_mut would never work without potential UB.

Fwiw this is not true, an m128 is trivially type-punnable as a [f32; 4] and therefore also a

#[repr(C)]
struct XYZW {
    x: f32,
    y: f32,
    z: f32,
    w: f32,
}

Which are both then destructurable. That's exactly how the internal implementations of glam's Deref and DerefMut impls work