1 ! Copyright (c) 2012 Anonymous
2 ! See http://factorcode.org/license.txt for BSD license.
4 USING: accessors arrays calendar colors kernel locals math
5 math.constants math.functions math.rectangles math.vectors
6 opengl sequences system timers ui ui.gadgets ui.render ;
8 IN: rosetta-code.animate-pendulum
10 ! http://rosettacode.org/wiki/Animate_a_pendulum
12 ! One good way of making an animation is by simulating a
13 ! physical system and illustrating the variables in that system
14 ! using a dynamically changing graphical display. The classic such
15 ! physical system is a simple gravity pendulum.
17 ! For this task, create a simple physical model of a pendulum
24 : current-time ( -- time ) nano-count -9 10^ * ;
26 : T0 ( -- T0 ) 2 pi l g / sqrt * * ;
27 : omega0 ( -- omega0 ) 2 pi * T0 / ;
28 : theta ( -- theta ) current-time omega0 * cos theta0 * ;
30 : relative-xy ( theta l -- xy )
31 [ [ sin ] [ cos ] bi ]
32 [ [ * ] curry ] bi* bi@ 2array ;
33 : theta-to-xy ( origin theta l -- xy ) relative-xy v+ ;
35 TUPLE: pendulum-gadget < gadget alarm ;
37 : O ( gadget -- origin ) rect-bounds [ drop ] [ first 2 / ] bi* 0 2array ;
38 : window-l ( gadget -- l ) rect-bounds [ drop ] [ second ] bi* ;
39 : gadget-xy ( gadget -- xy ) [ O ] [ drop theta ] [ window-l ] tri theta-to-xy ;
41 M: pendulum-gadget draw-gadget*
43 [ O ] [ gadget-xy ] bi gl-line ;
45 M: pendulum-gadget graft* ( gadget -- )
48 dup [ relayout-1 ] curry
49 20 milliseconds every >>alarm drop
52 M: pendulum-gadget ungraft*
53 [ alarm>> stop-timer ] [ call-next-method ] bi ;
55 : <pendulum-gadget> ( -- gadget )
57 { 500 500 } >>pref-dim ;
59 MAIN-WINDOW: pendulum-main
60 { { title "pendulum" } }
61 <pendulum-gadget> >>gadgets ;