Skip to content

Instantly share code, notes, and snippets.

@n1xx1
Last active December 9, 2018 17:50
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 n1xx1/3cfd650f9d49127af5ec2df7e0b83eca to your computer and use it in GitHub Desktop.
Save n1xx1/3cfd650f9d49127af5ec2df7e0b83eca to your computer and use it in GitHub Desktop.
public class MyThing {
private void DebugDrawLine(Vector4 a, Vector4 b) {
a = a / a.w;
b = b / b.w;
Gizmos.DrawLine(new Vector3(a.x, a.y), new Vector3(b.x, b.y));
}
private void DebugDrawPolygon(List<Vector4> poly) {
for (int i = 0; i < poly.Count; i++) {
if (i == poly.Count - 1) {
DebugDrawLine(poly[i], poly[0]);
} else {
DebugDrawLine(poly[i], poly[i + 1]);
}
}
}
private void DebugDrawClippedTriangle(Vector4 a, Vector4 b, Vector4 c) {
var poly = new List<Vector4> { a, b, c };
if (ClipPolygon(poly, 0) && ClipPolygon(poly, 1) && ClipPolygon(poly, 2)) {
DebugDrawPolygon(poly);
}
}
private bool ClipPolygon(List<Vector4> vertices, int component) {
ClipPolygon(vertices, component, 1);
if (vertices.Count == 0)
return false;
ClipPolygon(vertices, component, -1);
return vertices.Count > 0;
}
private void ClipPolygon(List<Vector4> vertices, int component, float factor) {
var input = new List<Vector4>(vertices);
vertices.Clear();
Vector4 prev = input[input.Count - 1];
float prevComp = prev[component] * factor;
bool prevInside = prevComp <= prev.w;
foreach (var cur in input) {
float curComp = cur[component] * factor;
bool curInside = curComp <= cur.w;
if (curInside ^ prevInside) {
float lerpAmt = (prev.w - prevComp) / ((prev.w - prevComp) - (cur.w - curComp));
vertices.Add(Vector4.Lerp(prev, cur, lerpAmt));
}
if (curInside) {
vertices.Add(cur);
}
prev = cur;
prevComp = curComp;
prevInside = curInside;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment