from visual import *

#----- Set These Values in Meters, Seconds, Kilograms-----
len=0.50 #meters
grav = 9.81 #meters per second^2
mass = 0.200 #kilograms
pull_back=0.30 #meters
#----------------------------
# T-m*g*cos(a)=m*v**2/L
# m*ax=-T*sin(a)
# m*ay=T*cos(a)-m*g
friction_const=0.5
ball_radius=0.025
pi=3.14159
d2r=pi/180.0
r2d=1.0/d2r
angle=arctan(pull_back/len)*r2d
scene.background=(1,1,1)
ceiling = box(pos=(0,0,0), length=0.5, height=0.01, width=0.5, color=color.blue)
ballx=len*sin(angle*d2r)
bally=-len*cos(angle*d2r)
air_density=1.29
kvalue=0.5*friction_const*air_density*3.14159*ball_radius**2/mass
ball = sphere(pos=(ballx,bally,0), radius=ball_radius, color=color.red)
pointer=arrow(pos=(0,0,0),axis=(ballx,bally,0), color=color.black, shaftwidth=0.005, headwidth=0.005)
ball.velocity = vector(0,0,0)
vold = vector(0,0,0)
dt = 0.001
time0=0
time=0.0
scene.autoscale=0
scene.uniform=1
done=0
while 1:
    rate(100)
    vold=ball.velocity
    stheta=ball.pos.x/len
    ctheta=-ball.pos.y/len
    vmag2=(vold.x**2+vold.y**2)
    vmag=vmag2**0.5
    tension=grav*ctheta+(vmag2/len)
    ax=-tension*stheta-kvalue*vmag*vold.x
    ay=tension*ctheta-grav-kvalue*vmag*vold.y
    ball.acceleration=vector(ax,ay,0)
    if (done==0):
        ball.velocity=vold+ball.acceleration*0.5*dt
        done=1
    else:
        ball.velocity=vold+ball.acceleration*dt
    ball.pos = ball.pos + ball.velocity*dt
    pointer.axis=ball.pos
    angle=arctan(-ball.pos.x/ball.pos.y)*r2d
    time=time+dt
    if ((vold.x>0) and (ball.velocity.x<=0)):
      print "Period ",time-time0," Angle ",angle," degrees"
      time0=time