Skip to content

Instantly share code, notes, and snippets.

@YellowAfterlife
Created August 28, 2014 22:25
Show Gist options
  • Save YellowAfterlife/35a092749d8ff886bd12 to your computer and use it in GitHub Desktop.
Save YellowAfterlife/35a092749d8ff886bd12 to your computer and use it in GitHub Desktop.
/**
* Draws a "square" to given Graphics object.
* @param g Graphics object to draw in
* @param x X position of square (px)
* @param y Y position of square (px)
* @param z Size of square (px)
* @param a Top-left value (0..1)
* @param b Top-right value (0..1)
* @param c Bottom-left value (0..1)
* @param d Bottom-right value (0..1)
* @return
*/
public function drawSq(g:Graphics, x:Float, y:Float, z:Float,
a:Float, b:Float, c:Float, d:Float):Bool {
var f = (a > 0.5 ? 1 : 0) | (b > 0.5 ? 2 : 0) | (c > 0.5 ? 4 : 0) | (d > 0.5 ? 8 : 0),
p, x1, x2, y1, y2;
inline function lerp(u:Float, v:Float) {
return u == v ? .5 : (.5 - u) / (v - u);
}
inline function moveTo(u:Float, v:Float) g.moveTo(x + u * z, y + v * z);
inline function lineTo(u:Float, v:Float) g.lineTo(x + u * z, y + v * z);
inline function triangle(x1, y1, x2, y2, x3, y3) {
moveTo(x1, y1); lineTo(x2, y2); lineTo(x3, y3);
}
inline function quad(x1, y1, x2, y2, x3, y3, x4, y4) {
moveTo(x1, y1); lineTo(x2, y2); lineTo(x3, y3); lineTo(x4, y4);
}
inline function pent(x1, y1, x2, y2, x3, y3, x4, y4, x5, y5) {
moveTo(x1, y1); lineTo(x2, y2); lineTo(x3, y3); lineTo(x4, y4); lineTo(x5, y5);
}
switch (f) {
// outer corners:
case 1: triangle(0, 0, lerp(a, b), 0, 0, lerp(a, c));
case 2: triangle(lerp(a, b), 0, 1, 0, 1, lerp(b, d));
case 4: triangle(0, lerp(a, c), lerp(c, d), 1, 0, 1);
case 8: triangle(1, lerp(b, d), 1, 1, lerp(c, d), 1);
// sides:
case 3: quad(0, 0, 1, 0, 1, lerp(b, d), 0, lerp(a, c));
case 5: quad(0, 0, lerp(a, b), 0, lerp(c, d), 1, 0, 1);
case 10: quad(lerp(a, b), 0, 1, 0, 1, 1, lerp(c, d), 1);
case 12: quad(0, lerp(a, c), 1, lerp(b, d), 1, 1, 0, 1);
// inner corners:
case 7: pent(0, 0, 1, 0, 1, lerp(b, d), lerp(c, d), 1, 0, 1);
case 13: pent(0, 0, lerp(a, b), 0, 1, lerp(b, d), 1, 1, 0, 1);
case 11: pent(0, 0, 1, 0, 1, 1, lerp(c, d), 1, 0, lerp(a, c));
case 14: pent(lerp(a, b), 0, 1, 0, 1, 1, 0, 1, 0, lerp(a, c));
// diags (pairs of outer corners):
case 6:
triangle(lerp(a, b), 0, 1, 0, 1, lerp(b, d));
triangle(lerp(c, d), 1, 0, 1, 0, lerp(a, c));
case 9:
triangle(0, 0, lerp(a, b), 0, 0, lerp(a, c));
triangle(1, lerp(b, d), 1, 1, lerp(c, d), 1);
// all and none:
case 15: quad(0, 0, 1, 0, 1, 1, 0, 1);
default: return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment