Skip to content

Instantly share code, notes, and snippets.

@dermotbalson
Created November 14, 2015 00:22
Show Gist options
  • Save dermotbalson/7a5988ff80924d3a7c23 to your computer and use it in GitHub Desktop.
Save dermotbalson/7a5988ff80924d3a7c23 to your computer and use it in GitHub Desktop.
Is point in triangle
function setup()
A={}
n=10000
for i=1,n do
A[i]=vec2(math.random(0,WIDTH),math.random(0,HEIGHT))
end
v1,v2,v3=vec2(445,30),vec2(150,500),vec2(600,600)
parameter.integer("Method",1,4,1)
methods={IsPointInTriangleBary,IsPointInTrianglePara,IsPointInTriangleDot,IsPointInTriangleDot2}
local n1=vec2(v2.y-v1.y,v1.x-v2.x)
local n2=vec2(v1.y-v3.y,v3.x-v1.x)
for j=1,4 do
f=methods[j]
t=os.time()
for i=1,n do
a=f(A[i],v1,v2,v3,n1,n2)
end
print(j,os.time()-t,(os.time()-t)*60/n)
end
end
function draw()
--[
background(150)
strokeWidth(2) stroke(0)
line(v1.x,v1.y,v2.x,v2.y)
line(v1.x,v1.y,v3.x,v3.y)
line(v3.x,v3.y,v2.x,v2.y)
f=methods[Method]
local n1=vec2(v2.y-v1.y,v1.x-v2.x)
local n2=vec2(v1.y-v3.y,v3.x-v1.x)
for i=1,1000 do
if f(A[i],v1,v2,v3,n1,n2) then fill(0,0,255) else fill(255,0,0) end
ellipse(A[i].x,A[i].y,10)
end
--]]
end
function IsPointInTriangleBary(p,p1,p2,p3)
local x,y,x1,y1,x2,y2,x3,y3=p.x,p.y,p1.x,p1.y,p2.x,p2.y,p3.x,p3.y
local d=((y2 - y3)*(x1 - x3) + (x3 - x2)*(y1 - y3))
local a = ((y2 - y3)*(x - x3) + (x3 - x2)*(y - y3)) / d
if a<0 or a>1 then return false end
local b = ((y3 - y1)*(x - x3) + (x1 - x3)*(y - y3)) / d
if b<0 or b>1 then return false end
local c = 1 - a - b
if c<0 or c>1 then return false else return true end
end
function IsPointInTrianglePara(p,p1,p2,p3)
local x,y,x1,y1,x2,y2,x3,y3=p.x,p.y,p1.x,p1.y,p2.x,p2.y,p3.x,p3.y
local d=(x1*(y2 - y3) + y1*(x3 - x2) + x2*y3 - y2*x3)
t1 = (x*(y3 - y1) + y*(x1 - x3) - x1*y3 + y1*x3) / d
if t1<0 or t1>1 then return false end
t2 = (x*(y2 - y1) + y*(x1 - x2) - x1*y2 + y1*x2) / -d
if t2<0 or t2>1 then return false end
if t1 + t2 <= 1 then return true else return false end
end
function IsPointInTriangleDot(p,p1,p2,p3)
local x,y,x1,y1,x2,y2,x3,y3=p.x,p.y,p1.x,p1.y,p2.x,p2.y,p3.x,p3.y
local side= function(x1, y1, x2, y2, x, y)
return (y2 - y1)*(x - x1) + (-x2 + x1)*(y - y1)>=0
end
if not side(x1, y1, x2, y2, x, y) then return false end
if not side(x2, y2, x3, y3, x, y) then return false end
if not side(x3, y3, x1, y1, x, y) then return false end
return true
end
function IsPointInTriangleDot2(p,p1,p2,p3,n1,n2) --p1 must be camera position, p2 is left far end
local a=p-p1
if n1:dot(a)<0 or n2:dot(a)<0 then return false else return true end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment