26F-Studio / Zenitha

BSD 3-Clause "New" or "Revised" License
10 stars 6 forks source link

Add "Is Point In Polygon?" in mathExtend.lua #3

Closed Not-A-Normal-Robot closed 1 year ago

Not-A-Normal-Robot commented 1 year ago

i found this function in the public domain https://love2d.org/forums/viewtopic.php?p=236582&sid=33f2e78acfbc738ac4b4b9a83488cc6f#p236582

-- By Pedro Gimeno, donated to the public domain
function isPointInPolygon(x, y, poly)
  local x1, y1, x2, y2
  local len = #poly
  x2, y2 = poly[len - 1], poly[len]
  local wn = 0
  for idx = 1, len, 2 do
    x1, y1 = x2, y2
    x2, y2 = poly[idx], poly[idx + 1]

    if y1 > y then
      if (y2 <= y) and (x1 - x) * (y2 - y) < (x2 - x) * (y1 - y) then
        wn = wn + 1
      end
    else
      if (y2 > y) and (x1 - x) * (y2 - y) > (x2 - x) * (y1 - y) then
        wn = wn - 1
      end
    end
  end
  return wn % 2 ~= 0 -- even/odd rule
end

also if you change wn % 2 ~= 0 to wn ~= 0 it'll become the non-zero winding rule

MrZ626 commented 1 year ago

I've seen this algorithm before, great

Not-A-Normal-Robot commented 1 year ago

what about zframework, which is still used by techmino?

MrZ626 commented 1 year ago

I don't think it has a chance to be used

Not-A-Normal-Robot commented 1 year ago

I used that function for making the star collision detection in https://github.com/26F-Studio/Techmino/pull/778

MrZ626 commented 1 year ago

😨 okay

Not-A-Normal-Robot commented 1 year ago

also maybe you can have 2 output variables: 1st one is non-zero rule and the 2nd one is the even/odd rule

MrZ626 commented 1 year ago

I think so time to push -f

Not-A-Normal-Robot commented 1 year ago

looks good