Skip to content

Generic casting function: U32x2 to F32x2 and vice versa #3

Description

@lassade

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?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions