Skip to content

Instantly share code, notes, and snippets.

@tonis2
Created March 31, 2021 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonis2/3f3d5f707d0960ae2ecab44a72c6ac67 to your computer and use it in GitHub Desktop.
Save tonis2/3f3d5f707d0960ae2ecab44a72c6ac67 to your computer and use it in GitHub Desktop.
Ziglang linear interpolation
// Linear Interpolation Functions
const std = @import("std");
const math = std.math;
fn lerp(x: f16, y: f16, a: f16) f16 {
return x * (1 - a) + y * a;
}
fn invLerp(x: f16, y: f16, a: f16) f16 {
return clamp((a - x) / (y - x), 0, 1);
}
fn clamp(a: f16, min: f16, max: f16) f16 {
return math.min(max, math.max(min, a));
}
fn range(x1: f16, y1: f16, x2: f16, y2: f16, a: f16) f16 {
return lerp(x2, y2, invLerp(x1, y1, a));
}
pub fn main() !void {
const max: f16 = 255;
var value: f16 = 51;
const percentage = value / max * 100;
std.debug.print("lerp {d} \n", .{lerp(0, 7, percentage) / 100});
std.debug.print("invLerp {d} \n", .{invLerp(0, 255, value)});
std.debug.print("range {d} \n", .{range(0, 255, 0, 7, value)});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment