import math
import bezier, physik, Lsystem, pyg
from physik import *


def build_L(chien,lon=15.0):
	stack = []
	a,b = ball(1000,2000),ball(1000,1900)
	l = []
	s = [spring(a,b)]
	r = 0.0
	x,y = 1000,1900
	bezlst = []
	bezone = [a,b]
	for i in chien:
		if i == "+":
			r = r - (math.pi/7)
		elif i == "-":
			r = r + (math.pi/7)
		elif i == "[":
			stack.append((x,y,r,a,b))
			bezlst.append(bezone)
			bezone = [a,b]
		elif i == "]":
			x,y,r,a,b = stack.pop()
			bezlst.append(bezone)
			bezone = [a,b]
		elif (i=="F") or (i =="E"):
			y = y - (lon * math.cos(r))
			x = x + (lon * math.sin(r))
			c = ball(x,y)
			l.append(c)
			s.append(spring(c,b))
			s.append(spring(c,a))
			a = b
			b = c
			bezone.append(c)
	bezlst.append(bezone)
	return bezlst,l,s
	
if __name__ == "__main__":

	tree = "X"
	rule = [("X" , "F-[[X]+X]+F[+FX]-X"), ("F" , "FF")]
	tree = "E"
	rule = [("F", "FF"), ("E", "F[+E]-E")]
	tree = "F"
	rule = [("F","F[-F]F[+F][F]")]
	#~ tree = "F"
	#~ rule = [("F","FF-[-F+F+F]+[+F-F-F]")]
	tree = "F"
	rule = [("F", "F[+F]F[-F]F")]

	for i in range(3):
		tree=Lsystem.iterate(tree,rule)
		print(tree)

	w,l,s = build_L(tree,60)
	windr = 0.0
	while pyg.main():
		for i in s:
			#pyg.line(i.b1.x, i.b1.y, i.b2.x, i.b2.y)
			i.pull()
		for i in l:
			#pyg.circle(int(i.x),int(i.y))
			i.move()
			#gravity
			i.vy += 0.00618
			#wind
			#i.vx +=0.1
			windr = math.fabs(math.pi/360)
			i.vx += (0.1*math.sin(windr))
			#wall(i,pyg.width,pyg.height)
		for i in w:
			n= []
			for p in i:
				n.append((p.x,p.y))
			for (x,y) in bezier.bezier(n):
				pyg.plot(x,y)


