Newer
Older
DungeonShooting / addons / vnen.tiled_importer / polygon_sorter.gd
@小李xl 小李xl on 21 May 2022 2 KB 安装Tiled插件
  1. # The MIT License (MIT)
  2. #
  3. # Copyright (c) 2018 George Marques
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in all
  13. # copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22.  
  23. # Sorter for polygon vertices
  24. tool
  25. extends Reference
  26.  
  27. var center
  28.  
  29. # Sort the vertices of a convex polygon to clockwise order
  30. # Receives a PoolVector2Array and returns a new one
  31. func sort_polygon(vertices):
  32. vertices = Array(vertices)
  33.  
  34. var centroid = Vector2()
  35. var size = vertices.size()
  36.  
  37. for i in range(0, size):
  38. centroid += vertices[i]
  39.  
  40. centroid /= size
  41.  
  42. center = centroid
  43. vertices.sort_custom(self, "is_less")
  44.  
  45. return PoolVector2Array(vertices)
  46.  
  47. # Sorter function, determines which of the poins should come first
  48. func is_less(a, b):
  49. if a.x - center.x >= 0 and b.x - center.x < 0:
  50. return false
  51. elif a.x - center.x < 0 and b.x - center.x >= 0:
  52. return true
  53. elif a.x - center.x == 0 and b.x - center.x == 0:
  54. if a.y - center.y >= 0 or b.y - center.y >= 0:
  55. return a.y < b.y
  56. return a.y > b.y
  57.  
  58. var det = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y)
  59. if det > 0:
  60. return true
  61. elif det < 0:
  62. return false
  63.  
  64. var d1 = (a - center).length_squared()
  65. var d2 = (b - center).length_squared()
  66.  
  67. return d1 < d2