Skip to content

Instantly share code, notes, and snippets.

@csprance
Created February 9, 2021 01:53
Show Gist options
  • Save csprance/d513b3d8b90f57b3028756806b1e57e2 to your computer and use it in GitHub Desktop.
Save csprance/d513b3d8b90f57b3028756806b1e57e2 to your computer and use it in GitHub Desktop.
How to calculate barycentric coordinates in houdini using vex given 3 points making up a triangle and a point p we want to get the coordinates for
// This is the point we want to find barycentric coordinates of
vector p = point(0, "P", 3);
// These are the vertices of the main triangle we want to find coordinates for
vector v1 = point(0, "P", 0),
v2 = point(0, "P", 1),
v3 = point(0, "P", 2);
// Edge Vectors of the main triangle
vector e1 = v3 - v2,
e2 = v1 - v3,
e3 = v2 - v1;
// Sub Triangle Edge Vectors created using p
vector d1 = p - v1,
d2 = p - v2,
d3 = p - v3;
// We need a normal vector so generate one from the edge vectors of the main triangle
vector n = cross(e1, e2) / length(cross(e1, e2));
// Now find the area of each triangle using the triple product: (a × b) ⋅ n
float AT = dot(cross(e1, e2), n) / 2,
AT1 = dot(cross(e1, d3), n) / 2,
AT2 = dot(cross(e2, d1), n) / 2,
AT3 = dot(cross(e3, d2), n) / 2;
// Now we divide the area of each subtriangle against the area of the main triangle
float u = AT1/AT,
v = AT2/AT,
w = AT3/AT;
// Congrats these are our barycentric coordinates!
vector b = set(u, v, w);
// To project the point down on to the surface of the triangle in the shortest distance
vector pProjected = u*v1 + v*v2 + w*v3;
// Set somethings for houdini
v@bary = b;
// If we add up all these values they should = 1. If it > 1 That means it's outside the triangle
f@amt = abs(u) + abs(v) + abs(w);
// If our length is > 0 That means the original point is on the plane
f@d = length(p - pProjected);
i@onPlane = !(f@d > 0.000001);
// Add the point so we can see where it gets projects to
addpoint(0, pProjected);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment