Advertisement
BanyRule

Clipping Poligon

Jan 5th, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.18 KB | None | 0 0
  1. # Sutherland-Hodgman algorithm for
  2. def clip(subjectPolygon, clipPolygon):
  3.    def inside(p):
  4.       return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])
  5.  
  6.    def computeIntersection():
  7.       dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]
  8.       dp = [ s[0] - e[0], s[1] - e[1] ]
  9.       n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
  10.       n2 = s[0] * e[1] - s[1] * e[0]
  11.       n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
  12.       return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]
  13.  
  14.    outputList = subjectPolygon
  15.    cp1 = clipPolygon[-1]
  16.  
  17.    for clipVertex in clipPolygon:
  18.       cp2 = clipVertex
  19.       inputList = outputList
  20.       outputList = []
  21.       s = inputList[-1]
  22.  
  23.       for subjectVertex in inputList:
  24.          e = subjectVertex
  25.          if inside(e):
  26.             if not inside(s):
  27.                outputList.append(computeIntersection())
  28.             outputList.append(e)
  29.          elif inside(s):
  30.             outputList.append(computeIntersection())
  31.          s = e
  32.       cp1 = cp2
  33.    return(outputList)
  34.  
  35. a = [[50,150],[200,50],[350,150],[350,300],[250,300,],[200,250],[150,350],[100,250],[100,200]]
  36. b = [[100,100],[300,100],[300,300],[100,300]]
  37. print(clip(a, b))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement