Files
mrugesh 91df817cfe fix(guide) add stubs, update spellings and prepare for move (#36531)
* fix(guide) add stubs and correct file path misspellings and pr… (#36528)

* fix: corrected file path to match curriculum

* fix: renamed to newer challenge name

* fix: added solutions to articles from challenge files

* fix: added missing .english to file name

* fix: added missing title to guide article

* fix: correct solution for guide article

* fix: replaced stub with hint

* fix: added space in Hint headers

* fix: added solution to guide article

* fix: added solution to guide article

* test: replaced stub with hint and solution

* fix: add Problem number: to title

* fix: changed generatorexponential to correct name

* fix: renamed knight's tour to knights-tour

* fix: updated guide article
2019-07-30 00:25:58 +05:30

1.3 KiB

title
title
Sutherland-Hodgman polygon clipping

Sutherland-Hodgman polygon clipping


Solutions

Solution 1 (Click to Show/Hide)
function clip(subjectPolygon, clipPolygon) {
  var cp1, cp2, s, e, i, j;
  var inside = function(p) {
    return (cp2[0] - cp1[0]) * (p[1] - cp1[1]) > (cp2[1] - cp1[1]) * (p[0] - cp1[0]);
  };
  var intersection = function() {
    var dc = [cp1[0] - cp2[0], cp1[1] - cp2[1]],
      dp = [s[0] - e[0], s[1] - e[1]],
      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0],
      n2 = s[0] * e[1] - s[1] * e[0],
      n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]);
    return [(n1 * dp[0] - n2 * dc[0]) * n3, (n1 * dp[1] - n2 * dc[1]) * n3];
  };
  var outputList = subjectPolygon;
  cp1 = clipPolygon[clipPolygon.length - 1];
  for (j in clipPolygon) {
    var cp2 = clipPolygon[j];
    var inputList = outputList;
    outputList = [];
    s = inputList[inputList.length - 1]; //last on the input list
    for (i in inputList) {
      var e = inputList[i];
      if (inside(e)) {
        if (!inside(s)) {
          outputList.push(intersection());
        }
        outputList.push(e);
      } else if (inside(s)) {
        outputList.push(intersection());
      }
      s = e;
    }
    cp1 = cp2;
  }
  return outputList.map(e => e.map(f => Math.round(f * 1000) / 1000));
}