Guides/Window Driver/Animation/Animated Plot

From J Wiki
Jump to navigation Jump to search

Here's an example showing an animated plot running in a child control. -- tangentstorm

NB. -------------------------------------------------
NB. animated sine plot in J
NB.   by michal wallace (
NB.   free for use under the MIT license
NB. -------------------------------------------------

coinsert each 'jgl2'; 'jzplot'

pc =: 'w0'                  NB. name of parent control (window)
pn =: 'animated plot'       NB. parent name (window title)
cc =: 'g0'                  NB. name of child control (isidraw canvas)
wh =: 720 200               NB. width and height of the window

n =: 0x                     NB. tick counter
s =: 0$0                    NB. series to plot

update =: verb define       NB. build a series for a sine wave
  s =: 1 o. (n =: n + 1) + 0.1 * i: 100

render =: verb define       NB. put pd commands here
  pd 'frame 1; axes 1 1; labels 0 0;'
  pd 'color red'
  pd s

NB. -------------------------------------------------
NB. everything below here is pretty much boilerplate
NB. ------------------------------------------------

trap_z_ =: verb define      NB. halt timer to avoid infinite modal error msg death loop
  wd 'timer 0'
  smoutput LF,(13!:12''),'timer stopped.' [ wd 'timer 0'

signal_jzplot_=:13!:8&12 [ trap

3 : 0'' NB. create the window if it doesn't exist
 if. -. wdisparent pc do.
   wd 'pc ',pc,' closeok; pn "',pn,'";'
   wd 'minwh ',(":wh),'; cc ',cc,' isidraw flush;'
   wd 'pshow; pcenter;'

to_pc =: verb define        NB. choose where to draw pd commands
  wd 'psel ', PForm_jzplot_=: pc
  PFormhwnd_jzplot_ =: wd 'qhwndp'
  PIdhwnd_jzplot_ =: wd 'qhwndc ', PId_jzplot_=: cc
  pd 'reset ',pc

paint =: verb define        NB. repaint current window on demand
  glpaint @ ppaint''

step =: verb define         NB. animation engine, with error trap
  try. paint render to_pc [ update'' 
  catch. trap'' end.

sys_timer_z_ =: step_base_ 
wd 'timer 100'       NB. set to 0 to stop the timer