Skip to content

Commit 10c16a1

Browse files
committed
feat: support vectors
1 parent fb756ae commit 10c16a1

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

lib/std/math.zig

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1313,18 +1313,24 @@ test "lossyCast" {
13131313
}
13141314

13151315
/// Performs linear interpolation between *a* and *b* based on *t*.
1316-
/// *t* must be in range 0.0 to 1.0. T must be a float type.
1316+
/// *t* must be in range 0.0 to 1.0. Supports floats and vectors of floats.
13171317
///
13181318
/// This does not guarantee returning *b* if *t* is 1 due to floating-point errors.
13191319
/// This is monotonic.
13201320
pub fn lerp(a: anytype, b: anytype, t: anytype) @TypeOf(a, b, t) {
1321-
const T = @TypeOf(a, b, t);
1322-
1323-
comptime if (!std.meta.trait.isFloat(T))
1324-
@compileError("T must be a float type");
1321+
const Type = @TypeOf(a, b, t);
1322+
1323+
switch (@typeInfo(Type)) {
1324+
.Float, .ComptimeFloat => assert(t >= 0 and t <= 1),
1325+
.Vector => |vector| {
1326+
const lower_bound = @reduce(.And, t >= @splat(vector.len, @as(vector.child, 0)));
1327+
const upper_bound = @reduce(.And, t <= @splat(vector.len, @as(vector.child, 1)));
1328+
assert(lower_bound and upper_bound);
1329+
},
1330+
else => comptime unreachable,
1331+
}
13251332

1326-
assert(t >= 0 and t <= 1);
1327-
return @mulAdd(T, b - a, t, a);
1333+
return @mulAdd(Type, b - a, t, a);
13281334
}
13291335

13301336
test "lerp" {
@@ -1339,6 +1345,15 @@ test "lerp" {
13391345
try testing.expectEqual(@as(f64, 0.0), lerp(@as(f64, 1.0e16), 1.0, 1.0));
13401346
try testing.expectEqual(@as(f32, 1.0), lerp(@as(f32, 1.0e7), 1.0, 1.0));
13411347
try testing.expectEqual(@as(f64, 1.0), lerp(@as(f64, 1.0e15), 1.0, 1.0));
1348+
1349+
try testing.expectEqual(
1350+
lerp(@splat(3, @as(f32, 0)), @splat(3, @as(f32, 50)), @splat(3, @as(f32, 0.5))),
1351+
@Vector(3, f32){ 25, 25, 25 },
1352+
);
1353+
try testing.expectEqual(
1354+
lerp(@splat(3, @as(f64, 50)), @splat(3, @as(f64, 100)), @splat(3, @as(f64, 0.5))),
1355+
@Vector(3, f64){ 75, 75, 75 },
1356+
);
13421357
}
13431358

13441359
/// Returns the maximum value of integer type T.

0 commit comments

Comments
 (0)