zig-gamedev/zmath

Generic casting function: U32x2 to F32x2 and vice versa

Opened this issue · 1 comments

Hi I did a generic vector/array casting function that I use for by 2d game

pub inline fn cast(comptime T: type, value: anytype) @Vector(veclen(@TypeOf(value)), T) {
    // This routine won't handle nan, inf and numbers greater than 8_388_608.0 (will generate undefined values).
    @setRuntimeSafety(false);

    const len = veclen(@TypeOf(value));
    const child = vectype(@TypeOf(value));

    var dst: [len]T = undefined;
    switch (@typeInfo(child)) {
        .Int => {
            comptime var i: u32 = 0;
            inline while (i < len) : (i += 1) {
                dst[i] = @intToFloat(T, value[i]);
            }
        },
        .Float => {
            comptime var i: u32 = 0;
            inline while (i < len) : (i += 1) {
                dst[i] = @floatToInt(T, value[i]);
            }
        },
        else => {
            @compileError("cast not supported");
        },
    }

    return dst;
}

I had to modify veclen to add support to arrays, but what you guys think? is PR worth?

Hi, yes, please make a PR.