chiark / gitweb /
fix angle and "right" handling in cmd_rel; allow "=" as prefix for identity; make...
[trains.git] / layout / layout
1 #!/usr/bin/perl -w
2
3 use POSIX;
4 use strict;
5 no strict 'subs';
6
7 our $ptscale= 72/25.4 / 7.0;
8
9 our $psu_ulen= 4.5;
10 our $psu_edgelw= 0.5;
11 our $psu_ticklw= 0.1;
12 our $psu_ticksperu= 1;
13 our $psu_ticklen= 5.0;
14 our $psu_allwidth= 37.0/2;
15 our $psu_gauge= 9;
16 our $psu_sleeperlen= 17;
17 our $psu_sleeperlw= 15;
18 our $psu_raillw= 1.0;
19 our $psu_thinlw= 1.0;
20
21 our $lmu_marklw= 4;
22 our $lmu_marktpt= 11;
23 our $lmu_txtboxtxty= $lmu_marktpt * 0.300;
24 our $lmu_txtboxh= $lmu_marktpt * 1.100;
25 our $lmu_txtboxpadx= $lmu_marktpt * 0.335;
26 our $lmu_txtboxoff= $lmu_marklw / 2;
27 our $lmu_txtboxlw= 1;
28
29 our $pi= atan2(0,-1);
30
31 our $draw_t_def= '1';
32 #$draw_t_def= 'T';
33
34 # Data structures:
35 #  $ctx->{CmdLog}= undef                  } not in defobj
36 #  $ctx->{CmdLog}[]= [ command args ]     } in defobj
37 #  $ctx->{LocsMade}[]= $id
38 #  $ctx->{Loc}{$id}{X}
39 #  $ctx->{Loc}{$id}{Y}
40 #  $ctx->{Loc}{$id}{A}
41 #  $ctx->{Trans}{X}       # transformation.  is ev representing
42 #  $ctx->{Trans}{Y}       # new origin.  (is applied at _input_
43 #  $ctx->{Trans}{A}       # not at plot-time)
44 #  $ctx->{Trans}{R}       # but multiply all y coords by this!
45 #  $ctx->{Draw}{T}        # 1 or '' for drawing track
46 #  $ctx->{Draw}{L}        # L1 or 1 or '' for labelling or drawing locs
47 #
48 #  $objs{$id}{CmdLog}
49 #  $objs{$id}{Loc}
50
51 our $ctx;
52 our %objs;
53 our @al; # current cmd
54
55 our $o='';
56 our $ol='';
57
58 our $param; # for parametric_curve
59
60 our $debug=0;
61 #$debug=1;
62 open DEBUG, ($debug ? ">&2" : ">/dev/null") or die $!;
63
64 if ($debug) {
65     select(DEBUG); $|=1;
66     select(STDOUT); $|=1;
67 }
68
69 # ev_... functions
70 #
71 # Operate on Enhanced Vectors which are a location (coordinates) and a
72 # direction at that location.  Representation is a hash with members X
73 # Y and A (angle of the direction in radians, anticlockwise from
74 # East).  May be absolute, or interpreted as relative, according to
75 # context.
76 #
77 # Each function's first argument is a hashref whose X Y A members will
78 # be created or overwritten; this hashref will be returned (so you can
79 # use it `functionally' by passing {}).  The other arguments may be ev
80 # hashrefs, or other info.  The results are in general undefined if
81 # one of the arguments is the same hash as the result.
82
83 sub ev_byang ($$;$) {
84     # ev_byang(R, ANG,[LEN])
85     # result is evec of specified angle and length (default=1.0)
86     my ($res,$ang,$len)=@_;
87     $len=1.0 unless defined $len;
88     $res->{X}= $len * cos($ang);
89     $res->{Y}= $len * sin($ang);
90     $res->{A}= $ang;
91     $res;
92 }
93 sub ev_compose ($$$) {
94     # ev_compose(SUM_R, A,B);
95     # appends B to A, result is end of new B
96     # (B's X is forwards from end of A, Y is translating left from end of A)
97     # A may have a member R, which if provided then it should be 1.0 or -1.0,
98     # and B's Y and A will be multiplied by R first (ie, we can reflect);
99     my ($sum,$a,$b) = @_;
100     my ($r);
101     $r= defined $a->{R} ? $a->{R} : 1.0;
102     $sum->{X}= $a->{X} + $b->{X} * cos($a->{A}) - $r * $b->{Y} * sin($a->{A});
103     $sum->{Y}= $a->{Y} + $r * $b->{Y} * cos($a->{A}) + $b->{X} * sin($a->{A});
104     $sum->{A}= $a->{A} + $r * $b->{A};
105     $sum;
106 }
107 sub ev_decompose ($$$) {
108     # ev_decompose(B_R, A,SUM)
109     # computes B_R s.t. ev_compose({}, A, B_R) gives SUM
110     my ($b,$a,$sum)=@_;
111     my ($r,$brx,$bry);
112     $r= defined $a->{R} ? $a->{R} : 1.0;
113     $brx= $sum->{X} - $a->{X};
114     $bry= $r * ($sum->{Y} - $a->{Y});
115     $b->{X}= $brx * cos($a->{A}) + $bry * sin($a->{A});
116     $b->{Y}= $bry * cos($a->{A}) - $brx * sin($a->{A});
117     $b->{A}= $r * ($sum->{A} - $a->{A});
118     $b;
119 }
120 sub ev_lincomb ($$$$) {
121     # ev_linkcomb(RES,A,B,P)
122     # gives P*A + (1-P)*B
123     my ($r,$a,$b,$p) = @_;
124     my ($q) = 1.0-$p;
125     map { $r->{$_} = $q * $a->{$_} + $p * $b->{$_} } qw(X Y A);
126     $r;
127 }
128 sub ev_bearing ($$) {
129     # ev_bearing(A,B)
130     # returns bearing of B from A
131     # value returned is in [ A->{A}, A->{A} + 2*$pi >
132     # A->{A} and B->{A} are otherwise ignored
133     my ($a,$b)= @_;
134     my ($r);
135     $r= atan2($b->{Y} - $a->{Y},
136               $b->{X} - $a->{X});
137     $r -= 4.0 * $pi;
138     while ($r < $a->{A}) { $r += 2.0 * $pi; }
139     $r;
140 }                
141 sub v_dist ($$) {
142     # v_dist(A,B)
143     # returns distance from A to B
144     # A->{A} and B->{A} are ignored
145     my ($a,$b)= @_;
146     my ($xd,$yd);
147     $xd= $b->{X} - $a->{X};
148     $yd= $b->{Y} - $a->{Y};
149     return sqrt($xd*$xd + $yd*$yd);
150 }                
151
152 sub canf ($$) {
153     my ($converter,$defaulter)=@_;
154     my ($spec,$v);
155     return &$defaulter unless @al;
156     $spec= shift @al;
157     $v= &$converter($spec);
158     dv('canf ','$spec',$spec, '$v',$v);
159     return $v;
160 }
161 sub can ($) { my ($c)=@_; canf($c, sub { die "too few args"; }); }
162 sub cano ($$) { my ($c,$def)=@_; canf($c, sub { return $def }); }
163
164 sub signum ($) { return ($_[0] > 0) - ($_[0] < 0); }
165
166 our %units_len= qw(- mm  mm 1  cm 10  m 1000);
167 our %units_ang= qw(- d   r 1); $units_ang{'d'}= 2*$pi / 360;
168
169 sub cva_len ($) { my ($sp)=@_; cva_units($sp,\%units_len); }
170 sub cva_ang ($) { my ($sp)=@_; cva_units($sp,\%units_ang); }
171 sub cva_absang ($) { input_absang(cva_ang($_[0])) }
172 sub cva_units ($$) {
173     my ($sp,$ua)=@_;
174     my ($n,$u,$r);
175     $sp =~ m/^([-0-9eE.]*[0-9.])([A-Za-z]*)$/
176         or die "lexically invalid quantity";
177     ($n,$u)= ($1,$2);
178     $u=$ua->{'-'} unless length $u;
179     defined $ua->{$u} or die "unknown unit $u";
180     $r= $n * $ua->{$u};
181     print DEBUG "cva_units($sp,)=$r ($n $u $ua->{$u})\n";
182     return $r;
183 }
184 sub cva_idstr ($) {
185     my ($sp)=@_;
186     die "invalid id" unless $sp =~ m/^[a-z][_0-9A-Za-z]*$/;
187     return $&;
188 }
189 sub cva_idex ($) {
190     my ($sp,$id)=@_;
191     my ($r,$d,$k,$neg,$na);
192     $neg= $sp =~ s/^\-//;
193     $id= cva_idstr($sp);
194     die "unknown $id" unless defined $ctx->{Loc}{$id};
195     $r= $ctx->{Loc}{$id};
196     $d= "idex $id";
197     foreach $k (sort keys %$r) { $d .= " $k=$r->{$k}"; }
198     printf DEBUG "%s\n", $d;
199     if ($neg) {
200         $na= $r->{A} + $pi;
201         $na -= 2*$pi if $na >= 2*$pi;
202         $r= { X => $r->{X}, Y => $r->{Y}, A => $na };
203     }
204     return $r;
205 }
206 sub cva_idnew ($) {
207     my ($sp)=@_;
208     my ($id);
209     $id=cva_idstr($sp);
210     die "duplicate $id" if exists $ctx->{Loc}{$id};
211     exists $ctx->{Loc}{$id}{X};
212     push @{ $ctx->{LocsMade} }, $id;
213     return $ctx->{Loc}{$id};
214 }
215 sub cva_cmd ($) { return cva_idstr($_[0]); }
216 sub cva__enum ($$) {
217     my ($sp,$el)=@_;
218     return $sp if grep { $_ eq $sp } @$el;
219     die "invalid option (permitted: @$el)";
220 }
221 sub cvam_enum { my (@e) = @_; return sub { cva__enum($_[0],\@e); }; }
222
223 sub cmd_abs {
224     my ($i,$nl);
225     $nl= can(\&cva_idnew);
226     $i->{X}= can(\&cva_len);
227     $i->{Y}= can(\&cva_len);
228     $i->{A}= can(\&cva_ang);
229     ev_compose($nl, $ctx->{Trans}, $i);
230 }
231 sub cmd_rel {
232     my ($from,$to,$len,$right,$turn);
233     $from= can(\&cva_idex);
234     $to= can(\&cva_idnew);
235     $len= cano(\&cva_len,0);
236     $right= cano(\&cva_len,0) * $ctx->{Trans}{R};
237     $turn= cano(\&cva_ang, 0) * $ctx->{Trans}{R};
238     my ($u)= ev_compose({}, $from, { X => $len, Y => -$right, A => 0 });
239     ev_compose($to, $u, { X => 0, Y => 0, A => $turn });
240 }
241
242 sub dv__evreff ($) {
243     my ($pfx) = @_;
244     $pfx . ($pfx =~ m/\}$|\]$/ ? '' : '->');
245 }
246 sub dv__evr ($) {
247     my ($v) = @_;
248     return 'undef' if !defined $v;
249     return $v if $v !~ m/\W/ && $v =~ m/[A-Z]/ && $v =~ m/^[a-z_]/i;
250     return $v if $v =~ m/^[0-9.]+/;
251     $v =~ s/[\\\']/\\$&/g;
252     return "'$v'";
253 }
254 sub dv1 ($$$);
255 sub dv1_kind ($$$$$$$) {
256     my ($pfx,$expr,$ref,$ref_exp,$ixfmt,$ixesfn,$ixmapfn) = @_;
257     my ($ix,$any);
258     return 0 if $ref ne $ref_exp;
259     $any=0;
260     foreach $ix (&$ixesfn) {
261         $any=1;
262         my ($v)= &$ixmapfn($ix);
263 #print STDERR "dv1_kind($pfx,$expr,$ref,$ref_exp,$ixmapfn) ix=$ix v=$v\n";
264         dv1($pfx,$expr.sprintf($ixfmt,dv__evr($ix)),$v);
265     }
266     if (!$any) {
267         printf DEBUG "%s%s= $ixfmt\n", $pfx, $expr, ' ';
268     }
269     1;
270 }    
271 sub dv1 ($$$) {
272     return 0 unless $debug;
273     my ($pfx,$expr,$v) = @_;
274     my ($ref);
275     $ref= ref $v;
276 #print STDERR "dv1 >$pfx|$ref<\n";
277     if (!$ref) {
278         printf DEBUG "%s%s= %s\n", $pfx,$expr, dv__evr($v);
279         return;
280     } elsif ($ref eq 'SCALAR') {
281         dv1($pfx, ($expr =~ m/^\$/ ? "\$$expr" : '${'.$expr.'}'), $$v);
282         return;
283     }
284     $expr.='->' unless $expr =~ m/\]$|\}$/;
285     return if dv1_kind($pfx,$expr,$ref,'ARRAY','[%s]',
286                        sub { ($[ .. $#$v) },
287                        sub { $v->[$_[0]] });
288     return if dv1_kind($pfx,$expr,$ref,'HASH','{%s}',
289                        sub { sort keys %$v },
290                        sub { $v->{$_[0]} });
291     printf DEBUG "%s%s is %s\n", $pfx, $expr, $ref;
292 }
293     
294 sub dv {
295     my ($pfx,@l) = @_;
296     my ($expr,$v,$ref);
297     while (@l) {
298         ($expr,$v,@l)=@l;
299         dv1($pfx,$expr,$v);
300     }
301 }                   
302
303 sub o ($) { $o .= $_[0]; }
304 sub ol ($) { $ol .= $_[0]; }
305
306 our $o_path_verb;
307
308 sub o_path_begin () {
309     o("      newpath\n");
310     $o_path_verb= 'moveto';
311 }
312 sub o_path_point ($) {
313     my ($pt)=@_;
314     o("        $pt $o_path_verb\n");
315     $o_path_verb= 'lineto';
316 }
317 sub o_path_stroke ($) {
318     my ($width)=@_;
319     o("        $width setlinewidth stroke\n");
320 }    
321
322 sub o_line ($$$) {
323     my ($a,$b,$width)=@_;
324     o_path_begin();
325     o_path_point($a);
326     o_path_point($b);
327     o_path_stroke($width);
328 }
329
330 sub psu_coords ($$$) {
331     my ($ends,$inunit,$across)=@_;
332     # $ends->[0]{X} etc.; $inunit 0 to 1 (but go to 1.5);
333     # $across in mm, +ve to right.
334     my (%ea_zo, $zo, $prop);
335     $ea_zo{X}=$ea_zo{Y}=0;
336     foreach $zo (qw(0 1)) {
337         $prop= $zo ? $inunit : (1.0 - $inunit);
338         $ea_zo{X} += $prop * ($ends->[$zo]{X} - $across * sin($ends->[0]{A}));
339         $ea_zo{Y} += $prop * ($ends->[$zo]{Y} + $across * cos($ends->[0]{A}));
340     }
341 #    dv("psu_coords ", '$ends',$ends, '$inunit',$inunit, '$across',$across,
342 #       '\\%ea_zo', \%ea_zo);
343     return $ea_zo{X}." ".$ea_zo{Y};
344 }
345
346 sub parametric__o_pt ($) {
347     my ($pt)=@_;
348     o_path_point("$pt->{X} $pt->{Y}");
349 }
350
351 sub parametric_segment ($$$$) {
352     my ($p0,$p1,$lenperp,$calcfn) = @_;
353     # makes $p (global) go from $p0 to $p1  ($p1>$p0)
354     # $lenperp is the length of one unit p, ie the curve
355     # must have a uniform `density' in parameter space
356     # $calcfn is invoked with $p set and should return a loc
357     # (ie, ref to X =>, Y =>, A =>).
358     my ($pa,$pb,@ends,$side,$ppu,$e,$v,$tick,$thinline);
359     return unless $ctx->{Draw}{T} =~ m/./;
360     $ppu= $psu_ulen/$lenperp;
361     my ($railctr)=($psu_gauge + $psu_raillw)*0.5;
362     my ($tickend)=($psu_allwidth - $psu_ticklen);
363     my ($tickpitch)=($psu_ulen / $psu_ticksperu);
364     my ($sleeperctr)=($psu_ulen*0.5);
365     my ($sleeperend)=($psu_sleeperlen*0.5);
366 print DEBUG "ps $p0 $p1 $lenperp ($ppu)\n";
367     $thinline= $ctx->{Draw}{T} !~ m/1/;
368     if ($thinline) {
369         my ($pt);
370         o("    $psu_thinlw setlinewidth\n");
371         o_path_begin();
372         for ($param=$p0; $param<$p1; $param += $ppu) {
373             parametric__o_pt(&$calcfn);
374         }
375         $param=$p1;
376         parametric__o_pt(&$calcfn);
377         o("      stroke\n");
378         return;
379     }
380     for ($pa= $p0; $pa<$p1; $pa=$pb) {
381         $pb= $pa + $ppu;
382         $param= $pa; $ends[0]= @ends ? $ends[1] : &$calcfn;
383         $param= $pb; $ends[1]= &$calcfn;
384 #print DEBUG "pa $pa $ends[0]{X} $ends[0]{Y} $ends[0]{A}\n";
385 #print DEBUG "pb $pb $ends[1]{X} $ends[1]{Y} $ends[1]{A}\n";
386         $e= $pb<=$p1 ? 1.0 : ($p1-$pa)/$ppu;
387         o("    gsave\n");
388         o_path_begin();
389         o_path_point(psu_coords(\@ends,0,-$psu_allwidth));
390         o_path_point(psu_coords(\@ends,0,$psu_allwidth));
391         o_path_point(psu_coords(\@ends,$e,$psu_allwidth));
392         o_path_point(psu_coords(\@ends,$e,-$psu_allwidth));
393         o("        closepath clip\n");
394         foreach $side qw(-1 1) {
395             o_line(psu_coords(\@ends,0,$side*$psu_allwidth),
396                    psu_coords(\@ends,1.5,$side*$psu_allwidth),
397                    $psu_edgelw);
398             o_line(psu_coords(\@ends,0,$side*$railctr),
399                    psu_coords(\@ends,1.5,$side*$railctr),
400                    $psu_raillw);
401             for ($tick=0; $tick<1.5; $tick+=$tickpitch/$psu_ulen) {
402                 o_line(psu_coords(\@ends,$tick,$side*$psu_allwidth),
403                        psu_coords(\@ends,$tick,$side*$tickend),
404                        $psu_ticklw);
405             }
406         }
407         o_line(psu_coords(\@ends,$sleeperctr,-$sleeperend),
408                psu_coords(\@ends,$sleeperctr,+$sleeperend),
409                $psu_sleeperlw);
410         o("      grestore\n");
411     }
412 }
413
414 sub arc ($$$$$) {
415     my ($to, $ctr,$from, $radius,$delta) = @_;
416     # does parametric_segment to draw an arc centred on $ctr
417     # ($ctr->{A} ignored)
418     # from $from with radius $radius (this must be consistent!)
419     # and directionally-subtending an angle $delta.
420     # sets $to->... to be the other end, and returns $to
421     my ($beta);
422     $to->{A}= $beta= $from->{A} + $delta;
423     $to->{X}= $ctr->{X} - $radius * sin($beta);
424     $to->{Y}= $ctr->{Y} + $radius * cos($beta);
425     return if abs($delta*$radius) < 1E-9;
426     parametric_segment(0.0,1.0, abs($radius*$delta), sub {
427         my ($beta) = $from->{A} + $delta * $param;
428         return { X => $ctr->{X} - $radius * sin($beta),
429                  Y => $ctr->{Y} + $radius * cos($beta),
430                  A => $beta }
431     });
432 }
433
434 sub cmd_join {
435     my ($from,$to,$how,$minradius);
436     $from= can(\&cva_idex);
437     $to= can(\&cva_idex);
438     $minradius= can(\&cva_len);
439     my (@paths,@solkinds);
440     do {
441         my ($sigma,$distfact, $theta,$phi, $a,$b,$c,$d, $m,$r, $radius);
442         my ($cvec,$cfrom,$cto,$midpt, $delta1,$delta2, $path,$reverse);
443         $sigma= ev_bearing($from,$to);
444         $distfact= v_dist($from,$to);
445         $theta= 0.5 * $pi - ($from->{A} - $sigma);
446         $phi=   0.5 * $pi - ($to->{A} + $pi - $sigma);
447         $a= 2 * (1 + cos($theta - $phi));
448         $b= 2 * (cos($theta) - cos($phi));
449         $c= -1;
450         $d= sqrt($b*$b - 4*$a*$c);
451         foreach $m (qw(-1 1)) {
452             next if $a < 1e-6;
453             $r= -0.5 * (-$b + $m*$d) / $a;
454             $radius= -$r * $distfact;
455             next if abs($radius) < $minradius;
456             $cfrom=  ev_compose({}, $from, { X=>0, Y=>-$radius, A=>-0.5*$pi });
457             $cto=    ev_compose({}, $to,   { X=>0, Y=> $radius, A=> 0.5*$pi });
458             $midpt=  ev_lincomb({}, $cfrom, $cto, 0.5);
459             $reverse= signum($r);
460             if ($reverse<0) {
461                 $cfrom->{A} += $pi;
462                 $cto->{A} += $pi;
463             }
464             $delta1= ev_bearing($cfrom, $midpt) - $cfrom->{A};
465             $delta2= ev_bearing($cto,   $midpt) - $cto->{A};
466             if ($reverse<0) {
467                 $delta1 -= 2*$pi;
468                 $delta2 -= 2*$pi;
469             }
470             my ($fs);
471             $path= [{ T=>Arc, F=>$from, C=>$cfrom, R=> $radius, D=>$delta1 },
472                     { T=>Arc, F=>$to,   C=>$cto,   R=>-$radius, D=>$delta2 }];
473             push @paths, $path;
474             push @solkinds, 'twoarcs';
475         }
476     } while 0;
477     my ($path,$segment,$bestpath,$len,$scores,$bestscores,@bends,$sk);
478     my ($crit,$cs,$i,$cmp);
479     foreach $path (@paths) {
480         $sk= shift @solkinds;
481         o("%   possible path $sk $path\n");
482         $len= 0;
483         @bends= ();
484         foreach $segment (@$path) {
485             if ($segment->{T} eq Arc) {
486                 o("%     Arc C ".loc2dbg($segment->{C}).
487                   " R $segment->{R} D ".ang2deg($segment->{D})."\n");
488                 $len += abs($segment->{R} * $segment->{D});
489                 push @bends, signum($segment->{R} * $segment->{D}); # right +ve
490             } else {
491                 die "unknown segment $segment->{T}";
492             }
493         }
494         o("%    length $len\n");
495         $scores= [];
496         foreach $crit (@al, 'short') {
497             if ($crit eq 'long') { $cs= $len; }
498             elsif ($crit eq 'short') { $cs= -$len; }
499             elsif ($crit =~ m/^(begin|end|)(left|right)$/) {
500                 if ($1 eq 'begin') { $cs= $bends[0]; }
501                 elsif ($1 eq 'end') { $cs= $bends[$#bends]; }
502                 else { $cs=0; map { $cs += $_ } @bends; }
503                 $cs= -$cs if $2 eq 'left';
504             } elsif ($crit =~ m/^(\!?)(twoarcs|arcline|arcsline)$/) {
505                 $cs= ($2 eq $sk) != ($1 eq '!');
506             }
507             push @$scores, $cs;
508         }
509         o("%    scores @$scores\n");
510         if (defined $bestpath) {
511             for ($i=0,$cmp=0; !$cmp && $i<@$scores; $i++) {
512                 $cmp= $scores->[$i] <=> $bestscores->[$i];
513             }
514             next if $cmp < 0;
515         }
516         $bestpath= $path;
517         $bestscores= $scores;
518     }
519     die "no solution" unless defined $bestpath;
520     o("%   chose path $bestpath @al\n");
521     @al= ();
522     foreach $segment (@$bestpath) {
523         if ($segment->{T} eq 'Arc') {
524             arc({}, $segment->{C},$segment->{F},$segment->{R},$segment->{D});
525         } else {
526             die "unknown segment";
527         }
528     }
529 }
530
531 sub cmd_extend {
532     my ($from,$to,$radius,$len,$upto,$ctr,$beta,$ang,$how,$sign_r);
533     $from= can(\&cva_idex);
534     $to= can(\&cva_idnew);
535     printf DEBUG "from $from->{X} $from->{Y} $from->{A}\n";
536     $how= can(cvam_enum(qw(len upto ang uptoang parallel)));
537     if ($how eq 'len') { $len= can(\&cva_len); }
538     elsif ($how =~ m/ang$/) { $ang= can(\&cva_ang); }
539     elsif ($how eq 'parallel' || $how eq 'upto') { $upto= can(\&cva_idex); }
540     $radius= cano(\&cva_len, 'Inf'); # +ve is right hand bend
541     if ($radius eq 'Inf') {
542 #       print DEBUG "extend inf $len\n";
543         if ($how eq 'upto') {
544             $len= ($upto->{X} - $from->{X}) * cos($from->{A})
545                 + ($upto->{Y} - $from->{Y}) * sin($from->{A});
546         } elsif ($how eq 'len') {
547         } else {
548             die "len of straight spec by angle";
549         }
550         printf DEBUG "len $len\n";
551         $to->{X}= $from->{X} + $len * cos($from->{A});
552         $to->{Y}= $from->{Y} + $len * sin($from->{A});
553         $to->{A}= $from->{A};
554         parametric_segment(0.0, 1.0, abs($len), sub {
555             ev_lincomb({}, $from, $to, $param);
556         });
557     } else {
558         my ($sign_r, $sign_ang, $ctr, $beta_interval, $beta, $delta);
559         print DEBUG "radius >$radius<\n";
560         $radius *= $ctx->{Trans}{R};
561         $sign_r= signum($radius);
562         $sign_ang= 1;
563         $ctr->{X}= $from->{X} + $radius * sin($from->{A});
564         $ctr->{Y}= $from->{Y} - $radius * cos($from->{A});
565         if ($how eq 'upto') {
566             $beta= atan2(-$sign_r * ($upto->{X} - $ctr->{X}),
567                          $sign_r * ($upto->{Y} - $ctr->{Y}));
568             $beta_interval= 1.0;
569         } elsif ($how eq 'parallel') {
570             $beta= $upto->{A};
571             $beta_interval= 1.0;
572         } elsif ($how eq 'uptoang') {
573             $beta= input_absang($ang);
574             $beta_interval= 2.0;
575         } elsif ($how eq 'len') {
576             $sign_ang= signum($len);
577             $beta= $from->{A} - $sign_r * $len / abs($radius);
578             $beta_interval= 2.0;
579         } else {
580             $sign_ang= signum($ang);
581             $beta= $from->{A} - $sign_r * $ang;
582             $beta_interval= 2.0;
583         }
584     printf DEBUG "ctr->{Y}=$ctr->{Y} radius=$radius beta=$beta\n";
585         $beta += $sign_ang * $sign_r * 4.0 * $pi;
586         for (;;) {
587             $delta= $beta - $from->{A};
588             last if $sign_ang * $sign_r * $delta <= 0;
589             $beta -= $sign_ang * $sign_r * $beta_interval * $pi;
590         }       
591     printf DEBUG "ctr->{Y}=$ctr->{Y} radius=$radius beta=$beta\n";
592         arc($to, ,$ctr,$from, $radius,$delta);
593     }
594     printf DEBUG "to $to->{X} $to->{Y} $to->{A}\n";
595 }
596
597 sub loc2dbg ($) {
598     my ($loc) = @_;
599     return "$loc->{X} $loc->{Y} ".ang2deg($loc->{A});
600 }
601 sub ang2deg ($) {
602     return $_[0] * 180 / $pi;
603 }
604 sub input_absang ($) {
605     return $_[0] * $ctx->{Trans}{R} + $ctx->{Trans}{A};
606 }
607 sub input_abscoords ($$) {
608     my ($in,$out);
609     ($in->{X}, $in->{Y}) = @_;
610     $in->{A}= 0.0;
611     $out= ev_compose({}, $ctx->{Trans}, $in);
612     return ($out->{X}, $out->{Y});
613 }
614
615 sub newctx () {
616     $ctx= {
617         Trans => { X => 0.0, Y => 0.0, A => 0.0, R => 1.0 },
618         InRunObj => "",
619         Draw => { T => $draw_t_def, L => L1 }
620         };
621 }
622
623 our $defobj_save;
624
625 sub cmd_defobj {
626     my ($id);
627     $id= can(\&cva_idstr);
628     die "nested defobj" if $defobj_save;
629     die "repeated defobj" if exists $objs{$id};
630     $defobj_save= $ctx;
631     newctx();
632     $ctx->{CmdLog}= [ ];
633     $ctx->{InDefObj}= $id;
634     $ctx->{Draw}= { T => '', L => '' }
635 }
636
637 sub cmd_enddefobj {
638     my ($bit,$id);
639     $id= $ctx->{InDefObj};
640     die "unmatched enddefobj" unless defined $id;
641     foreach $bit (qw(CmdLog Loc)) {
642         $objs{$id}{$bit}= $ctx->{$bit};
643     }
644     $ctx= $defobj_save;
645     $defobj_save= undef;
646 }
647
648 sub cmd_obj { cmd__obj(1); }
649 sub cmd_objflip { cmd__obj(-1); }
650 sub cmd__obj ($) {
651     my ($flipsignum)=@_;
652     my ($obj_id, $ctx_save, $pfx, $actual, $formal_id, $formal, $formcv);
653     my ($c, $ctx_inobj, $obj, $id, $newid, $newpt);
654     $obj_id= can(\&cva_idstr);
655     $actual= can(\&cva_idex);
656     $formal_id= can(\&cva_idstr);
657     $obj= $objs{$obj_id};
658     dv("cmd__obj ",'$obj',$obj);
659     die "unknown obj $obj_id" unless $obj;
660     $formal= $obj->{Loc}{$formal_id};
661     die "unknown formal $formal_id" unless $formal;
662     $ctx_save= $ctx;
663     newctx();
664     $ctx->{Trans}{R}= $flipsignum;
665     $ctx->{Trans}{A}= $actual->{A} - $formal->{A}/$flipsignum;
666     $formcv= ev_compose({}, $ctx->{Trans},$formal);
667     $ctx->{Trans}{X}= $actual->{X} - $formcv->{X};
668     $ctx->{Trans}{Y}= $actual->{Y} - $formcv->{Y};
669     $ctx->{InRunObj}= $ctx_save->{InRunObj}."${obj_id}::";
670     $ctx->{Draw}{T}= $ctx_save->{Draw}{T};
671     $ctx->{Draw}{L}= $ctx_save->{Draw}{L};
672     $ctx->{Draw}{L} =~ s/L//;
673 dv("cmd__obj $obj_id ",'$ctx',$ctx);
674     {
675         local (@al);
676         foreach $c (@{ $obj->{CmdLog} }) {
677             @al= @$c;
678             next if $al[0] eq 'enddefobj';
679             cmd__one();
680         }
681     };
682     if (@al && $al[0] eq '=') {
683         $pfx= ''; shift @al;
684     } else {
685         $pfx= cano(\&cva_idstr,undef);
686     }
687     $ctx_inobj= $ctx;
688     $ctx= $ctx_save;
689     if (defined $pfx) {
690         foreach $id (keys %{ $ctx_inobj->{Loc} }) {
691             next if $id eq $formal_id;
692             $newid= $pfx.$id;
693             next if exists $ctx_save->{Loc}{$newid};
694             $newpt= cva_idnew($newid);
695             %$newpt= %{ $ctx_inobj->{Loc}{$id} };
696         }
697     }
698 }
699
700 sub cmd__do {
701     my ($cmd);
702 dv("cmd__do $ctx @al ",'$ctx',$ctx);
703     $cmd= can(\&cva_cmd);
704     my ($id,$loc,$io,$ad);
705     $io= defined $ctx->{InDefObj} ? "$ctx->{InDefObj}!" : $ctx->{InRunObj};
706     o("%L cmd   $io $cmd @al\n");
707     $ctx->{LocsMade}= [ ];
708     {
709         no strict 'refs';
710         &{ "cmd_$cmd" };
711     };
712     die "too many args" if @al;
713     foreach $id (@{ $ctx->{LocsMade} }) {
714         $loc= $ctx->{Loc}{$id};
715         $ad= ang2deg($loc->{A});
716         ol("%L point $io$id ".loc2dbg($loc)."\n");
717         if (length $ctx->{Draw}{L}) {
718             ol("    gsave\n".
719                "      $loc->{X} $loc->{Y} translate $ad rotate\n");
720             if ($ctx->{Draw}{L} =~ m/1/) {
721                 ol("      0 $psu_allwidth newpath moveto\n".
722                    "      0 -$psu_allwidth lineto\n".
723                    "      $lmu_marklw setlinewidth stroke\n");
724             }
725             if ($ctx->{Draw}{L} =~ m/L/) {
726                 ol("      /s ($id) def\n".
727                    "      lf setfont\n".
728                    "      /sx5  s stringwidth pop\n".
729                    "      0.5 mul $lmu_txtboxpadx add def\n".
730                    "      -90 rotate  0 $lmu_txtboxoff translate  newpath\n".
731                    "      sx5 neg  0             moveto\n".
732                    "      sx5 neg  $lmu_txtboxh  lineto\n".
733                    "      sx5      $lmu_txtboxh  lineto\n".
734                    "      sx5      0             lineto closepath\n".
735                    "      gsave  1 setgray fill  grestore\n".
736                    "      $lmu_txtboxlw setlinewidth stroke\n".
737                    "      sx5 neg $lmu_txtboxpadx add  $lmu_txtboxtxty\n".
738                    "      moveto s show\n");
739             }
740             ol("      grestore\n");
741         }
742     }
743 }
744
745 sub cmd__one {
746     cmd__do();
747 }
748
749 print
750     "%!\n".
751     "  /lf /Courier-New findfont $lmu_marktpt scalefont def\n".
752     "  $ptscale $ptscale scale\n"
753     or die $!;
754
755 newctx();
756     
757 while (<>) {
758     next if m/^\s*\#/;
759     chomp; s/^\s+//; s/\s+$//;
760     @al= split /\s+/, $_;
761     next unless @al;
762     print DEBUG "=== @al\n";
763     push @{ $ctx->{CmdLog} }, [ @al ] if exists $ctx->{CmdLog};
764     cmd__one();
765 }
766
767 print $o, $ol, "  showpage\n"
768     or die $!;