Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
Bezier Curve code — Gideros Forum

Bezier Curve code

fawzmafawzma Member
edited February 2012 in Code snippets
Here's a quick sample for doing bezier curves.

Change the mu value from 0 to 1.
--[[
	bezier.lua
	<a href="http://www.fawzma.com" rel="nofollow">http://www.fawzma.com</a>
 
	source ported from <a href="http://paulbourke.net/geometry/bezier/index2.html" rel="nofollow">http://paulbourke.net/geometry/bezier/index2.html</a>	
 
	stage:addChild(drawB3({x=10,y=10},{x=100,y=100},{x=200,y=10},0.01))
	stage:addChild(drawB4({x=10,y=10},{x=100,y=100},{x=150,y=50},{x=200,y=250},0.01))
--]]
 
 
function drawB3(p1,p2,p3,mu)
	curve = Shape.new()
	curve:setLineStyle(1,0xff0000,0.5)
	curve:beginPath()
	curve:moveTo(p1.x,p1.y)
	for i = 0,1,mu do
		local p = bezier3(p1,p2,p3,i)
		curve:lineTo(p.x,p.y)
	end
	curve:endPath()
 
	return curve
end
 
function drawB4(p1,p2,p3,p4,mu)
	curve = Shape.new()
	curve:setLineStyle(1,0xff0000,0.5)
	curve:beginPath()
	curve:moveTo(p1.x,p1.y)
	for i = 0,1,mu do
		local p = bezier4(p1,p2,p3,p4,i)
		curve:lineTo(p.x,p.y)
	end
	curve:endPath()
 
	return curve
end
 
function bezier3(p1,p2,p3,mu)
	local mum1,mum12,mu2
	local p = {}
	mu2 = mu * mu
	mum1 = 1 - mu
	mum12 = mum1 * mum1
	p.x = p1.x * mum12 + 2 * p2.x * mum1 * mu + p3.x * mu2
	p.y = p1.y * mum12 + 2 * p2.y * mum1 * mu + p3.y * mu2
	--p.z = p1.z * mum12 + 2 * p2.z * mum1 * mu + p3.z * mu2
 
	return p
end
 
function bezier4(p1,p2,p3,p4,mu)
   local mum1,mum13,mu3;
   local p = {}
 
   mum1 = 1 - mu
   mum13 = mum1 * mum1 * mum1
   mu3 = mu * mu * mu
 
   p.x = mum13*p1.x + 3*mu*mum1*mum1*p2.x + 3*mu*mu*mum1*p3.x + mu3*p4.x
   p.y = mum13*p1.y + 3*mu*mum1*mum1*p2.y + 3*mu*mu*mum1*p3.y + mu3*p4.y
   --p.z = mum13*p1.z + 3*mu*mum1*mum1*p2.z + 3*mu*mu*mum1*p3.z + mu3*p4.z
 
   return p	
end
 
function bezier(p,n,mu)
	-- p = {{x=1,y=1},{x=2,y=2},{x=3,y=4}}
   local k,kn,nn,nkn
   local blend,muk,munk
   local b = {0.0,0.0,0.0}
 
   local muk = 1
   local munk = math.pow(1-mu,n)
 
	for k=0,k<=n,1 do
      nn = n
      kn = k
      nkn = n - k
      blend = muk * munk
      muk = muk * mu
      munk = munk / (1-mu)
      while nn >= 1 do
         blend = blend * nn
         nn = nn - 1
         if kn > 1 then
            blend = blend / kn
            kn = kn -1
         end
         if nkn > 1 then
            blend = blend / nkn
            nkn = nkn - 1
         end
      end
      b.x = b.x + p[k].x * blend
      b.y = b.y + p[k].y * blend
      b.z = b.z + p[k].z * blend
   end
 
   return b	
end
How do you wrap code on this forum?
Tagged:

Comments

Sign In or Register to comment.