User:Brian Schott/code/turtleGraphics/3D

From J Wiki
Jump to navigation Jump to search

This version no longer works with J8xx and J9xx as openGL has been altered.
Instead a modern openGL version can be found at [|https://github.com/zerowords/tgsjo]
and simply installed as an addon named zerowords/tgsjo .


Download the script here: File:Tgsj3.ijs

NB. key turtle commands              ***************
NB. yw     yaw turtle(s) clockwise
NB. rl     roll turtle(s) clockwise
NB. pt     pitch turtle(s) upward
NB. fd     move turtle(s) forward
NB. bk     move turtle(s) backward
NB. ju     jump turtle(s) upward
NB. jr     jump turtle(s) n the 90 degrees right direction
NB. goto   move turtle(s) to position(s)
NB. home   move turtle(s) to original position(s)
NB. eyeto  move eye(s) to position(s) and alter its(their) gaze
NB. pu     change penstate(s) to up
NB. pd     change penstate(s) to down
NB. pc     change the pencolor(s)
NB. cs     clear the drawing screen
NB. iTS    initialize the turtle population
NB. show   report the state of the turtle(s)
NB. delay  change to slow or speed up drawings

require 'gl2 trig colortab'
coinsert'jgl2 bmsturtle3'

delay =: 6!:3
Delay =: 0.02  NB. change to slow or speed up drawings

NB. set sm =: smoutput to see  intermediate steps of
NB.    some multi-step verbs.
sm =: smoutput
sm =: [

NB. ***********************************************************
NB. Table of Contents
NB. suggesting some example moves    *************** START HERE
NB. setting global parameter values  ***************
NB.    ***begin 'bmsturtle3' locale***
NB. defining some globals            ***************
NB. perspective drawing              ***************
NB. main turtle control              ***************
NB. main graphics initialization     ***************
NB. turtle state dbase verbs         ***************
NB. main graphics update verbs       ***************
NB. setting turtle parameter values  ***************
NB. turtle initialization verbs      ***************
NB. ***********************************************************

NB. Generally verbs, adverbs and conjunctions in this
NB.    script have names starting with lower case;
NB.    nouns have names beginning with upper case
NB.    except local nouns in explict definitions,
NB.    which are often lower case.

NB. suggesting some example moves    ***************

help =: 0 : 0
NB. You can experiment with the system after "running"
NB.   the script file, by placing your cursor on each
NB.   line in turn and pressing Control-r .
NB. It's easier to use the Control-r trick if first
NB.   you copy this information to a "New ijs" window
NB.   (created with "^N").
NB. You should see the graphics screen change and you
NB.   may get feedback on the text .ijx screen, too.

yw 0  NB. shows the turtle's or turtles' heading(s)
fd 0  NB. shows the turtle's or turtles' position(s)
fd 10 _20
yw 30 90
fd 20 10
yw 90 30


cs ''
iTS 2 NB. restores all params to original values
yw 0  NB. shows the turtle's or turtles' heading(s)
fd 0  NB. shows the turtle's or turtles' position(s)
fd 10 _20
yw 30 90
fd 20 10
yw 90 30

cs ''
''[iTS 2 NB. output suppressed with ''[
yw 0
2 repeats fd 5 _5
4 repeats do'yw 90[fd 20'   NB. do argument read from right
4 repeats dO'fd 20[yw 90'   NB. dO argument read from  left
SC =: SC0  NB. reinitialize StateChange database
20 repeats do 'yw 18[5 repeats do ''yw 72[fd 13'''
+/"_1 SC    NB. determine amount of change
avg"_1 SC   NB. determines average change
25 _25 (2 repeats fdyw) 30 30[cs'' NB. "fdyw" has left and right args

cs ''
yw 0
fd 0
penup 0   NB. no change to turtle 1; penup for 0
fd 25 _25
fd 25 _25
show 0

cs ''
''[iTS 3
pendown 2 0  NB. no change to turtle 1, pendown turtles 0 and 2
10 5 _5(5 repeats fdyw) 30 30 30
show 1 2

cs ''
''[iTS _5  NB. negative number for number of turtles!
yw 0

NB. Next example shows a pair of helix-like paths.
NB. The following example extends it slightly.
cs''
tgsj3_run 0
20 (15 repeats poly3)30
2 goto ,: _20 0 1000
2 gazeat ,: 0 0 0
NB. goto and gazeat are combined in "eyeto":
NB.            eyeto ,: _20 0 1000  NB. or
NB. (,: 0 0 0) eyeto ,: _20 0 1000
)

coclass 'bmsturtle3'           NB. give system its own locale


NB. setting global parameter values  ***************

''[do (_11}."1 COLORTABLE),"1 ',:' ,"1] _11{."1 COLORTABLE

Bkgrd =: White
Pengap =: 2
Screen_center =: 500 500
D =: Dimensions =: 3  NB. set 3D system to 3D
ClusterFlag =: 0      NB. changing to 1 speeds up eyeto

NB. 3D eye information
Pe0 =: 0 0 1000
He0 =: 0 0 _90

Eye =: 1               NB. add one turtle for the eye
eye =: Eye&{           NB. must always be changed after Eye

NB. defining some globals            ***************

NB. matrix and vector verbs
mp =: +/ . *
x =: mp"2
mfv =: _3&(]\)"1    NB. matrix from vector
length   =: +/&.:*:"1
sqlength =: +/&: *:"1
nrmlz =: ] % [: length ]

NB. verbs for drawing lines and rotating turtles
tfd =: turtlefromdegrees =: rfd @: (360&|)@:(90&+)  @: -
dft =: degreesfromturtle =: 360&| @: dfr @: (-@:(-&(pi%2)))
dfd =: degreesfromdegrees =: 360&|&.(180&-)

limitTrim =: [<.([:(<0 0)&{"2(>./@:])"2)%6: NB. 1/6th of height
Ls =: limitTrim * [: (%length) |@(-/"2@])

dle =: deleteLastErased =: ([:<^:3#@[-.~ i:){[

NB. perspective drawing              ***************
vfp =: }:%{:   NB. vector from projection
pfv =: ,&1 :. vfp NB. projection from vector

NB. V means (V)iewport
NB. s means (s)creen
NB. S means half-screen (S)ize
NB. D means screen (D)istance from the eye
NB. c means (c)enter for center-size notation

S_s =: 500 500
Vsize =: 500 500
Vcenter =: 500 500

ratio =: (% {."1)~
ratioS =: ratio S_s
V_s =: Vsize  *"1 ratioS
V_c =: Vcenter*"1 ratioS

NB. some parameters
I3 =:  =@i. 3
i3 =: I3"_
I4 =:  =@i. 4
'X Y Z' =: i. 3
'XX YY ZZ' =: 2#"0 i. 3
XYZ =: i. 3

'RlRow YwRow PtRow' =: i. 3
AllRow =: i. 3
PtPlane =: 1 2
YwPlane =: 0 1
RlPlane =: 2 0

NB. for hyp and angle between hyp and side of right triangle
la =: lengthangle =: *.@*@(j./)  NB. extra * provides tolerance
ang =: {:@la
hyp =: {.@la

vfe =: 1 0&(but"0@[ |."1@:{])     NB. distance of view from eye
angFdist =: *@[ * [:dfd@:dfr @:ang"1@] vfe@]

NB. angle between two vectors
sp =: [: +/ *                     NB. sum of products
angle =: [: arccos sp&nrmlz       NB. angle between two vectors
cst =:C.!.2@(#:i.)@:#~
cross1 =: [mp cst@#@[mp]

ywProj =: (([ mp 0&{@]),([ mp 1&{@]))"1 2
ptProj =: (([ mp 1&{@]),([ mp 2&{@]))"1 2
rlProj =: (([ mp 0&{@]),([ mp 2&{@]))"1 2

translate0 =: (-@] , 1:) 3} [
translate =: I4&translate0

but =: [:#&XYZ-.@(XYZ&=)
butbx =: [:<@:;~but
All0Q =: *./@:(0&=)     NB. all values equal 0
nAll0Q =: -.@:All0Q     NB. not all values equal 0
allNNeg =: *./@:(0&<:)  NB. all values nonnegative

axes0y =: (-@{.,{:),:({:-@,{.)
axesy =: axes0y % hyp
yrotaxes0 =: axesy@] (butbx Y)}I4"_
yrotaxes =: (I4"_`yrotaxes0@.nAll0Q)"1

axes0x =: (-@{.,{:),:({:-@,{.)
axesx =: axes0x % hyp
xrotaxes0 =: axesx@] (butbx X)}I4"_
xrotaxes =: (I4"_`xrotaxes0@.nAll0Q)"1

zrotaxes =: xrotaxes

col =: &({"1)                 NB. adverb for columns
a =: X col@[
b =: Y col@[
c =: Z col@[
d =: X col@]
e =: Y col@]
f =: Z col@]

amendcol3 =: (([*{:@])(3}) ])"0 1
den =: >:@:f
T_00 =: den%~(*:@:e)+f+(*:@:f)
T_11 =: den%~(*:@:d)+f+(*:@:f)
T_01 =: den%~[:-e*d
T_30 =: den%~(c*d)+(b*d*e)+(c*d*f)-(a*e*e)+(a*f)+(a*f*f)
T_31 =: den%~(c*e)+(a*d*e)+(c*e*f)-(b*d*d)+(b*f)+(b*f*f)
Tb0 =: T_00,T_01,0:,d
Tb1 =: T_01,T_11,0:,e
Tb2 =: ([:-d),([:-e),0:,f
Tb3 =: T_30,T_31,0:,([:] sp) NB. change ] to - for traditional view
Tb =: Tb0,Tb1,Tb2,:Tb3

NB. unused verb perspective0
perspective0=: dyad define
NB. x is the position of the view
NB. y is the position of the observer
tmp =. x - y
r =. %k =. length tmp
dir =. nrmlz tmp
T =. y Tb"1 dir
T =. r amendcol3 T
if. _1 = f dir
do.
  T =. (y     f dir) ( XX; YY)}"0 2 T
  T =. (y (a,b) dir) (3 0;3 1)}"1 2 T
  T =. (           0) (1 0;0 1)}"1 2 T
end.
T
)

den_00 =: -.@:(*:@:f)
den_01 =: >:@:f
T2_00 =: den_00%~(*:@:e)+f-(f^3:)+(*:@:e)*f
T2_11 =: den_00%~(*:@:d)+f-(f^3:)+(*:@:d)*f
T2_01 =: den_01%~[:-e*d
T2b0 =: T2_00,T2_01,([:-d),0:
T2b1 =: T2_01,T2_11,([:-e),0:
T2b0 =: T2_00,T2_01,d,0:
T2b1 =: T2_01,T2_11,e,0:
T2b2 =: ([:-d),([:-e),f,0:
NB. T2b2 =: d,e,f,0:
T2b3 =: 0:,0:,0:,1:
T2b =: T2b0,T2b1,T2b2,:T2b3

perspective =: dyad define
NB. x is the position of the view
NB. y is the position of the observer
tmp =. x - y
r =. %k =. length tmp
dir =. nrmlz tmp
T1 =. translate y
T2 =. T2b"1 dir
if. 1 = *: f dir do.  T2 =. (f dir) (XX;YY)}"0 2 T2 end.
T3 =. (-k) (<3 2)}"0 2 (# mat x) copies I4
NB. T3 =.  _1  (<3 3)}"0 2 T3
T4 =. ( r) (<2 3)}"0 2 (# mat x) copies I4
T4 =.   0  (<ZZ )}"0 2 T4
NB. smoutput (d,e,f) dir
NB. smoutput T1 ; T2 ; T3 ; T4
T =. T1 x T2 x T3 x T4
t =. -(<3 3){"0 2 T    NB. needed for unusual view position
t (<3 3)}"0 2 T        NB. of the eye in this 3D version
)

see =: monad define
  eyepos =. stateEye 'Position'
  obj =. y
  lines =. x&VN&.:(pfv"1) (4&rankinc obj)[~"1/~ mat eyepos
  Xs =. (X{V_c)+ X col lines
  Ys =. (Y{V_c)+ Y col lines
  t =. Xs,:"2 Ys
)

rx0=: (cos,sin),:(-@sin,cos)
ry0 =: (cos,-@sin),:(sin,cos)
ry0 =: rz0 =: rx0
bip=: <"1@(,"0/~)                 NB. Table of boxed index pairs
bipx =: (bip PtPlane)"_
bipy =: (bip RlPlane)"_
bipz =: (bip YwPlane)"_

rx=: ''&(rx0@]`bipx`i3})"0
ry=: ''&(ry0@]`bipy`i3})"0
rz=: ''&(rz0@]`bipz`i3})"0

ptRot =: rx
rlRot =: ry
ywRot =: rz@:-
NB. extra space in AllRot needed for allRot,
NB.   but must be deleted from rot in turn and advance
AllRot =: ,&' 'each ;:'rlRot ywRot ptRot' NB. for priming Heading
allRot =: [: x/"_1 [: ".&> AllRot"_ ,each"1 [: ] [: <&":"0 ]
A =: @(i.@$@])                            NB. for revising Heading

NB. verbs for checking & massaging input and output nouns
NB.    for verbs and conditions
arow =: ,"1                  NB. append rows
copies =: $,:
yxs =: $~#                   NB. copy x to number of y's
n1s =: ##1:
amend0f1 =: (0:`]`(n1s@[) )} NB. usage: State amend0f1 Eye
pvfc =: [: ; {.&1&.>         NB. Partition vector from count
rankinc =: ,@]$~-@[{.!.1 $@] NB. increase rank of y to x's value
mat =: 2&rankinc             NB. increase rank of y to a matrix
rankincI =: ,:"1             NB. increase rank of y's items
lr=: 3 : '5!:5 <''y'''      NB. linear representation

neqQ =: =&#                  NB. argument #s     equal?
nneQ =: ~:&#                 NB. argument #s not equal?
okvaluesQ =: [:  *./ +./@(=/) NB. check x values against y values
mtQ =: 0&e.@$                NB. empty

changetodown =: -.@[`[`1:  @.(>:@])"0 NB. change pen
changetoup   =: -.@[`[`0:  @.(>:@])"0 NB. change pen

IVC =: InitialVerbCharacters =: a.{~91,97+i. 26
verbB =: [ e.~ [: {.&> [: ;: ] NB. creates a boolean list marking verbs
dO =: IVC&([: ". [: ; [: |. verbB <@(;:^:_1);.1 ;:@])

NB. Fraser Jackson contributed the next three verbs:
NB.  rep, repeat, and (O)on

NB.  rep Generates code to be executed
rep =: 3 : 0
  'n action' =: y
  (n*#action)$action
)

NB.  repeat displays
repeat =: 3 : 0
  ".rep y
)
NB. *then v laminates two vectors otherwise uses join
then =: 4 : 0
  dx =. $$x
  dy =. $$y
  if. (dx>2)+. dy>2 do. 'Domain Error' return. end.
  if. (dx<2)*. dy<2 do. x,:y return. end.
  x,y
)

NB.  square
NB. repeat 4 ; 'fd 30' then 'yw 90'

NB.  rotated squares
NB. repeat 24 ; (rep 4; 'fd 30' then 'yw 90') then 'yw 15'

input =: 1!:1@1:
dOO =: verb define
  90 dOO y
  :
  if. y-:'' do.y =. 5 end.
  select. input''
  case. ,'' do. return.
  case. ,'f' do. fd y
  case. ,'r' do. rl x
  case. ,'y' do. yw x
  case. ,'p' do. pt x
  end.
  x dOO y
)

NB. main turtle control              ***************

NB. The conjunction "change" is used as follows:
NB. rl =: roll  =: RlRow change 'turn'
NB. yw =: yaw   =: YwRow change 'turn'
NB. pt =: pitch =: PtRow change 'turn'
NB.
NB. jr =: jumpright =: RlRow change 'advance'
NB. fd =: forward =: YwRow change 'advance'
NB. ju =: jumpup =: PtRow change 'advance'
NB. These definitions are supplied below,
NB.    below the definitions of their components.

NB.* change c
NB. The conjunction change provides common
NB.    preprocessing for all the turtle movement changes.
NB. The argument n is usually turn or advance
NB. the argument m is usually RlRow, YwRow, or PtRow
change =: conjunction define
  change0 =. '(',(":m),' ',n,') '
  change1 =. 'change0'~
  numS =. i.#State
  turtles =. Eye -.~ numS
  scanmask =. turtles e.~ numS
  if. 1=#y
  do.
    y =. 0 Eye}yxs&State y
    ".  change1, lr y
    return.
  end.
 if. turtles neqQ y
 do.
    ".  change1, lr y #^:_1~ scanmask
   return.
 end.
 if. State neqQ y
 do.
    ".  change1, lr y
   return.
 end.
 if. State nneQ y
 do.
   'Supply ',(":#State),' move values.'
   return.
 end.
 'Your inputs are not understood.'
:
  change0 =. '(',(":m),' ',n,') '
  change1 =. 'change0'~
  numS =. i.#State
  turtles =. Eye -.~ numS
  scanmask =. turtles e.~ numS
x =. ,x
if. (y nneQ x) *. 1~:#y
 do.
 'The number of moves must be 1 or the same as the number of turtles listed.'
 return.
end.
if. (1<#y) *.x nneQ y
do.
 'Supply 1 or ',(":#x),' move values.'
 return.
end.
if. ((#State)<:>./x) do.
 'Supply only turtle values between 0 and ',(":<:#State),' .'
 return.
end.
  if. x nneQ ~: x
  do.
    'Values of x must be unique'
    return.
  end.
 if. x neqQ y
 do.
   tmp =. /: x
   x =. tmp{x
   y =. tmp{y
   scanmask =. x e.~ numS
   ". change1, lr y #^:_1~ scanmask
   return.
 end.
if. (1=#y) *.x nneQ y
do.
   NB. y =. ((#~.x) copies ,y) (~.x)}state trait
   y =. (,(#~.x) copies y) (~.x)}0 #~#State
  ". change1, lr y
  NB. x =. /:~x
  NB. scanmask =. x e.~ numS
  NB. ". change1, lr y #^:_1~ scanmask
 return.
end.
 'Your inputs are not understood.'
)

rl =: roll  =: RlRow change 'turn'
yw =: yaw   =: YwRow change 'turn'
pt =: pitch =: PtRow change 'turn'
rt =: right =: yw
lt =: left  =: yw&- : (yw -)

jr =: jumpright =: RlRow change 'advance'
fd =: forward =: YwRow change 'advance'
ju =: jumpup =: PtRow change 'advance'

jl =: jumpleft =: jr&- : (jr -)
bk =: back =: fd&- : (fd -)
jd =: jumpdown =: ju&- : (ju -)

NB. turn is used to create yw, rl and pt, below
NB.* turn a  degrees of turn for each or all except the Eye turtles
NB. usage: type turn 30  or type turn 30 _60 30 0 for three turtles
NB. the final 0 is for the Eye turtle
turn =: adverb define
  NB. some parameters using the adverb value
  type =. m
  Row =. type  NB. simplified from type&{AllRow
  rot =. (dtb>@(type&{)AllRot)~
  OneHeading =. 'Heading',type&{ 'RHU'

 if. (1=#y) do.
   y =. 0 Eye}yxs&State ,y
 end.
 if. State nneQ ,y do.
   'Supply ',(":#State),' turn values.'
   return.
 end.

 oldH =. Heading

 NB. get State info
 localnames =. 'turtleerase turtlestate heading position turtlesize'
 statenames =. ;:'Turtleerase Turtlestate Heading Position Turtlesize'
 (localnames) =. state each statenames

 NB. erase old turtle
 if. (1<:+/,turtlestate) *. 1<:+/,turtleerase do.
  mask =. (,turtleerase)&#
  lines =. position +"1 TNorth x mfv heading
  plines =. ,"2]|:"2],"2]3 2 4 1|:see mask lines
  State  (] erasedraw"1"2 [: mask [)plines
  t =. (,"2  lines),"1&:mask ,.&:>/ state each ;:'Turtlecolor Pensize Penstyle'
  DrawTList =: DrawTList dle"_1 _ t
 end.

 NB. update SC and State
 C =. SCN aindex OneHeading
 D =. 360|y
 SC =: C aC D
 heading =. (mfv state 'Heading') x~ rot rfd D
 heading state 'Heading'

 NB. draw new turtle
 if. 1<:+/,turtlestate do.
  mask =. (,turtlestate)&#
  lines =. position +"1 TNorth x heading
  plines =. ,"2]|:"2],"2]3 2 4 1|:see mask lines
  State  (] objectdraw"1"2 [: mask [)plines
  t =. (,"2  lines),"1&:mask ,.&:>/ state each ;:'Turtlecolor Pensize Penstyle'
  DrawTList =: DrawTList,"_1 _ t
 end.
 delay Delay
 glshow ''

 NB. update user's information
 tmp =. 360|(y+ Row col oldH) Row col A} oldH
 'Heading';Heading =: dfd tmp
 :
  type =. m
  if. (1=#y) *. (State neqQ ~.x)
  do.
  type turn y#^:_1~x e.~i.#State
 return.
 end.
 )

NB. advance is used to create fd, bk, ju and jr
NB.* advance a movement distance for each or all except the Eye turtles
NB. usage: dir advance 10  or dir advance 10 _10 5 for three turtles
advance =: adverb define
  NB. some parameters using the adverb value
  dir =. m
  Row =. dir
  rot =. (dtb>@(dir&{)AllRot)~
  OneHeading =. 'Heading',dir&{ 'RHU'
  OneDistance =. 'Distance',dir&{ 'RHU'

 if. (1=#y) do.
   y =. 0 Eye}yxs&State y
 end.

 NB. get State info
 localnames =. 'penstate turtleerase turtlestate heading position turtlesize stepsize'
 statenames =. ;:'Penstate Turtleerase Turtlestate Heading Position Turtlesize Stepsize'
 (localnames) =. state each statenames

 NB. erase old turtle
 if. (1<:+/,turtlestate) *. 1<:+/,turtleerase do.
  mask =. (,turtleerase)&#
  lines =. position +"1 TNorth x mfv heading
  plines =. ,"2]|:"2],"2]3 2 4 1|:see mask lines
  State  (] erasedraw"1"2 [: mask [)plines
  t =. (,"2  lines),"1&:mask ,.&:>/ state each ;:'Turtlecolor Pensize Penstyle'
  DrawTList =: DrawTList dle"_1 _ t
 end.

 NB. update SC and State
 oldposition =. position
 C =. SCN aindex OneDistance
 D =. , stepsize*y
 SC =: C aC D
 position =. oldposition + D * state OneHeading
 position state 'Position'

 NB. draw new path
 maskS =. maskT =. (,penstate)&#
 if. StereoFlag do. maskS =. eye end.
 if. 1<:+/,penstate do.
  lines =. oldposition ; position
  plines =. ,."_1&>/ ,"2@:(2 1&|:)each,"2 each see&:rankincI each maskT each lines
 if. StereoFlag do.
  State  (([: maskS [) linesdraw"1 ])plines
else.
  State  (([: maskS [) linesdraw"1"2 ])plines
end.
  t =. maskT (,.&>/lines) ,. ,.&:>/ state each ;:'Pencolor Pensize Penstyle'
  DrawPathList =: DrawPathList, t
 end.

 NB. draw new turtle
 if. 1<:+/,turtlestate do.
  mask =. (,turtlestate)&#
  lines =. position +"1 TNorth x mfv heading
  plines =. ,"2]|:"2],"2]3 2 4 1|:see mask lines
  State  (] objectdraw"1"2 [: mask [)plines
  t =. (,"2  lines),"1&:mask ,.&:>/ state each ;:'Turtlecolor Pensize Penstyle'
  DrawTList =: DrawTList,"_1 _ t
 end.
 delay Delay
 glshow ''

 delay Delay
 glshow ''

 NB. update user's information
 'Position';Position =: state  'Position'
 :
  dir =. m
  if. (1=#y) *. (State neqQ ~.x)
  do.
  dir advance y#^:_1~x e.~i.#State
 return.
 end.
)

NB. The conjunction "status" is used as follows:
NB. goto =: 'Position' status 'goto0'
NB. gazeat =: 'Position' status 'gazeat0'
NB. These definitions are supplied below,
NB.    below the definitions of their components.

status =: conjunction define
  trait =. m
  status0 =. n,' '
  status1 =. 'status0'~
  numS =. i.#State
  turtles =. Eye -.~ numS
  if. 2>#$y
  do.
    'The rank of the right argument must be 2: eg ,:100 200 0'
  end.
  if. 1=#y
  do.
    y =. (,y) turtles}state trait
    ".  status1, lr y
    return.
  end.
 if. turtles neqQ y
 do.
   y =. y turtles}state trait
    ".  status1, lr y
   return.
 end.
 if. State neqQ ~.y
 do.
    ".  status1, lr y
   return.
 end.
 if. State nneQ y
 do.
   'Supply ',(":#State),' goto values.'
   return.
 end.
 'Your inputs are not understood.'
:
  trait =. m
  status0 =. n,' '
  status1 =. 'status0'~
  numS =. i.#State
  turtles =. Eye -.~ numS
  x =. ,x
  if. 2>#$y
  do.
    'The rank of the right argument must be 2: eg ,:100 200 0'
 return.
  end.
if. (y nneQ x) *. 1~:#y
do.
 'The number of traits must be 1 or the same as the number of turtles listed.'
 return.
end.
if. (1<#y) *.x nneQ y
do.
 'Supply 1 or ',(":#x),' trait values.'
 return.
end.
if. ((#State)<:>./x) do.
 'Supply only turtle values between 0 and ',(":<:#State),' .'
 return.
end.
  if. x nneQ ~: x
  do.
    'Values of x must be unique'
    return.
  end.
 if. x neqQ y
 do.
   tmp =. /: x
   x =. tmp{x
   y =. tmp{y
   y =. y (~.x)}state trait
   ". status1, lr y
   return.
 end.
if. 1=#y
 do.
   y =. ((#~.x) copies ,y) (~.x)}state trait
   ". status1, lr y
   return.
 end.
 'Your inputs are not understood.'
)

goto0 =: monad define
geth =. YwRow&{"2             NB. get H row
getp =. PtRow&{"2             NB. get U row
NB. get State info
'position heading stepsize' =. state each ;: 'Position Heading Stepsize'

NB. put desired turtle position & heading temps
P =. y
H =. heading
heading =. mfv heading
distance =. length P-"1 position

NB. in 5 steps execute "goto"
NB. 1: +yw toward the desired point
NB. 2: +pt toward the desired point
NB. 3:  fd toward the desired point
NB. 4: -pt to reverse step 2
NB. 5: -yw to reverse step 1

NB. step 1
tpos =. P-"1 position

NB. reverse compensates for yw being clockwise
turn1 =.  tpos (([: ang@:|. "1 nrmlz@:ywProj )) heading
sm 'yw ',":[tmp =. dfr turn1
sm yw tmp


NB. step 2

heading =. state 'Heading'
tpos =. P-"1 position

turn2 =.  tpos (([: ang "1 nrmlz@:ptProj )) mfv state 'Heading'
sm 'pt ',":[tmp =. dfr turn2
sm pt tmp

NB. step 3
sm 'fd ',":[tmp =. distance%,stepsize
sm fd tmp

NB. step 4
sm 'pt ',":[tmp =. dfr -turn2
sm pt tmp

NB. step 5
sm 'yw ',":[tmp =. dfr -turn1
sm yw tmp
)

NB.* goto v [indices of turtles] goto Position(s) to goto
NB.  goto moves the turtle(s)' Position(s)
NB.      to place(s) specified in y .
NB. left argument can be a list of turtle indices
NB.   (where turtle indices begin with 0).
NB.   If the left argument is omitted, Eye turtle(s) are
NB.   elided from the list of all turtles moved.
NB. Turtle indices are 0 1 2 ...
goto =: [ ('Position' status 'goto0') mat@]

turnto0 =: monad define
geth =. YwRow&{"2             NB. get H row
getp =. PtRow&{"2             NB. get U row
NB. get State info
NB. 'position heading stepsize' =. state each ;: 'Position Heading Stepsize'
'position heading' =. state each ;: 'Position Heading'

NB. put initial turtle position & heading temps
P =. y
heading =. mfv heading
distance =. length P-"1 position


NB. in 3 steps execute "gazeat"
NB. 1: +yw toward position
NB. 2: +pt toward position
NB. 3: -yw back

tpos =. P-"1 position

NB. step 1

heading =. mfv state 'Heading'

NB. reverse compensates for yw being clockwise
turn1 =. tpos (([: ang@:|. "1 nrmlz@:ywProj )) heading
sm 'yw ',":[FaceTurn =: tmp =. dfr turn1
sm yw tmp

NB. step 2
heading =. mfv state 'Heading'

turn2 =.  tpos (([: ang"1 nrmlz@:ptProj )) heading
sm 'pt ',":[tmp =. dfr turn2
sm pt tmp

NB. step 3
NB. sm 'yw ',":[tmp =. dfr -turn1
NB. sm yw tmp
)
turnto =: [ ('Position' status 'turnto0') mat@]

NB. gazeat1 is the old gazeat0, which was reworked
NB. separating out the turnto0 section which works
NB. by itself when turning nonEye turtles
NB. 4/21/5
gazeat1 =: monad define
geth =. YwRow&{"2             NB. get H row
getp =. PtRow&{"2             NB. get U row
NB. get State info
'position heading stepsize' =. state each ;: 'Position Heading Stepsize'

NB. put initial turtle position & heading temps
P =. y
heading =. mfv heading
distance =. length P-"1 position


NB. in 3 steps execute "gazeat"
NB. 1: +yw toward position
NB. 2: +pt toward position
NB. 3: -yw back

tpos =. P-"1 position

NB. step 1

heading =. mfv state 'Heading'

NB. reverse compensates for yw being clockwise
turn1 =. tpos (([: ang@:|. "1 nrmlz@:ywProj )) heading
sm 'yw ',":[tmp =. dfr turn1
sm yw tmp

NB. step 2
heading =. mfv state 'Heading'

turn2 =.  tpos (([: ang"1 nrmlz@:ptProj )) heading
sm 'pt ',":[tmp =. dfr turn2
sm pt tmp

NB. step 3
NB. sm 'yw ',":[tmp =. dfr -turn1
NB. sm yw tmp

cs''

VN =: (Eye{y) perspective"1 (stateEye 'Position')
lines =. ,"2]2 4|:,"4 see"2 ]_3,:\"1 ]6{."1 DrawPathList
traits =.  _5{."1 DrawPathList
if. StereoFlag
do.
tmp =. ;,.&.>/stateEye each ;:'Pencolor Pensize Penstyle'
lines pathclusterdraw tmp copies~#traits
else.
lines pathclusterdraw traits
end.
lines =. ,"2]2 4|:,"4 see"2 ]_3,:\"1 ]24{."1 DrawTList
traits =.  _5{."1 DrawTList
tclusterdraw ,/,/lines ,"1 traits
return.
)

gazeat0 =: monad define
turnto0 y
cs''

VN =: (Eye{y) perspective"1 (stateEye 'Position')
lines =. ,"2]2 4|:,"4 see"2 ]_3,:\"1 ]6{."1 DrawPathList
traits =.  _5{."1 DrawPathList
if. StereoFlag
do.
tmp =. ;,.&.>/stateEye each ;:'Pencolor Pensize Penstyle'
lines pathclusterdraw tmp copies~#traits
else.
lines pathclusterdraw traits
end.
lines =. ,"2]2 4|:,"4 see"2 ]_3,:\"1 ]24{."1 DrawTList
traits =.  _5{."1 DrawTList
tclusterdraw ,/,/lines ,"1 traits
return.
)

gazeat =: [ ('Position' status 'gazeat0') mat@]

NB.* eyeto v moves any Eye(s) to y Position
NB.  usage: [gaze_Position] goto new_position
eyeto =: verb define
  Eye goto y
  Eye gazeat EyeGazesAt
  :
  Eye goto y
  Eye gazeat EyeGazesAt =: x
)

NB.* home v returns the turtle(s)' Position(s)
NB.         to its/their starting value
NB.         updating StateChange, also.
NB.         Other States remain unchanged.
NB. argument can be '' or a list of turtle numbers
NB.   where turtle numbers begin with 0
NB.   If the argument is '' Eye turtle(s) are elided
NB.   from the list of all turtles moved home.
home =:  monad define NB. home the Turtle State
smoutput 'Only the repositioning works, not reorienting.'
smoutput 'For clearer error messages, use goto directly.'
  numS =. i.#State
  turtles =. Eye -.~ numS
  if. ''-:y
  do. turtles goto turtles{P0
  else.  y goto mat y{P0
  end.
)

NB.* penup v make turtle path for turtles listed by number
NB. usage: penup '' or penup 0 1 2 3 for all four turtles
pu =: penup =: monad define
if. y-:'' do.
  y =. i. #State
  end.
  y =. ,~. y
if. ((#State)<:>./y) do.
 'Supply only turtle values between 0 and ',(":<:#State),' .'
 return.
end.

NB. update SC and State
oldpenstate =. state 'Penstate'
penstate =. 0 y} oldpenstate
D =. penstate - oldpenstate
C =. SCN aindex 'Penstate'
SC =: C aC D
penstate state 'Penstate'

NB. update user's info
Penstate =: ,state 'Penstate'
'Penstate';,Penstate

)

NB.* pendown v make turtle path for turtles listed by number
NB. usage: pendown '' or pendown 0 1 2 3 for all four turtles
pd =: pendown =: monad define
if. y-:'' do.
  y =. i. #State
  end.
  y =. ,~. y
if. ((#State)<:>./y) do.
 'Supply only turtle values between 0 and ',(":<:#State),' .'
 return.
end.

NB. update SC and State
oldpenstate =. state 'Penstate'
penstate =. 1 y} oldpenstate
D =. penstate - oldpenstate
C =. SCN aindex 'Penstate'
SC =: C aC D
penstate state 'Penstate'

NB. update user's info
Penstate =: ,state 'Penstate'
'Penstate';Penstate
)

pc =: pencolor =: verb define
NB.* pencolor v [indices of turtles] pencolor colors to assign
NB. See the list of colors by typing COLORTABLE.
NB. Turtle indices are 0 1 2 ...
y pencolor~i.#State
:
 if. (1=#y) *. -. StereoFlag do.
   y =. (,Bkgrd) Eye}yxs&State y
 end.
x =. ,x
if. (y nneQ x) *. 1~:#y do.
 'The number of colors must be 1 or the same as the number of turtles listed.'
 return.
end.
if. (1<#y) *.x nneQ y do.
 'Supply 1 or ',(":#x),' pencolor values.' return.
end.

NB. update SC and State
oldpencolor =. state 'Pencolor'
newpencolor =. (((#x),3)$,y) x} oldpencolor
D =. newpencolor - oldpencolor
C =. SCN aindex 'Pencolor'
SC =: C aC1 D
newpencolor state 'Pencolor'

NB. update user's info
Pencolor =: state 'Pencolor'
'Pencolor';Pencolor
)

NB. enable one-liner turtle movement sequences
repeats =: conjunction define
 for. i. m
  do. v y
 end.
:
 for. i. m
  do. x v y
 end.
)

NB. a handy verb that combines J and turtle commands
ywfd =: yawforward =: dyad define
yw x
fd y
)

NB. iTS uses radius of 300 here
NB. cs''[iTS 2[cs''
NB. ''[(0,0,:0) state 'Turtlestate'
NB. ''[8 (12 repeats poly3)30
NB. eyeto 10*-:+/ }:Position
NB. ''[5 (11 repeats poly3)30

NB. iTS uses radius of 200 here
NB. ''[iTS 2[cs''
NB. ''[(0,0,:0) state 'Turtlestate'
NB. 2 (60 repeats poly3)10[yw _55[pd ''[rl 110[jr 0[pu ''
NB. 100 0 0 eyeto ,: 100 0 1000

NB. a handy verb that combines J and turtle commands
poly3 =: fruyrp =: dyad define
if. -. StereoFlag do. pencolor Red    end.
fd x
rl y
if. -. StereoFlag do. pencolor Blue end.
ju x
yw y
if. -. StereoFlag do. pencolor Black end.
jr x
pt -y
Head =: Head,{.state 'Heading'
)

NB. a handy verb that combines J and turtle commands
fdyw =: forwardyaw =: dyad define
fd x
yw y
)

NB.* show v show values of the turtle parameters
NB. argument can be '' or a list of turtle numbers
NB.   where turtle numbers begin with 0
NB. also note that output of "heading" is in radians
show =: showTurtleState =: monad define
if. y-:'' do.
  y =. i. #State
  end.
  y =. ,~. y
if. ((#State)<:>./y) do.
 'Supply only turtle values between 0 and ',(":<:#State),' .'
 return.
end.
NB. prints heading in radians, not degrees -- all in columns
NB. BasicTnames,. y &{ each state each BasicTnames

NB. prints some facts in rows and some in columns
NB. because global singleton values are saved indiviually as rows
BasicTnames,. y &{ each do each BasicTnames
)

NB. The next two verbs are rather complex and should be used
NB.    with care by experienced users.
NB.* pendownchange v make turtle path show or change status of penstate
NB. usage: pendownchange 1 or pendownchange 0 1 _1 1 for four turtles
NB. arg values of  1 mean put the penstates to pendown
NB. arg values of _1 mean to reverse the current penstates
NB. arg values of 0 mean NOT to change the penstates
pendownchange =: monad define
if. (1<#,y) *. 0=+/,|y do.
  'Use penupchage to set penstates to penup.'
  return. end.
if. (-. mtQ,y) *. -. _1 0 1 &okvaluesQ ,y do.
  'Supply only _1s, zeros and ones.'
  return.
end.
if. (1<#,y) *.State nneQ ,y do.
 'Supply 1 or ',(":#State),' pendownchange (_1, 0, or 1) values.'
 return.
end.
oldpenstate =. state 'Penstate'
if. (y-:'') +. (y-:1) do.
  y =.  yxs&State 1
 else.
   y =. ,y
end.
penstate =. oldpenstate changetodown y
D =. |penstate - oldpenstate
C =. SCN aindex 'Penstate'
SC =: C aC D
N =. SN aindex 'Penstate'
State =: N aS penstate
Penstate =: ,state 'Penstate'
'Penstate';Penstate
)

NB.* penupchange v hide turtle path or change status of penstate
NB. usage: penupchange 1 or penupchange 0 1 _1 1 for four turtles
NB. arg values of 1 mean put the penstates to penup
NB. arg values of _1 mean to reverse the current penstates
NB. arg values of 0 mean NOT to change the penstates
penupchange =: monad define
if. (1<#,y) *. 0=+/,|y
do. 'Use pendownchange to set penstates to pendown.'
  return.
end.
if. (-. mtQ,y) *. -. _1 0 1 &okvaluesQ ,y
do. 'Supply only _1s, zeros and ones.'
  return.
end.
if. (1<#,y) *.State nneQ ,y do.
 'Supply 1 or ',(":#State),' penupchange (_1, 0 or 1) values.'
 return.
end.
oldpenstate =. state 'Penstate'
if. (y-:'') +. (y-:1) do.
  Penstate =:  yxs&State 0
 else. y =. ,y
end.
penstate =. oldpenstate changetoup y
D =. |penstate - oldpenstate
C =. SCN aindex 'Penstate'
SC =: C aC D
N =. SN aindex 'Penstate'
State =: N aS penstate
Penstate =: ,state 'Penstate'
'Penstate';Penstate
)

NB. main graphics initialization     ***************

SCREEN =: 0 : 0
pc Screen;
xywh 6 6 100 100;cc Left isigraph rightmove bottommove;
pas 6 6;pcenter;ptop;
rem form end;
)

Screen_run =: monad define
wd SCREEN
wd 'pshow;'
wd 'psel Screen'
)

Screen_close=: 3 : 0
wd'pclose'
)

NB. turtle state dbase verbs         ***************

yfx =: {."1~ #@]                 NB. (#y) taken from x
amemb =: ,:@] {."1@:E. yfx       NB. all members of y in x
aindex =: amemb # i.@#@[         NB. all indices of y in x
num =: [:{:2:{.!.1 $             NB. columns of matrix or 1 for vector
rnd =: <.@(0.5&+)                NB. can round off State/SC output


NB. for updating the turtle state array
aS =: alterState =: 4 : 'y  ({;&x i.@#State)}State'

NB.  State is queried or modified by state
NB.  Notice that in dyadic use, global State is modified*****
NB.* state v retrieve y in State : x amends y, and State is updated
NB.  usage: heading =. state 'Heading'
NB.         state each ;:'Heading Position'
NB.         ((,"_1 (ywRot rfd 90 0),ptRot rfd 90);0 0 0,250 _200 0,:0 0 200)state each ;:'Heading Position'
state =: verb define
State {"1~ SN aindex y
:
i =. SN aindex y
if. ($,.x) -: $State {"1~i do.
       State =: (,.x) ({;&i i.@#State)} State
       else.
       smoutput 'The shape of ',y,' in State is different from ',": x
       return.
end.
)

NB.  State is queried or modified by stateEye
NB.  Notice that in dyadic use, global State is modified*****
NB.* stateEye v retrieve y in State : x amends y, and State is updated
NB.  usage: heading =. stateEye 'Heading'
NB.         stateEye each ;:'Heading Position'
NB.         ((,"_1 ptRot rfd 90);,:0 0 200)stateEye each ;:'Heading Position'
stateEye =: (verb define)   NB. "_ 1 _
eye State {"1~ SN aindex y
:
i =. SN aindex y
if. x -:&$&mat eye State {"1~i
do.
  State =: (x) (mat{;&i Eye)} State
else.
smoutput 'The shape of ',y,' in State is different from ',": x
return.
end.
)


NB. below is for summarizing or modifiying SC (StateChange dbase)
NB. useful for averaging state-change dbase
avg =: +/ % +/@(~:&0)  NB. denominator counts ~:0

NB. for updating the turtle state-change history array
NB.   when the trait is a scalar
NB.  Notice that in dyadic use, global SC is modified*****
aC =: appendChange =: dyad define
filler =. 0$~(#y),#SCN
SC,"_1 y x }"0 1 filler
)

NB. for updating the turtle state-change history array
NB.   when the trait is a vector
NB.  Notice that in dyadic use, global SC is modified*****
aC1 =: appendChange =: dyad define
filler =. 0$~(#y),#SCN
SC,"_1 y x }"1 filler
)

NB. main graphics update verbs       ***************

objectdraw =: dyad define
 turtlecolor =. y{~ SN aindex 'Turtlecolor'
 pensize =. y{~ SN aindex 'Pensize'
 penstyle =. y{~ SN aindex 'Penstyle'
 wd'psel Screen'
 glmap MM_DEFAULT
 glrgb Red
 glbrush''
 glrgb turtlecolor
 glpen pensize , penstyle
 gllines  "1 x
 NB. glshowx''
 )

erasedraw =: dyad define
 pensize =. y{~ SN aindex 'Pensize'
 penstyle =. y{~ SN aindex 'Penstyle'
 wd'psel Screen'
 glmap MM_DEFAULT
 glrgb Red
 glbrush''
 glrgb Bkgrd
 glpen pensize , penstyle
 gllines  "1  x
 NB. glshowx''
 )

linesdraw =: dyad define
 pencolor =. x{~ SN aindex 'Pencolor'
 pensize =. x{~ SN aindex 'Pensize'
 penstyle =. x{~ SN aindex 'Penstyle'
 wd'psel Screen'
 glmap MM_DEFAULT
 glrgb Red
 glbrush''
 glrgb pencolor
 glpen pensize, penstyle
 gllines y
 NB. glshowx''
 )

tclusterdraw =: monad define
  clusters =. ~. keys =. 16}."1 y
  lines =. keys </. 16{."1 y
  clusters tdraw"1 0 lines
  glshow ''
)

tdraw =: dyad define
  parts =. #&> (<SN) aindex each ;:'Turtlecolor Pensize Penstyle'
 'turtlecolor pensize penstyle' =. x <;.1~pvfc parts
 wd'psel Screen'
 glmap MM_DEFAULT
 glrgb Red
 glbrush''
 glrgb turtlecolor
 glpen pensize , penstyle
 gllines  "1 >y
 NB. glshowx''
 )

pathclusterdraw =: dyad define
  if. StereoFlag NB. *. 3<#State
  do.
      combined =. ,/,/x,"1"2 y
    else.
        combined =. ,/,/x,"1 y
  end.
  draw =. (4&}."1) (pathdraw"1) 4&{."1
    if. ClusterFlag do.
        draw =. ([: ~. 4&}."1) (pathdraw"1 0) 4&}."1 </. 4&{."1
    end.
  draw combined
  NB. glshow ''
)

pathdraw =: dyad define
  parts =. #&> (<SN) aindex each ;:'Pencolor Pensize Penstyle'
 'pencolor pensize penstyle' =. x <;.1~pvfc parts
 wd'psel Screen'
 glmap MM_DEFAULT
 glrgb Red
 glbrush''
 glrgb pencolor
 glpen pensize, penstyle
 gllines"1 >y
 NB. glshowx''
 )

cs =: clearscreen =: monad define
wd'psel Screen'
glclear ''
glmap MM_DEFAULT
glshow''
NB. DrawTList =: i. (#Eye),0 ,(3&* #{.TNorth)++/#&> (<SN) aindex each ;:'Turtlecolor Pensize Penstyle'
NB. DrawPathList =: i. 0 ,6++/#&> (<SN) aindex each ;:'Pencolor Pensize Penstyle'
)

NB. setting turtle parameter values  ***************

BasicTnames =: <;._2 noun define
Position
Heading
Pencolor
Pensize
Penstyle
Turtlecolor
Turtlesize
Turtleploughshape
Penstate
Turtlestate
Turtleerase
Stepsize
)

EyesTs =: noun define


NB. Stereo eyes must have a parity for left vs right eye
NB. The sequence here must correspond with that assigned
NB.      in Position, P0, Heading, and H0
NB.      here in this noun and in its
NB.      parallel noun for defining State.
NB. Also note that turtle 0 can never be a left eye
NB.      (_0 is meaningless).
Eye =: 2 3           NB. add one turtle for the eye
eye =: Eye&{           NB. must always be changed after Eye

P0 =: Position =: 4 3$0 0 0 250 _200 0 _10 0 1000 10 0 1000
P0 =: Position =: 4 3$0 0 0 250 _200 0 _5 0 1000 5 0 1000
tmp =. Eye angFdist"1 eye P0
H0 =: Heading =: 4 3$0 0 0 0 90 0 0 0 _90 0 0 _90
H0 =: Heading =: 4 3$0 0 0 0 90 0 0.572939 0 _90 _0.572939 0 _90
H0 =: Heading =: 4 3$0 0 0 0 90 0 ,,tmp,._90
Pe0 =: eye P0
He0 =: eye H0
Pencolor  =: Black,Blue,Red,Blue
Pensize =: 2 2 2 2
Penstyle =: 0 0 0 0
Turtlecolor =: Red,Blue,Red,Blue
Turtlesize =: 12 51 12,9 30 12,9 30 12,:9 30 12 NB. (halfwidth,height,depth)
Turtleploughshape =: 1 1 1 1
Penstate =: 1 1 0 0
Turtlestate =: 1 1 0 0
Turtleerase =: 1 1 1 1
Stepsize =: 5 5 5 5
)

SampleTs =: noun define
P0 =: Position =: 3 3$0 0 0 250 _200 0 0 0 1000
H0 =: Heading =: 3 3$0 0 0 0 90 0 0 0 _90
Eye =: 2               NB. add one turtle for the eye
eye =: Eye&{           NB. must always be changed after Eye
Pe0 =: eye P0
He0 =: eye H0
Pencolor  =: Black,Blue,Bkgrd
Pensize =: 2 2 2
Penstyle =: 0 0 0
Turtlecolor =: Red,Blue,Bkgrd
Turtlesize =: 12 51 12,9 30 12,:9 30 12 NB. (halfwidth,height,depth)
Turtleploughshape =: 1 1 1
Penstate =: 1 1 0
Turtlestate =: 1 1 0
Turtleerase =: 1 1 1
Stepsize =: 5 5 5
)

EyesTvalues =: <@". ;._2 noun define
4 3$0 0 0 250 _200 0 _10 0 1000 10 0 1000
,"_1 allRot 4 3$0 0 0 0,(pi%2), 0 0.00499996 0 ,(-pi%2), _0.00499996 0 ,-pi%2
Black,Blue,Red,Blue
2 2 2 2
0 0 0 0
Red,Blue,Red,Blue
12 51 12,9 30 12,9 30 12,:9 30 12
1 1 1 1
1 1 0 0
1 1 0 0
1 1 1 1
5 5 5 5
)

SampleTvalues =: <@". ;._2 noun define
3 3$0 0 0 250 _200 0 0 0 1000
,"_1 allRot 3 3$0 0 0 0,(pi%2), 0 0 0 ,-pi%2
Black,Blue,Bkgrd
2 2 2
0 0 0
Red,Blue,Bkgrd
12 51 12,9 30 12,:9 30 12
1 1 1
1 1 0
1 1 0
1 1 1
5 5 5
)

SN =: StateNames =: ];._2 ] 0 : 0
PositionX
PositionY
PositionZ
HeadingRX
HeadingRY
HeadingRZ
HeadingHX
HeadingHY
HeadingHZ
HeadingUX
HeadingUY
HeadingUZ
PencolorR
PencolorG
PencolorB
Penstate
Pensize
Penstyle
Turtlestate
Turtleerase
TurtlecolorR
TurtlecolorG
TurtlecolorB
TurtlesizeW
TurtlesizeH
TurtlesizeZ
Turtleploughshape
Stepsize
)

SCN =: StateChangeNames =: ];._2 ] 0 : 0
HeadingRD
HeadingHD
HeadingUD
DistanceRD
DistanceHD
DistanceUD
PencolorRD
PencolorGD
PencolorBD
PenstateD
PensizeD
PenstyleD
TurtlestateD
TurtleeraseD
TurtlecolorRD
TurtlecolorGD
TurtlecolorBD
TurtlesizeWD
TurtlesizeHD
TurtlesizeZD
TurtleploughshapeD
Stepsize
)

BasicTvalues =: <@". ;._2 noun define
1 3$0
,:1 0 0 0 1 0 0 0 1
Black
2
0
Blue
,:9 30 12
1
1
1
1
5
)

NB. turtle initialization verbs      ***************

NB.* tP v ambivalent produces initial Turtle positions on unit circle
NB. usage: [radius] tP no_of_turtles
NB. positive y produces equi-distant turtles
NB. negative y produces turtles of random distance
NB. programmed by Paul Chapman
regular =. i. % ]
irregular =. (? % ])&1000000@|
list =. irregular`regular@.(= |)@]
thetas =. 2p1"_ * list
r =. * (| > 1:)
tP =: turtlePosition =: (1: $: ]) : (r +.@r. thetas) f.

NB. usage: triangle"1 Turtlesize
NB. turtles start heading up, but math "0" faces right
oft =: originforturtles =: 0:,1&{,0:
mults =: 0 1 2 0 3 2 1 3{4 3$1 _1 0 0 0 0 0 _1 1 _1 _1 0
triangle =: oft+"1 *"1/&mults

tgsj3_run =: 3 : 0
NB. if. -. ('jjava'-:wd 'qwd')*.(502 <: ".1 2 3&{  9!:14 '') do.
if. -. (IFJAVA)*.(502 <: ".1 2 3&{  9!:14 '') do.
 'You must be using a Java enabled J version 5.02a or later.'
 return.
end.
smoutput 'Look for examples near the beginning of the script.'

NB. creates user's info for sample data
''[".;._2 SampleTs NB. Gives two turtle samples

NumTs =. #P0

NB. initialize shell State database
State0 =: State =: 0$~NumTs,#StateNames
SampleTvalues state each BasicTnames
EyeGazesAt =: ,:0 0 0

VN =: 0 0 0 perspective"1 stateEye 'Position'
StereoFlag =: 0

NB. initialize special user info
heading =. ,"_1 allRot rfd Heading
heading state 'Heading'
State0 =: State

NB. initialize shell SC database
NB. SC0 =: SC =: StateChange =: 0$~ NumTs,0,#StateChangeNames
SC0 =: SC =: StateChange =: $. 0$~ NumTs,0,#StateChangeNames

NB. initialize shell turtle
TNorth =: triangle"1 Turtlesize

NB. initialize shell drawing database
DrawTList =: i. (#Eye),0 ,(3&* #{.TNorth)+# SN aindex 'Turtlecolor Pensize Penstyle'
DrawTList =: i. (#Eye),0 ,(3&* #{.TNorth)++/#&> (<SN) aindex each ;:'Turtlecolor Pensize Penstyle'
DrawPathList =: i. (#Eye),0 ,6++/#&> (<SN) aindex each ;:'Pencolor Pensize Penstyle'

if. y do.  Screen_run '' end.

Head =: ,: {.state 'Heading'  NB. needed for poly3 initialization
yw 0
smoutput 'type "help" for a very little'
)

stereo_run =: 3 : 0
NB. creates user's info for Eyes data
''[".;._2 EyesTs NB. Gives two turtle samples

NumTs =. #P0

NB. initialize shell State database
State0 =: State =: 0$~NumTs,#StateNames
EyesTvalues state each BasicTnames
EyeGazesAt =: 0 0 0,:0 0 0

VN =: EyeGazesAt perspective"1 stateEye 'Position'
StereoFlag =: 1

NB. initialize special user info
heading =. ,"_1 allRot rfd Heading
heading state 'Heading'
State0 =: State

NB. initialize shell SC database
NB. SC0 =: SC =: StateChange =: 0$~ NumTs,0,#StateChangeNames
SC0 =: SC =: StateChange =: $. 0$~ NumTs,0,#StateChangeNames

NB. initialize shell turtle
TNorth =: triangle"1 Turtlesize

NB. initialize shell drawing database
DrawTList =: i. (#Eye),0 ,(3&* #{.TNorth)++/#&> (<SN) aindex each ;:'Turtlecolor Pensize Penstyle'
DrawPathList =: i. (#Eye),0 ,6++/#&> (<SN) aindex each ;:'Pencolor Pensize Penstyle'

yw 0
)

NB.* initTurtleState v (ambivalent)
NB. usage: [rows of (x,y) headings] initTStateBasic (no. of Ts)
NB. eg. (2 3$ 0 90 0 0 45 0 ) iTS 2  NB. create 2 identical turtles
NB.           iTS  4                 NB. create 4 identical turtles
NB.           iTS _4                 NB. create 4 identical turtles
iTS =: initTurtleState =: verb define
y iTS~ 0 0 0 copies~|y
:
y =. | y
if. y~:#x  do.
 'The number of turtle headings must equal the number of turtles.'
 return.
end.
if. (~:<.)y do.
  'Number of Turtles must be integer.'
  return.
end.

NB. 3D eye information
Pe0 =: 0 0 1000
He0 =: 0 0 _90

Eye =: y              NB. add one turtle for the eye (left)
y =. >: Eye           NB. add one turtle for the eye (left)
eye =: Eye&{          NB. must always be changed after Eye

NB. initialize default State
State =:  0$~y,#StateNames
(y&# each BasicTvalues) state each BasicTnames
EyeGazesAt =: ,:0 0 0

NB. initialize user info
P0 =: Position =: (3&{."1 [ 200 tP y),Pe0
H0 =: Heading =: x,He0

NB. convert user info to dbase format
heading =. ,"_1 allRot rfd Heading
position =. Position

NB. revise default State
(position;heading) state each ;:'Position Heading'
(Blue;(,:0);(,:0);(,:0)) stateEye each ;:'Pencolor Penstate Turtlestate Turtleerase'
VN =: EyeGazesAt perspective"1 stateEye 'Position'
StereoFlag =: 0

NB. revise user info
(BasicTnames) =: state each BasicTnames
Position =: P0
Heading =: H0
Turtlesize =: Turtlesize

NB. keep copy of initial State
State0 =: State

NB. create State Change shell
SC0 =: SC =: StateChange =: 0$~ y,0,#StateChangeNames NB. unsparse
NB. SC0 =: SC =: StateChange =: $. 0$~  y,0,#StateChangeNames NB. sparse

NB. initialize turtle shape
TNorth =: triangle"1 Turtlesize

NB. initialize shell drawing database
DrawTList =: i. (#Eye),0 ,(3&* #{.TNorth)+# SN aindex 'Turtlecolor Pensize Penstyle'
DrawTList =: i. (#Eye),0 ,(3&* #{.TNorth)++/#&> (<SN) aindex each ;:'Turtlecolor Pensize Penstyle'
DrawPathList =: i. (#Eye), 0 ,6++/#&> (<SN) aindex each ;:'Pencolor Pensize Penstyle'

yw 0
StateNames;|:State0
)

NB.* initStereoTurtleState v (ambivalent)
NB. usage: [rows of (x,y) headings] initTStateBasic (no. of Ts)
NB. eg. (2 3$ 0 90 0 0 45 0 ) iSTS 2  NB. create 2 identical turtles
NB.           iSTS  4                 NB. create 4 identical turtles
NB.           iSTS _4                 NB. create 4 identical turtles
iSTS =: initStereoTurtleState =: verb define
y iSTS~ 0 0 0 copies~|y
:
y =. | y
if. y~:#x  do.
 'The number of turtle headings must equal the number of turtles.'
 return.
end.
if. (~:<.)y do.
  'Number of Turtles must be integer.'
  return.
end.

NB. 3D eye information
Eye =: y,>:y            NB. add two turtles for the eyes
eye =: Eye&{            NB. must always be changed after Eye
y =. 2+y
Pe0 =: _10 0 1000,:10 0 1000
StereoFlag =: 1

NB. Most of the next values are dummy values
NB.      until after the eyeto sets real values.
He0 =: ,:~0 0 _90

NB. initialize default State
State =:  0$~y,#StateNames
(y&# each BasicTvalues) state each BasicTnames
(,:~0) stateEye 'Turtlestate'
(BasicTnames) =: state each BasicTnames
Position =: (y{.Position),Pe0
Heading  =: (y{.x      ),He0
(Blue,Red) stateEye 'Pencolor'
(Blue,Red) stateEye 'Turtlecolor'
EyeGazesAt =: 0 0 0,:0 0 0

VN =: EyeGazesAt perspective"1 stateEye 'Position'

NB. create State Change shell
NB. SC0 =: SC =: StateChange =: 0$~ y,0,#StateChangeNames NB. unsparse
SC0 =: SC =: StateChange =: $. 0$~  y,0,#StateChangeNames NB. sparse

NB. temporarily create these Draw databases (recreated below)
DrawTList =: i. (#Eye),0 ,(3&* #{.TNorth)++/#&> (<SN) aindex each ;:'Turtlecolor Pensize Penstyle'
DrawPathList =: i. (#Eye),0 ,6++/#&> (<SN) aindex each ;:'Pencolor Pensize Penstyle'
EyeGazesAt =: 0 0 0,:0 0 0

NB. initialize turtle shape
TNorth =: triangle"1 Turtlesize

NB. initialize eyes
EyeGazesAt eyeto Pe0
Pe0 =: eye Position
He0 =: eye Heading

NB. initialize user info
P0 =: Position =: (3&{."1 [ 200 tP y),Pe0
H0 =: Heading =: x,He0

NumTs =. #P0

NB. convert user info to dbase format
heading =. ,"_1 allRot rfd Heading
position =. Position

NB. revise default State
(position;heading) state each ;:'Position Heading'
VN =: EyeGazesAt perspective"1 stateEye 'Position'

NB. revise user info
(BasicTnames) =: state each BasicTnames
Position =: P0
Heading =: H0
traits =. ;:'Pencolor Penstate Turtlestate Turtleerase'
((Red,Red );(0,:0);(0,:0);(0,:0)) stateEye each traits

NB. keep copy of initial State
State0 =: State

NB. create State Change shell
NB. SC0 =: SC =: StateChange =: 0$~ y,0,#StateChangeNames NB. unsparse
SC0 =: SC =: StateChange =: $. 0$~  y,0,#StateChangeNames NB. sparse

NB. initialize shell drawing database
DrawTList =: i. (#Eye),0 ,(3&* #{.TNorth)++/#&> (<SN) aindex each ;:'Turtlecolor Pensize Penstyle'
DrawPathList =: i. (#Eye),0 ,6++/#&> (<SN) aindex each ;:'Pencolor Pensize Penstyle'

cs''
yw 0
StateNames;|:State0
)

coclass 'base'
NB. To initialize tgsj3 WITHOUT a new viewing screen,
NB.     supply a zero argument: tgsj3_run 0 .
tgsj3_run ''