Polygon split/cut/slice

Showcase your libraries, tools and other projects that help your fellow love users.
Post Reply
User avatar
markgo
Party member
Posts: 190
Joined: Sat Jan 05, 2013 12:21 am
Location: USA

Polygon split/cut/slice

Post by markgo »

There is an old demo for polygon splitting. The code is messy so I made my own and turned it into a small module. Very simple to use. Just plug in your cut line endpoints and the vertices of your polygon. CONVEX ONLY

Code: Select all

Usage:

table_of_polygons = polygoncut(cut_vertices,polygon_vertices)

polygons = polygoncut({x1,y1,x2,y2},{px,py,px1,py1,px2,py2,...})

for i,polygon in ipairs(polygons) do
	love.graphics.polygon('fill',unpack(polygon))
end
The module:

Code: Select all

local insert= table.insert

local function cross(dx,dy,dx2,dy2)
	return dx*dy2-dy*dx2
end

local polygonCut = function(cvertices,pvertices)
	local plen     = #pvertices
	local x,y,x2,y2= unpack(cvertices)
	local dx,dy    = x2-x,y2-y
	local polygons = {{},{}}
	local set      = polygons[1]
	local intersections = 0
	for i = 1,plen,2 do
		local x3,y3,x4,y4= pvertices[i],pvertices[i+1],pvertices[i+2] or pvertices[1],pvertices[i+3] or pvertices[2]
		insert(set,x3) insert(set,y3)
		local dx2,dy2    = x4-x3,y4-y3
		local denom      = cross(dx,dy,dx2,dy2)
		if denom ~= 0 then
			local tnum = cross((x3-x),(y3-y),dx2,dy2)
			local unum = cross((x3-x),(y3-y),dx,dy)
			local ct,pt= tnum/denom,unum/denom
			if ct >= 0 and ct <= 1 and pt >= 0 and pt <= 1 then
				local ix,iy = x+ct*dx,y+ct*dy
				if pt ~= 1 then
					if pt ~= 0 then
						insert(set,ix) insert(set,iy)
					end
					set = set == polygons[1] and polygons[2] or polygons[1]
					insert(set,ix) insert(set,iy)
					intersections = intersections+1
					
				end
			end
		end
	end
	if intersections == 2 then return polygons end
end

return polygonCut
Attachments
polygon_cut.love
(1.53 KiB) Downloaded 150 times
User avatar
Davidobot
Party member
Posts: 1226
Joined: Sat Mar 31, 2012 5:18 am
Location: Oxford, UK
Contact:

Re: Polygon split/cut/slice

Post by Davidobot »

Awesome!
PM me on here or elsewhere if you'd like to discuss porting your game to Nintendo Switch via mazette!
personal page and a raycaster
User avatar
Roland_Yonaba
Inner party member
Posts: 1563
Joined: Tue Jun 21, 2011 6:08 pm
Location: Ouagadougou (Burkina Faso)
Contact:

Re: Polygon split/cut/slice

Post by Roland_Yonaba »

Great job, Ngo. Great!
I remember I tried once something similar, and I failed miserably.
If you're willing to git it, let us know, so that I can drop some suggestions when I have some.
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 82 guests