from JiScript import *
import math

def r(theta):
    return 1.0/(1+eccentricity*math.cos(theta))

def position(p):
    p.beginpage()

    p.gsave()
    p.setfont(12)
    p.moveto(p.width()-5, 5)
    string = "Position"
    p.shift(-1, string)
    p.show(string)
    p.grestore()

    p.center()
    p.scale(60)

    p.gsave()
    p.newpath()
    p.moveto(-2, 0);  p.lineto(2, 0)
    p.moveto(0, -2);  p.lineto(0, 2)
    p.stroke(0.8)
    p.grestore()

    p.gsave()
    p.newpath()
    p.graph([lambda theta: r(theta)*math.cos(theta),
             lambda theta: r(theta)*math.sin(theta)],
            0, 2*math.pi)
    p.closepath()
    p.setlinewidth(2)
    p.stroke()
    p.grestore()

    x = r(theta)*math.cos(theta)
    y = r(theta)*math.sin(theta)

    p.gsave()
    p.translate(x, y)
    p.newpath()
    p.arrow(-math.sin(theta),
            math.cos(theta)+eccentricity, 0.05, 0.15)
    p.fill([1,0,0])
    p.stroke()
    p.grestore()

    p.gsave()
    p.newpath()
    p.arrow(x, y, 0.05, 0.15)
    p.fill([0,0,1])
    p.stroke()
    p.grestore()
        
    p.endpage()

def velocity(p):
    p.beginpage()
    
    p.gsave()
    p.setfont(12)
    p.moveto(p.width()-5, 5)
    string = "Velocity"
    p.shift(-1, string)
    p.show(string)
    p.grestore()

    p.center()
    p.scale(60)

    p.gsave()
    p.newpath()
    p.moveto(-2, 0);  p.lineto(2, 0)
    p.moveto(0, -2);  p.lineto(0, 2)
    p.stroke(0.8)
    p.grestore()

    p.gsave()
    p.newpath()
    p.arrow(-math.sin(theta),
            math.cos(theta)+eccentricity, 0.05, 0.15)
    p.fill([1,0,0])
    p.stroke()
    p.grestore()

    p.gsave()
    p.newpath()
    p.circle(0, eccentricity, 1)
    p.setlinewidth(2)
    p.stroke()
    p.grestore()

    p.endpage()

def begin():
    starttimer()

def pause():
    stoptimer()
        
def reset():
    global theta
    stoptimer()
    theta = 0
    refresh()

def update():
    global theta
    p = [r(theta)*math.cos(theta),
         r(theta)*math.sin(theta)]
    v = [-math.sin(theta), math.cos(theta)+eccentricity]
    dt = 0.025
    theta = math.atan2(p[1] + dt*v[1], p[0] + dt*v[0])
    refresh()

eccentricity = 0.3
theta = 1.5

settimer(25, update)
addbutton("Start", begin)
addbutton("Stop", pause)
addbutton("Reset", reset)
openframe([ [200, 200, position], [200, 200, velocity] ])


