chiark / gitweb /
thinner registration marks
[trains.git] / layout / layout
1 #!/usr/bin/perl -w
2
3 use POSIX;
4 use strict;
5 no strict 'subs';
6
7 our $scale= 7.0;
8 our $page_x= 0;
9 our $page_y= 0;
10 our $quiet=0;
11 our $debug=0;
12 our $output_layer= '*';
13
14 our $ps_page_shift= 615;
15 our $ps_page_xmul= 765.354;
16 our $ps_page_ymul= 538.583;
17
18 our @eopts;
19
20 our $drawers= 'arsclmno';
21 our %chdraw_emap= qw(A ARSc
22                      R aRsc
23                      S aRSc
24                      C arsC
25                      c Arsc
26                      r arcs
27                      L LM
28                      l l
29                      M Mno
30                      N MNo
31                      O MNO
32                      m mnol);
33
34 while (@ARGV && $ARGV[0] =~ m/^\-/) {
35     last if $ARGV[0] eq '-';
36     $_= shift @ARGV;
37     last if $_ eq '--';
38     s/^\-//;
39     while (length) {
40         if (s/^D(\d+)//) { $debug= $1; }
41         elsif (s/^D//) { $debug++; }
42         elsif (s/^q//) { $quiet=1; }
43         elsif (s/^l(\d+|\*)//) { $output_layer=$1; }
44         elsif (s/^S([0-9.]+)$//) { $scale= $1 * 1.0; }
45         elsif (s/^P(\d+)x(\d+)$//) { $page_x= $1; $page_y= $2; }
46         elsif (s/^(e)
47                ((?:[a-z]|\*|\?|\[[a-z][-a-z]*\])*?)
48                (\~?) (\d*) (\=*|\-+|\++) (\d*|\*)
49                ([a-z]+)$//ix) {
50             my ($ee,$g,$n,$d,$c,$v,$cc) = ($1,$2,$3,$4,$5,$6,$7);
51             my ($eo, $invert, $lfn, $ccc, $sense,$limit);
52             $g =~ s/\?/\./g; $g =~ s/\*/\.\*/g;
53             die '-[eE]GND[=]* not allowed' if $v eq '*' && length $d;
54             $d= $output_layer if !length $d;
55             $d= 5 if $d eq '*';
56             $invert= length $n;
57             $c= '=' if !length $c;
58             if (length $v && $v ne '*') {
59                 die '-[eE]GN[D]CCV not allowed' if length $c > 1;
60                 $c= $c x $v;
61             }
62             if ($c =~ m/^[-+]/) {
63                 die '-[eE]GN+/-* not allowed' if $v eq '*';
64                 $sense= ($&.'1') + 0;
65                 $limit= ($sense * $d) + length($c) - 1;
66                 $lfn= sub {
67                     ($output_layer eq '*' ? $d
68                      : $_[0]) * $sense >= $limit
69                          xor $invert;
70                 };
71             } elsif ($v eq '*') {
72                 $lfn= sub { !$invert; };
73             } else {
74                 $limit= length($c) - 1;
75                 $lfn= sub {
76 #my ($lfn_result)=(
77                     ($output_layer eq '*' ? 1
78                      : abs($_[0] - $d) <= $limit)
79                         xor $invert
80 #)
81                             ;
82 #print STDERR "output layer $output_layer; asking re $_[0] rel $d lim $limit invert $invert result $lfn_result\n";
83 #$lfn_result;
84                 };
85             }
86             $ccc= '';
87             foreach $c (split //, $cc) {
88                 if ($ee eq 'e') {
89                     die "bad -e option $c" unless defined $chdraw_emap{$c};
90                     $ccc .=  $chdraw_emap{$c};
91                 } else {
92                     die "bad -E option $c" unless $c =~ m/[$drawers]/i;
93                     $ccc .= $c;
94                 }
95             }
96             $eo->{GlobRe}= $g;
97             $eo->{LayerCheck}= $lfn;
98             $eo->{DrawMods}= $ccc;
99 #print STDERR "created eo $eo re $eo->{GlobRe} n=$n d=$d v=$v c=$c limit=$limit cc=$cc\n";
100             push @eopts, $eo;
101         } elsif (m/^S/) {
102             die "-S option must come right at the start and have numeric arg";
103         } else {
104             die "unknown option -$_";
105         }
106     }
107 }
108
109 our $ptscale= 72/25.4 / $scale;
110
111 our $psu_ulen= 4.5;
112 our $psu_edgelw= 0.5;
113 our $psu_ticklw= 0.1;
114 our $psu_ticksperu= 1;
115 our $psu_ticklen= 5.0;
116 our $psu_gauge= 9;
117 our $psu_sleeperlen= 17;
118 our $psu_sleeperlw= 15;
119 our $psu_raillw= 1.0;
120 our $psu_thinlw= 1.0;
121
122 our $lmu_marklw= 4;
123 our $lmu_marktpt= 11;
124 our $lmu_txtboxtxty= $lmu_marktpt * 0.300;
125 our $lmu_txtboxh= $lmu_marktpt * 1.100;
126 our $lmu_txtboxpadx= $lmu_marktpt * 0.335;
127 our $lmu_txtboxoff= $lmu_marklw / 2;
128 our $lmu_txtboxlw= 1;
129
130 our $olu_left= 10 * $scale;
131 our $olu_right= 217 * $scale - $olu_left;
132 our $olu_bottom= 20 * $scale;
133 our $olu_top= 270 * $scale - $olu_bottom;
134 our $olu_gap_x= 30;
135 our $olu_gap_y= 60;
136 our $olu_textheight= 15;
137 our $olu_textallowperc= $lmu_marktpt * 5.0/11;
138
139 our $pi= atan2(0,-1);
140
141 sub allwidth2 ($) {
142     my ($radius)= @_;
143     return 27 unless defined $radius;
144     $radius= abs($radius);
145     return ($radius >= 450 ? 33 :
146             $radius >= 400 ? 35 :
147             37);
148 }
149 sub allwidth ($) { return allwidth2($_[0]) * 0.5; }
150
151 our $allwidthmax= allwidth(0);
152 our $allwidthmin= allwidth(undef);
153
154 # Data structures:
155 #  $ctx->{CmdLog}= undef                  } not in defobj
156 #  $ctx->{CmdLog}[]= [ command args ]     } in defobj
157 #  $ctx->{LocsMade}[]{Id}= $id
158 #  $ctx->{LocsMade}[]{Neg}= 1 or 0
159 #  $ctx->{Loc}{$id}{X}
160 #  $ctx->{Loc}{$id}{Y}
161 #  $ctx->{Loc}{$id}{A}
162 #  $ctx->{Loc}{$id}{LayerKind}
163 #  $ctx->{Trans}{X}       # transformation.  is ev representing
164 #  $ctx->{Trans}{Y}       # new origin.  (is applied at _input_
165 #  $ctx->{Trans}{A}       # not at plot-time)
166 #  $ctx->{Trans}{R}       # but multiply all y coords by this!
167 #  $ctx->{Draw}           # sequence of one or more chrs from uc $drawers
168 #                         #  possibly including X meaning never draw
169 #                         #  anything now (eg in defobj)
170 #  $ctx->{DrawMap}        # =$fn s.t.
171 #                         #  &$fn($drawchrs_spec_by_layer_cmdline)
172 #                         #   = $drawchrs_we_should_use_due_to_obj_etc
173 #  $ctx->{Layer}{Level}
174 #  $ctx->{Layer}{Kind}
175 #
176 #  $objs{$id}{CmdLog}
177 #  $objs{$id}{Loc}
178 #  $objs{$id}{Part}       # 1 iff object is a part
179 #
180 #  $eopts[]{GlobRe}       # regexp for K
181 #  $eopts[]{LayerCheck}   # =$fn where &$fn($l) is true iff layer matches
182 #  $eopts[]{DrawMods}     # modifier chars for drawing
183
184 our $ctx;
185 our %objs;
186 our @al; # current cmd
187
188 our $o='';
189 our $ol='';
190
191 our $param; # for parametric_curve
192
193 # ev_... functions
194 #
195 # Operate on Enhanced Vectors which are a location (coordinates) and a
196 # direction at that location.  Representation is a hash with members X
197 # Y and A (angle of the direction in radians, anticlockwise from
198 # East).  May be absolute, or interpreted as relative, according to
199 # context.
200 #
201 # Each function's first argument is a hashref whose X Y A members will
202 # be created or overwritten; this hashref will be returned (so you can
203 # use it `functionally' by passing {}).  The other arguments may be ev
204 # hashrefs, or other info.  The results are in general undefined if
205 # one of the arguments is the same hash as the result.
206
207 sub ev_byang ($$;$) {
208     # ev_byang(R, ANG,[LEN])
209     # result is evec LEN (default=1.0) from origin pointing in direction ANG
210     my ($res,$ang,$len)=@_;
211     $len=1.0 unless defined $len;
212     $res->{X}= $len * cos($ang);
213     $res->{Y}= $len * sin($ang);
214     $res->{A}= $ang;
215     $res;
216 }
217 sub ev_compose ($$$) {
218     # ev_compose(SUM_R, A,B);
219     # appends B to A, result is end of new B
220     # (B's X is forwards from end of A, Y is translating left from end of A)
221     # A may have a member R, which if provided then it should be 1.0 or -1.0,
222     # and B's Y and A will be multiplied by R first (ie, we can reflect);
223     my ($sum,$a,$b) = @_;
224     my ($r);
225     $r= defined $a->{R} ? $a->{R} : 1.0;
226     $sum->{X}= $a->{X} + $b->{X} * cos($a->{A}) - $r * $b->{Y} * sin($a->{A});
227     $sum->{Y}= $a->{Y} + $r * $b->{Y} * cos($a->{A}) + $b->{X} * sin($a->{A});
228     $sum->{A}= $a->{A} + $r * $b->{A};
229     $sum;
230 }
231 sub ev_decompose ($$$) {
232     # ev_decompose(B_R, A,SUM)
233     # computes B_R s.t. ev_compose({}, A, B_R) gives SUM
234     my ($b,$a,$sum)=@_;
235     my ($r,$brx,$bry);
236     $r= defined $a->{R} ? $a->{R} : 1.0;
237     $brx= $sum->{X} - $a->{X};
238     $bry= $r * ($sum->{Y} - $a->{Y});
239     $b->{X}= $brx * cos($a->{A}) + $bry * sin($a->{A});
240     $b->{Y}= $bry * cos($a->{A}) - $brx * sin($a->{A});
241     $b->{A}= $r * ($sum->{A} - $a->{A});
242     $b;
243 }
244 sub ev_lincomb ($$$$) {
245     # ev_linkcomb(RES,A,B,P)
246     # gives P*A + (1-P)*B
247     my ($r,$a,$b,$p) = @_;
248     my ($q) = 1.0-$p;
249     map { $r->{$_} = $q * $a->{$_} + $p * $b->{$_} } qw(X Y A);
250     $r;
251 }
252 sub a_normalise ($$) {
253     # a_normalise(A,Z)
254     # adds or subtracts 2*$pi to/from A until it is in [ Z , Z+2*$pi >
255     my ($a,$z)=@_;
256     my ($r);
257     $r= $z + fmod($a - $z, 2.0*$pi);
258     $r += 2*$pi if $r < $z;
259     return $r;
260 }
261 sub ev_bearing ($$) {
262     # ev_bearing(A,B)
263     # returns bearing of B from A
264     # value returned is in [ A->{A}, A->{A} + 2*$pi >
265     # A->{A} and B->{A} are otherwise ignored
266     my ($a,$b)= @_;
267     my ($r);
268     $r= atan2($b->{Y} - $a->{Y},
269               $b->{X} - $a->{X});
270     $r= a_normalise($r,$a->{A});
271     return $r;
272 }
273
274 sub v_rotateright ($) {
275     # v_rotateright(A)
276     # returns image of A rotated 90 deg clockwise
277     my ($a)= @_;
278     return { X => $a->{Y}, Y => -$a->{X} };
279 }
280 sub v_dotproduct ($$) {
281     # v_dotproduct(A,B)
282     my ($a,$b)= @_;
283     return $a->{X} * $b->{X} + $a->{Y} * $b->{Y};
284 }
285 sub v_scalarmult ($$) {
286     # v_scalarmult(S,V)
287     # multiplies V by scalar S and returns product
288     my ($s,$v)=@_;
289     return { X => $s * $v->{X}, Y => $s * $v->{Y} };
290 }
291 sub v_add ($;@) {
292     # v_add(A,B,...)
293     # vector sum of all inputs
294     my (@i) = @_;
295     my ($r,$i);
296     $r= { X => 0.0, Y => 0.0 };
297     foreach $i (@i) { $r->{X} += $i->{X}; $r->{Y} += $i->{Y}; }
298     return $r;
299 }    
300 sub v_subtract ($$) {
301     # v_subtract(A,B)
302     # returns vector from A to B, ie B - A
303     my ($a,$b)= @_;
304     return { X => $b->{X} - $a->{X},
305              Y => $b->{Y} - $a->{Y} };
306 }
307 sub v_len ($) {
308     # v_len(V)
309     # scalar length of V
310     my ($v)=@_;
311     my ($x,$y) = ($v->{X}, $v->{Y});
312     return sqrt($x*$x + $y*$y);
313 }
314 sub v_dist ($$) {
315     # v_dist(A,B)
316     # returns distance from A to B
317     return v_len(v_subtract($_[0],$_[1]));
318 }
319
320 sub upd_min ($$) {
321     my ($limr,$now)=@_;
322     $$limr= $now unless defined $$limr && $$limr <= $now;
323 }
324 sub upd_max ($$) {
325     my ($limr,$now)=@_;
326     $$limr= $now unless defined $$limr && $$limr >= $now;
327 }
328
329 sub canf ($$) {
330     my ($converter,$defaulter)=@_;
331     my ($spec,$v);
332     return &$defaulter unless @al;
333     $spec= shift @al;
334     $v= &$converter($spec);
335     dv('canf ','$spec',$spec, '$v',$v);
336     return $v;
337 }
338 sub can ($) { my ($c)=@_; canf($c, sub { die "too few args"; }); }
339 sub cano ($$) { my ($c,$def)=@_; canf($c, sub { return $def }); }
340
341 sub signum ($) { return ($_[0] > 0) - ($_[0] < 0); }
342
343 sub bbox ($) {
344     my ($objhash) = @_;
345     my ($min_x, $max_x, $min_y, $max_y);
346     my ($loc);
347     foreach $loc (values %$objhash) {
348         upd_min(\$min_x, $loc->{X} - abs($allwidthmax * sin($loc->{A})));
349         upd_max(\$max_x, $loc->{X} + abs($allwidthmax * sin($loc->{A})));
350         upd_min(\$min_y, $loc->{Y} - abs($allwidthmax * cos($loc->{A})));
351         upd_max(\$max_y, $loc->{Y} + abs($allwidthmax * cos($loc->{A})));
352     }
353     return ($min_x, $max_x, $min_y, $max_y);
354 }
355
356 our %units_len= qw(- mm  mm 1  cm 10  m 1000);
357 our %units_ang= qw(- d   r 1); $units_ang{'d'}= 2*$pi / 360;
358
359 sub cva_len ($) { my ($sp)=@_; cva_units($sp,\%units_len); }
360 sub cva_identity ($) { my ($sp)=@_; $sp; }
361 sub cva_ang ($) { my ($sp)=@_; cva_units($sp,\%units_ang); }
362 sub cva_absang ($) { input_absang(cva_ang($_[0])) }
363 sub cva_units ($$) {
364     my ($sp,$ua)=@_;
365     my ($n,$u,$r);
366     $sp =~ m/^([-0-9eE.]*[0-9.])([A-Za-z]*)$/
367         or die "lexically invalid quantity";
368     ($n,$u)= ($1,$2);
369     $u=$ua->{'-'} unless length $u;
370     defined $ua->{$u} or die "unknown unit $u";
371     $r= $n * $ua->{$u};
372     print DEBUG "cva_units($sp,)=$r ($n $u $ua->{$u})\n";
373     return $r;
374 }
375 sub cva_idstr ($) {
376     my ($sp)=@_;
377     die "invalid id" unless $sp =~ m/^[a-z][_0-9A-Za-z]*$/;
378     return $&;
379 }
380 sub cva_idex ($) {
381     my ($sp)=@_;
382     my ($id,$r,$d,$k,$neg,$na,$obj_id,$vflip,$locs);
383     if ($sp =~ s/^(\^?)(\w+)\!//) {
384         $vflip= length($1);
385         $obj_id= $2;
386         die "invalid obj $obj_id in loc" unless exists $objs{$obj_id};
387         $locs= $objs{$obj_id}{Loc};
388     } else {
389         $locs= $ctx->{Loc};
390         $vflip= 0;
391     }
392     $neg= $sp =~ s/^\-//;
393     $id= cva_idstr($sp);
394     die "unknown $id" unless defined $locs->{$id};
395     $r= $locs->{$id};
396     $d= "idex $id";
397     foreach $k (sort keys %$r) { $d .= " $k=$r->{$k}"; }
398     printf DEBUG "%s\n", $d;
399     if ($vflip) {
400         $r= { X => $r->{X}, Y => -$r->{Y}, A => -$r->{A} };
401     }
402     if ($neg) {
403         $na= $r->{A} + $pi;
404         $na= a_normalise($na,0);
405         $r= { X => $r->{X}, Y => $r->{Y}, A => $na };
406     }
407     return $r;
408 }
409 sub cva_idnew ($) {
410     my ($sp)=@_;
411     my ($id, $neg);
412     $neg = $sp =~ s/^\-//;
413     $id=cva_idstr($sp);
414     die "duplicate $id" if exists $ctx->{Loc}{$id};
415     $ctx->{Loc}{$id}{LayerKind}= $ctx->{Layer}{Kind};
416     push @{ $ctx->{LocsMade} }, {
417         Id => $id,
418         Neg => $neg,
419     };
420     return $ctx->{Loc}{$id};
421 }
422 sub cva_cmd ($) { return cva_idstr($_[0]); }
423 sub cva__enum ($$) {
424     my ($sp,$el)=@_;
425     return $sp if grep { $_ eq $sp } @$el;
426     die "invalid option (permitted: @$el)";
427 }
428 sub cvam_enum { my (@e) = @_; return sub { cva__enum($_[0],\@e); }; }
429
430 sub cmd_abs {
431     my ($i,$nl);
432     $nl= can(\&cva_idnew);
433     $i->{X}= can(\&cva_len);
434     $i->{Y}= can(\&cva_len);
435     $i->{A}= can(\&cva_ang);
436     ev_compose($nl, $ctx->{Trans}, $i);
437 }
438 sub cmd_rel {
439     my ($from,$to,$len,$right,$turn);
440     $from= can(\&cva_idex);
441     $to= can(\&cva_idnew);
442     $len= cano(\&cva_len,0);
443     $right= cano(\&cva_len,0) * $ctx->{Trans}{R};
444     $turn= cano(\&cva_ang, 0) * $ctx->{Trans}{R};
445     my ($u)= ev_compose({}, $from, { X => $len, Y => -$right, A => 0 });
446     ev_compose($to, $u, { X => 0, Y => 0, A => $turn });
447 }
448
449 sub dv__evreff ($) {
450     my ($pfx) = @_;
451     $pfx . ($pfx =~ m/\}$|\]$/ ? '' : '->');
452 }
453 sub dv__evr ($) {
454     my ($v) = @_;
455     return 'undef' if !defined $v;
456     return $v if $v !~ m/\W/ && $v =~ m/[A-Z]/ && $v =~ m/^[a-z_]/i;
457     return $v if $v =~ m/^[0-9.]+/;
458     $v =~ s/[\\\']/\\$&/g;
459     return "'$v'";
460 }
461 sub dv1 ($$$);
462 sub dv1_kind ($$$$$$$) {
463     my ($pfx,$expr,$ref,$ref_exp,$ixfmt,$ixesfn,$ixmapfn) = @_;
464     my ($ix,$any);
465     return 0 if $ref ne $ref_exp;
466     $any=0;
467     foreach $ix (&$ixesfn) {
468         $any=1;
469         my ($v)= &$ixmapfn($ix);
470 #print STDERR "dv1_kind($pfx,$expr,$ref,$ref_exp,$ixmapfn) ix=$ix v=$v\n";
471         dv1($pfx,$expr.sprintf($ixfmt,dv__evr($ix)),$v);
472     }
473     if (!$any) {
474         printf DEBUG "%s%s= $ixfmt\n", $pfx, $expr, ' ';
475     }
476     1;
477 }    
478 sub dv1 ($$$) {
479     return 0 unless $debug;
480     my ($pfx,$expr,$v) = @_;
481     my ($ref);
482     $ref= ref $v;
483 #print STDERR "dv1 >$pfx|$ref<\n";
484     if (!$ref) {
485         printf DEBUG "%s%s= %s\n", $pfx,$expr, dv__evr($v);
486         return;
487     } elsif ($ref eq 'SCALAR') {
488         dv1($pfx, ($expr =~ m/^\$/ ? "\$$expr" : '${'.$expr.'}'), $$v);
489         return;
490     }
491     $expr.='->' unless $expr =~ m/\]$|\}$/;
492     return if dv1_kind($pfx,$expr,$ref,'ARRAY','[%s]',
493                        sub { ($[ .. $#$v) },
494                        sub { $v->[$_[0]] });
495     return if dv1_kind($pfx,$expr,$ref,'HASH','{%s}',
496                        sub { sort keys %$v },
497                        sub { $v->{$_[0]} });
498     printf DEBUG "%s%s is %s\n", $pfx, $expr, $ref;
499 }
500     
501 sub dv {
502     my ($pfx,@l) = @_;
503     my ($expr,$v,$ref);
504     while (@l) {
505         ($expr,$v,@l)=@l;
506         dv1($pfx,$expr,$v);
507     }
508 }                   
509
510 sub o ($) { $o .= $_[0]; }
511 sub ol ($) { $ol .= $_[0]; }
512 sub oflushpage () {
513     print $o, $ol, "  showpage\n"
514         or die $!;
515     $o=$ol='';
516 }
517
518 our $o_path_verb;
519
520 sub o_path_begin () {
521     o("      newpath\n");
522     $o_path_verb= 'moveto';
523 }
524 sub o_path_point ($) {
525     my ($pt)=@_;
526     o("        $pt $o_path_verb\n");
527     $o_path_verb= 'lineto';
528 }
529 sub o_path_stroke ($) {
530     my ($width)=@_;
531     o("        $width setlinewidth stroke\n");
532 }    
533
534 sub o_line ($$$) {
535     my ($a,$b,$width)=@_;
536     o_path_begin();
537     o_path_point($a);
538     o_path_point($b);
539     o_path_stroke($width);
540 }
541
542 sub current_draw () {
543     my ($r);
544     $r= $ctx->{Draw} =~ m/X/ ? '' : $ctx->{Draw};
545     $r;
546 }
547
548 sub psu_coords ($$$) {
549     my ($ends,$inunit,$across)=@_;
550     # $ends->[0]{X} etc.; $inunit 0 to 1 (but go to 1.5);
551     # $across in mm, +ve to right.
552     my (%ea_zo, $zo, $prop);
553     $ea_zo{X}=$ea_zo{Y}=0;
554     foreach $zo (qw(0 1)) {
555         $prop= $zo ? $inunit : (1.0 - $inunit);
556         $ea_zo{X} += $prop * ($ends->[$zo]{X} - $across * sin($ends->[0]{A}));
557         $ea_zo{Y} += $prop * ($ends->[$zo]{Y} + $across * cos($ends->[0]{A}));
558     }
559 #    dv("psu_coords ", '$ends',$ends, '$inunit',$inunit, '$across',$across,
560 #       '\\%ea_zo', \%ea_zo);
561     return $ea_zo{X}." ".$ea_zo{Y};
562 }
563
564 sub parametric__o_pt ($) {
565     my ($pt)=@_;
566     o_path_point("$pt->{X} $pt->{Y}");
567 }
568
569 sub parametric_segment ($$$$$) {
570     my ($p0,$p1,$lenperp,$minradius,$calcfn) = @_;
571     # makes $p (global) go from $p0 to $p1  ($p1>$p0)
572     # $lenperp is the length of one unit p, ie the curve
573     # must have a uniform `density' in parameter space
574     # $calcfn is invoked with $p set and should return a loc
575     # (ie, ref to X =>, Y =>, A =>).
576     my ($pa,$pb,@ends,$side,$ppu,$e,$v,$tick,$draw,$allwidth);
577     return unless $ctx->{Draw} =~ m/[ARSC]/;
578     $ppu= $psu_ulen/$lenperp;
579     $allwidth= allwidth($minradius);
580     my ($railctr)=($psu_gauge + $psu_raillw)*0.5;
581     my ($tickend)=($allwidth - $psu_ticklen);
582     my ($tickpitch)=($psu_ulen / $psu_ticksperu);
583     my ($sleeperctr)=($psu_ulen*0.5);
584     my ($sleeperend)=($psu_sleeperlen*0.5);
585 print DEBUG "ps $p0 $p1 $lenperp ($ppu)\n";
586     $draw= current_draw();
587     if ($draw =~ m/C/) {
588         my ($pt);
589         o("    $psu_thinlw setlinewidth\n");
590         o_path_begin();
591         for ($param=$p0; $param<$p1; $param += $ppu) {
592             parametric__o_pt(&$calcfn);
593         }
594         $param=$p1;
595         parametric__o_pt(&$calcfn);
596         o("      stroke\n");
597     }
598     return unless $draw =~ m/[ARS]/;
599     for ($pa= $p0; $pa<$p1; $pa=$pb) {
600         $pb= $pa + $ppu;
601         $param= $pa; $ends[0]= @ends ? $ends[1] : &$calcfn;
602         $param= $pb; $ends[1]= &$calcfn;
603 #print DEBUG "pa $pa $ends[0]{X} $ends[0]{Y} $ends[0]{A}\n";
604 #print DEBUG "pb $pb $ends[1]{X} $ends[1]{Y} $ends[1]{A}\n";
605         $e= $pb<=$p1 ? 1.0 : ($p1-$pa)/$ppu;
606         o("    gsave\n");
607         o_path_begin();
608         o_path_point(psu_coords(\@ends,0,-$allwidth));
609         o_path_point(psu_coords(\@ends,0,$allwidth));
610         o_path_point(psu_coords(\@ends,$e,$allwidth));
611         o_path_point(psu_coords(\@ends,$e,-$allwidth));
612         o("        closepath clip\n");
613         foreach $side qw(-1 1) {
614             if ($draw =~ m/R/) {
615                 o_line(psu_coords(\@ends,0,$side*$railctr),
616                        psu_coords(\@ends,1.5,$side*$railctr),
617                        $psu_raillw);
618             }
619         }
620         if ($draw =~ m/S/) {
621             o_line(psu_coords(\@ends,$sleeperctr,-$sleeperend),
622                    psu_coords(\@ends,$sleeperctr,+$sleeperend),
623                    $psu_sleeperlw);
624         }
625         if ($draw =~ m/A/) {
626             o("        0.5 setgray\n");
627             foreach $side qw(-1 1) {
628                 o_line(psu_coords(\@ends,0,$side*$allwidth),
629                        psu_coords(\@ends,1.5,$side*$allwidth),
630                        $psu_edgelw);
631                 for ($tick=0; $tick<1.5; $tick+=$tickpitch/$psu_ulen) {
632                     o_line(psu_coords(\@ends,$tick,$side*$allwidth),
633                            psu_coords(\@ends,$tick,$side*$tickend),
634                            $psu_ticklw);
635                 }
636             }
637         }
638         o("      grestore\n");
639     }
640 }
641
642 sub arc ($$$$$) {
643     my ($to, $ctr,$from, $radius,$delta) = @_;
644     # does parametric_segment to draw an arc centred on $ctr
645     # ($ctr->{A} ignored)
646     # from $from with radius $radius (this must be consistent!)
647     # and directionally-subtending an angle $delta.
648     # sets $to->... to be the other end, and returns $to
649     my ($beta);
650     $to->{A}= $beta= $from->{A} + $delta;
651     $to->{X}= $ctr->{X} - $radius * sin($beta);
652     $to->{Y}= $ctr->{Y} + $radius * cos($beta);
653     return if abs($delta*$radius) < 1e-9;
654     parametric_segment(0.0,1.0, abs($radius*$delta), $radius, sub {
655         my ($beta) = $from->{A} + $delta * $param;
656         return { X => $ctr->{X} - $radius * sin($beta),
657                  Y => $ctr->{Y} + $radius * cos($beta),
658                  A => $beta }
659     });
660 }
661
662 # joins_xxx all take $results, $from, $to, $minradius
663 # where $results->[]{Path}{K} etc. and $results->[]{SolKinds}[]
664
665 sub joins_twoarcs ($$$$) {
666     my ($results, $from,$to,$minradius) = @_;
667     # two circular arcs of equal maximum possible radius
668     # algorithm courtesy of Simon Tatham (`Railway problem',
669     # pers.comm. to ijackson@chiark 23.1.2004)
670     my ($sigma,$distfact, $theta,$phi, $a,$b,$c,$d, $m,$r, $radius);
671     my ($cvec,$cfrom,$cto,$midpt, $delta1,$delta2, $path,$reverse);
672     $sigma= ev_bearing($from,$to);
673     $distfact= v_dist($from,$to);
674     $theta= 0.5 * $pi - ($from->{A} - $sigma);
675     $phi=   0.5 * $pi - ($to->{A} + $pi - $sigma);
676     $a= 2 * (1 + cos($theta - $phi));
677     $b= 2 * (cos($theta) - cos($phi));
678     $c= -1;
679     $d= sqrt($b*$b - 4*$a*$c);
680     o("%     twoarcs theta=".ang2deg($theta)." phi=".ang2deg($phi).
681       " ${a}r^2 + ${b}r + ${c} = 0\n");
682     foreach $m (qw(-1 1)) {
683         if ($a < 1e-6) {
684             o("%     twoarcs $m insoluble\n");
685             next;
686         }
687         $r= -0.5 * (-$b + $m*$d) / $a;
688         $radius= -$r * $distfact;
689         o("%     twoarcs $m radius $radius ");
690         if (abs($radius) < $minradius) { o("too-small\n"); next; }
691         $cfrom=  ev_compose({}, $from, { X=>0, Y=>-$radius, A=>-0.5*$pi });
692         $cto=    ev_compose({}, $to,   { X=>0, Y=> $radius, A=> 0.5*$pi });
693         $midpt=  ev_lincomb({}, $cfrom, $cto, 0.5);
694         $reverse= signum($r);
695         if ($reverse<0) {
696             $cfrom->{A} += $pi;
697             $cto->{A} += $pi;
698         }
699         $delta1= ev_bearing($cfrom, $midpt) - $cfrom->{A};
700         $delta2= ev_bearing($cto,   $midpt) - $cto->{A};
701         o("ok deltas ".ang2deg($delta1)." ".ang2deg($delta2)."\n");
702         if ($reverse<0) {
703             $delta1 -= 2*$pi;
704             $delta2 -= 2*$pi;
705         }
706         my ($fs);
707         $path= [{ T=>Arc, F=>$from, C=>$cfrom, R=> $radius, D=>$delta1 },
708                 { T=>Arc, F=>$to,   C=>$cto,   R=>-$radius, D=>$delta2 }];
709         push @$results, { Path => $path,
710                           SolKinds =>  [ 'twoarcs', 'cross' ] };
711     }
712 }
713     
714 sub joins_arcsline ($$$$) {
715     my ($results, $from,$to,$minradius) = @_;
716     # two circular arcs of specified radius
717     # with an intervening straight
718     my ($lr,$inv, $c,$d,$alpha,$t,$k,$l,$rpmsina,$rcosa,$linelen, $path);
719     if ($minradius<=1e-6) { o("%     arcsline no-radius\n"); return; }
720     foreach $lr (qw(-1 +1)) {
721         foreach $inv (qw(-1 +1)) {
722             $c=ev_compose({},$from,{X=>0,Y=>-$lr*$minradius, A=>0 });
723             $d=ev_compose({},$to,{X=>0, Y=>-$inv*$lr*$minradius, A=>$pi });
724             $t= v_dist($c,$d);
725             o("%     arcsline $lr $inv t=$t ");
726             if ($t < 1e-6) { o("concentric"); next; }
727             $c->{A}= $d->{A}= ev_bearing($c,$d);
728             o("bearing ".ang2deg($c->{A}));
729             if ($inv>0) {
730                 o("\n");
731                 $k= ev_compose({}, $c, { X=>0, Y=>$lr*$minradius, A=>0 });
732                 $l= ev_compose({}, $d, { X=>0, Y=>$lr*$minradius, A=>0 });
733                 $linelen= $t;
734             } else {
735                 my ($cosalpha) = 2.0 * $minradius / $t;
736                 if ($cosalpha > (1.0 - 1e-6)) { o(" too-close\n"); next; }
737                 $alpha= acos($cosalpha);
738                 $rpmsina= $lr * $minradius * sin($alpha);
739                 $rcosa= $minradius * $cosalpha;
740                 $k= ev_compose({}, $c, { X=>$rcosa, Y=>$rpmsina, A=>0 });
741                 $l= ev_compose({}, $d, { X=>-$rcosa, Y=>-$rpmsina, A=>0 });
742                 $k->{A}= $l->{A}= ev_bearing($k,$l);
743                 o(" alpha=".ang2deg($alpha)." kl^=".ang2deg($k->{A})."\n");
744                 $linelen= v_dist($k,$l);
745             }
746             $path= [{ T => Arc, F => $from, C => $c,
747                       R =>$lr*$minradius,
748                       D => -$lr * a_normalise
749                           ($lr * ($from->{A} - $k->{A}), 0) },
750                     { T => Line, A => $k, B => $l, L => $linelen },
751                     { T => Arc, F => $l, C => $d,
752                       R => $inv*$lr*$minradius,
753                       D => -$lr*$inv * a_normalise
754                           (-$lr*$inv * ($to->{A} - $l->{A}), 0) }];
755             push @$results,
756             { Path => $path,
757               SolKinds => [ 'arcsline', ($inv<0 ? 'cross' : 'loop') ] };
758         }
759     }
760 }
761
762 sub joins_arcline ($$$$) {
763     my ($results, $from,$to,$minradius) = @_;
764     # one circular arc and a straight line
765     my ($swap,$echoice,$path, $ap,$bp,$av,$bv, $e,$f, $ae,$af,$afae);
766     my ($dak,$ak,$kj,$k,$j,$aja,$jl,$l,$jc,$lc,$c,$rj,$rb);
767     foreach $swap (qw(-1 +1)) {
768         foreach $echoice (qw(0 1)) {
769             $ap= $from; $bp= { %$to }; $bp->{A} += $pi;
770             ($ap,$bp)= ($bp,$ap) if $swap<0;
771             $av= ev_byang({}, $ap->{A});
772             $bv= ev_byang({}, $bp->{A});
773             $e= ev_byang({}, 0.5 * ($ap->{A} + $bp->{A} + $echoice * $pi));
774             $f= v_rotateright($e);
775             o("%     arcline $swap $echoice e ".loc2dbg($e)."\n");
776             $ae= v_dotproduct($av,$e);
777             $af= v_dotproduct($av,$f);
778             o("%     arcline $swap $echoice a.e=$ae a.f=$af ");
779             if (abs($ae) < 1e-6) { o(" singular\n"); next; }
780             $afae= $af/$ae;
781             o("a.f/a.e=$afae\n");
782             $dak= v_dotproduct(v_subtract($ap,$bp), $e);
783             $ak= v_scalarmult($dak, $e);
784             $kj= v_scalarmult($dak * $afae, $f);
785             $k= v_add($ap, $ak);
786             $j= v_add($k, $kj);
787             $aja= v_dotproduct(v_subtract($ap,$j), $av);
788             o("%     arcline $swap $echoice d_ak=$dak aj.a=$aja ");
789             if ($aja < 0) { o(" backwards aj\n"); next; }
790             $jl= v_scalarmult(0.5, v_subtract($j, $bp));
791             $lc= v_scalarmult(-v_dotproduct($jl, $f) * $afae, $e);
792             $l= v_add($j, $jl);
793             $c= v_add($l, $lc);
794             $rj= v_dotproduct(v_subtract($j,$c), v_rotateright($av));
795             $rb= v_dotproduct(v_subtract($c,$bp), v_rotateright($bv));
796             o("r_j=$rj r_b=$rb ");
797             if ($rj * $rb < 0) { o(" backwards b\n"); next; }
798             if (abs($rj) < $minradius) { o(" too-small\n"); next; }
799             o("ok\n");
800             $j->{A}= $ap->{A};
801             $c->{A}= 0;
802             $path= [{ T => Line, A => $ap, B => $j, L => $aja },
803                     { T => Arc, F => $j, C => $c, R => $rj,
804                       D => -signum($rj) * a_normalise
805                           (-signum($rj) * ($bp->{A} + $pi - $j->{A}), 0) }];
806             $path= [ reverse @$path ] if $swap<0;
807             push @$results, { Path => $path, SolKinds =>  [ 'arcline' ] };
808         }
809     }
810 }
811
812 sub cmd_join {
813     my ($from,$to,$minradius);
814     my (@results,$result);
815     my ($path,$segment,$bestpath,$len,$scores,$bestscores,@bends,$skl);
816     my ($crit,$cs,$i,$cmp);
817     $from= can(\&cva_idex);
818     $to= can(\&cva_idex);
819     $minradius= can(\&cva_len);
820     o("%   join ".loc2dbg($from)."..".loc2dbg($to)." $minradius\n");
821     joins_twoarcs(\@results, $from,$to,$minradius);
822     joins_arcsline(\@results, $from,$to,$minradius);
823     joins_arcline(\@results, $from,$to,$minradius);
824     foreach $result (@results) {
825         $path= $result->{Path};
826         $skl= $result->{SolKinds};
827         o("%   possible path @$skl $path\n");
828         $len= 0;
829         @bends= ();
830         foreach $segment (@$path) {
831             if ($segment->{T} eq Arc) {
832                 o("%     Arc C ".loc2dbg($segment->{C}).
833                   " R $segment->{R} D ".ang2deg($segment->{D})."\n");
834                 $len += abs($segment->{R} * $segment->{D});
835                 push @bends, -abs($segment->{R}) * $segment->{D}; # right +ve
836             } elsif ($segment->{T} eq Line) {
837                 o("%     Line A ".loc2dbg($segment->{A}).
838                   " B ".loc2dbg($segment->{A})." L $segment->{L}\n");
839                 $len += abs($segment->{L});
840             } else {
841                 die "unknown segment $segment->{T}";
842             }
843         }
844         o("%    length $len bends @bends.\n");
845         $scores= [];
846         foreach $crit (@al, 'short') {
847             if ($crit eq 'long') { $cs= $len; }
848             elsif ($crit eq 'short') { $cs= -$len; }
849             elsif ($crit =~ m/^(begin|end|)(left|right)$/) {
850                 if ($1 eq 'begin') { $cs= $bends[0]; }
851                 elsif ($1 eq 'end') { $cs= $bends[$#bends]; }
852                 else { $cs=0; map { $cs += $_ } @bends; }
853                 $cs= -$cs if $2 eq 'left';
854             } elsif ($crit =~ m/^(\!?)(twoarcs|arcs?line|cross|loop)$/) {
855                 $cs= !!(grep { $2 eq $_ } @$skl) != ($1 eq '!');
856             } else {
857                 die "unknown sort criterion $crit";
858             }
859             push @$scores, $cs;
860         }
861         o("%    scores @$scores\n");
862         if (defined $bestpath) {
863             for ($i=0,$cmp=0; !$cmp && $i<@$scores; $i++) {
864                 $cmp= $scores->[$i] <=> $bestscores->[$i];
865             }
866             next if $cmp < 0;
867         }
868         $bestpath= $path;
869         $bestscores= $scores;
870     }
871     die "no solution" unless defined $bestpath;
872     o("%   chose path $bestpath @al\n");
873     @al= ();
874     foreach $segment (@$bestpath) {
875         if ($segment->{T} eq 'Arc') {
876             arc({}, $segment->{C},$segment->{F},$segment->{R},$segment->{D});
877         } elsif ($segment->{T} eq 'Line') {
878             line($segment->{A}, $segment->{B}, $segment->{L});
879         } else {
880             die "unknown segment";
881         }
882     }
883 }
884
885 sub line ($$$) {
886     my ($from,$to,$len) = @_;
887     parametric_segment(0.0, 1.0, abs($len) + 1e-6, undef, sub {
888         ev_lincomb({}, $from, $to, $param);
889     });
890 }
891
892 sub cmd_extend {
893     my ($from,$to,$radius,$len,$upto,$ctr,$beta,$ang,$how,$sign_r);
894     $from= can(\&cva_idex);
895     $to= can(\&cva_idnew);
896     printf DEBUG "from $from->{X} $from->{Y} $from->{A}\n";
897     $how= can(cvam_enum(qw(len upto ang uptoang parallel)));
898     if ($how eq 'len') { $len= can(\&cva_len); }
899     elsif ($how =~ m/ang$/) { $ang= can(\&cva_ang); }
900     elsif ($how eq 'parallel' || $how eq 'upto') { $upto= can(\&cva_idex); }
901     $radius= cano(\&cva_len, 'Inf'); # +ve is right hand bend
902     if ($radius eq 'Inf') {
903 #       print DEBUG "extend inf $len\n";
904         if ($how eq 'upto') {
905             $len= ($upto->{X} - $from->{X}) * cos($from->{A})
906                 + ($upto->{Y} - $from->{Y}) * sin($from->{A});
907         } elsif ($how eq 'len') {
908         } else {
909             die "len of straight spec by angle";
910         }
911         printf DEBUG "len $len\n";
912         $to->{X}= $from->{X} + $len * cos($from->{A});
913         $to->{Y}= $from->{Y} + $len * sin($from->{A});
914         $to->{A}= $from->{A};
915         line($from,$to,$len);
916     } else {
917         my ($sign_r, $sign_ang, $ctr, $beta_interval, $beta, $delta);
918         print DEBUG "radius >$radius<\n";
919         $radius *= $ctx->{Trans}{R};
920         $sign_r= signum($radius);
921         $sign_ang= 1;
922         $ctr->{X}= $from->{X} + $radius * sin($from->{A});
923         $ctr->{Y}= $from->{Y} - $radius * cos($from->{A});
924         if ($how eq 'upto') {
925             $beta= atan2(-$sign_r * ($upto->{X} - $ctr->{X}),
926                          $sign_r * ($upto->{Y} - $ctr->{Y}));
927             $beta_interval= 1.0;
928         } elsif ($how eq 'parallel') {
929             $beta= $upto->{A};
930             $beta_interval= 1.0;
931         } elsif ($how eq 'uptoang') {
932             $beta= input_absang($ang);
933             $beta_interval= 2.0;
934         } elsif ($how eq 'len') {
935             $sign_ang= signum($len);
936             $beta= $from->{A} - $sign_r * $len / abs($radius);
937             $beta_interval= 2.0;
938         } else {
939             $sign_ang= signum($ang);
940             $beta= $from->{A} - $sign_r * $ang;
941             $beta_interval= 2.0;
942         }
943     printf DEBUG "ctr->{Y}=$ctr->{Y} radius=$radius beta=$beta\n";
944         $beta += $sign_ang * $sign_r * 4.0 * $pi;
945         for (;;) {
946             $delta= $beta - $from->{A};
947             last if $sign_ang * $sign_r * $delta <= 0;
948             $beta -= $sign_ang * $sign_r * $beta_interval * $pi;
949         }
950     printf DEBUG "ctr->{Y}=$ctr->{Y} radius=$radius beta=$beta\n";
951         arc($to, ,$ctr,$from, $radius,$delta);
952     }
953     printf DEBUG "to $to->{X} $to->{Y} $to->{A}\n";
954 }
955
956 sub loc2dbg ($) {
957     my ($loc) = @_;
958     return "$loc->{X} $loc->{Y} ".ang2deg($loc->{A});
959 }
960 sub ang2deg ($) {
961     return $_[0] * 180 / $pi;
962 }
963 sub input_absang ($) {
964     return $_[0] * $ctx->{Trans}{R} + $ctx->{Trans}{A};
965 }
966 sub input_abscoords ($$) {
967     my ($in,$out);
968     ($in->{X}, $in->{Y}) = @_;
969     $in->{A}= 0.0;
970     $out= ev_compose({}, $ctx->{Trans}, $in);
971     return ($out->{X}, $out->{Y});
972 }
973
974 sub newctx (;$) {
975     my ($ctx_save) = @_;
976     $ctx= {
977         Trans => { X => 0.0, Y => 0.0, A => 0.0, R => 1.0 },
978         InRunObj => "",
979         DrawMap => sub { $_[0]; }
980         };
981     %{ $ctx->{Layer} }= %{ $ctx_save->{Layer} }
982         if defined $ctx_save;
983 }
984
985 our $defobj_save;
986 our $defobj_ispart;
987
988 sub cmd_defobj { cmd__defobj(0); }
989 sub cmd_defpart { cmd__defobj(1); }
990 sub cmd__defobj ($) {
991     my ($ispart) = @_;
992     my ($id);
993     $id= can(\&cva_idstr);
994     die "nested defobj" if $defobj_save;
995     die "repeated defobj" if exists $objs{$id};
996     $defobj_save= $ctx;
997     $defobj_ispart= $ispart;
998     newctx($defobj_save);
999     $ctx->{CmdLog}= [ ];
1000     $ctx->{InDefObj}= $id;
1001     $ctx->{Draw}= $defobj_save->{Draw}.'X';
1002     $ctx->{DrawMap}= sub { ''; };
1003     $ctx->{Layer}= { Level => 5, Kind => '' };
1004 }
1005
1006 sub cmd_enddef {
1007     my ($bit,$id);
1008     $id= $ctx->{InDefObj};
1009     die "unmatched enddef" unless defined $id;
1010     foreach $bit (qw(CmdLog Loc)) {
1011         $objs{$id}{$bit}= $ctx->{$bit};
1012     }
1013     $objs{$id}{Part}= $defobj_ispart;
1014     $ctx= $defobj_save;
1015     $defobj_save= undef;
1016     $defobj_ispart= undef;
1017 }
1018
1019 sub cmd__runobj ($) {
1020     my ($obj_id)=@_;
1021     my ($c);
1022     local (@al);
1023     dv("cmd__runobj $obj_id ",'$ctx',$ctx);
1024     foreach $c (@{ $objs{$obj_id}{CmdLog} }) {
1025         @al= @$c;
1026         next if $al[0] eq 'enddef';
1027         cmd__one();
1028     }
1029 }
1030
1031 sub layer_draw ($$) {
1032     my ($k,$l) = @_;
1033     my ($eo,$cc, $r);
1034     if ($k eq '') {
1035         $r= 'RLMN';
1036     } elsif ($k eq 's') {
1037         $r= '';
1038     } elsif ($k eq 'l') {
1039         $r= 'CLMN';
1040     } else {
1041         $r= 'ARSCLMNO';
1042     }
1043     foreach $eo (@eopts) {
1044 #print STDERR "$. layer $k$l eo $eo re $eo->{GlobRe} then $eo->{DrawMods} now $r\n";
1045         next unless $k =~ m/^$eo->{GlobRe}$/;
1046 #print STDERR "$. layer $k$l eo re $eo->{GlobRe} match\n";
1047         next unless &{ $eo->{LayerCheck} }($l);
1048 #print STDERR "$. layer $k$l eo re $eo->{GlobRe} checked\n";
1049         foreach $cc (split //, $eo->{DrawMods}) {
1050             $r =~ s/$cc//ig;
1051             $r .= $cc if $cc =~ m/[A-Z]/;
1052         }
1053     }
1054 #print STDERR "layer $k$l gives $r (before map)\n";
1055     $r= &{ $ctx->{DrawMap} }($r);
1056     return $r;
1057 }
1058
1059 sub cmd_layer {
1060     my ($kl, $k,$l);
1061     $kl= can(\&cva_identity);
1062     $kl =~ m/^([A-Za-z_]*)(\d*|\=|\*)$/ or die "invalid layer spec";
1063     ($k,$l)=($1,$2);
1064     $l= $output_layer if $l eq '*';
1065     $l= $ctx->{Layer}{Level} if $l =~ m/^\=?$/;
1066     $ctx->{Layer}{Kind}= $k;
1067     $ctx->{Layer}{Level}= $l;
1068     $ctx->{Draw}= layer_draw($k,$l);
1069 }    
1070
1071 sub cmd_part { cmd__obj(Part); }
1072 sub cmd_obj { cmd__obj(1); }
1073 sub cmd_objflip { cmd__obj(-1); }
1074
1075 sub cmd__obj ($) {
1076     my ($how)=@_;
1077     my ($obj_id, $ctx_save, $pfx, $actual, $formal_id, $formal, $formcv);
1078     my ($part_name, $ctx_inobj, $obj, $id, $newid, $newpt);
1079     if ($how eq Part) {
1080         $part_name= can(\&cva_idstr);
1081         $how= (@al && $al[0] =~ s/^\^//) ? -1 : +1;
1082     }
1083     $obj_id= can(\&cva_idstr);
1084     if (defined $part_name) {
1085         $formal_id= can(\&cva_idstr);
1086         $actual= cano(\&cva_idex, undef);
1087         if (!defined $actual) {
1088             $actual= cva_idex("${part_name}_${formal_id}");
1089         }
1090     } else {
1091         $actual= can(\&cva_idex);
1092         $formal_id= can(\&cva_idstr);
1093     }
1094     $obj= $objs{$obj_id};
1095     dv("cmd__obj ",'$obj',$obj);
1096     die "unknown obj $obj_id" unless $obj;
1097     $formal= $obj->{Loc}{$formal_id};
1098     die "unknown formal $formal_id" unless $formal;
1099     $ctx_save= $ctx;
1100     newctx($ctx_save);
1101     $how *= $ctx_save->{Trans}{R};
1102     $ctx->{Trans}{R}= $how;
1103     $ctx->{Trans}{A}= $actual->{A} - $formal->{A}/$how;
1104     $formcv= ev_compose({}, $ctx->{Trans},$formal);
1105     $ctx->{Trans}{X}= $actual->{X} - $formcv->{X};
1106     $ctx->{Trans}{Y}= $actual->{Y} - $formcv->{Y};
1107     if (defined $part_name) {
1108         $ctx->{InRunObj}= $ctx_save->{InRunObj}."${part_name}:";
1109     } else {
1110         $ctx->{InRunObj}= $ctx_save->{InRunObj}."${obj_id}::";
1111     }
1112     $ctx->{DrawMap}= sub {
1113         my ($i) = @_;
1114         $i= &{ $ctx_save->{DrawMap} }($i);
1115         if ($obj->{Part}) {
1116             $i =~ s/[LMN]//g;
1117             $i =~ s/O/MNO/;
1118         } else {
1119             $i =~ s/[LM]//g;
1120             $i =~ s/N/MN/;
1121         }
1122         return $i;
1123     };
1124     $ctx->{Draw}= &{ $ctx->{DrawMap} }($ctx_save->{Draw});
1125     cmd__runobj($obj_id);
1126     if (defined $part_name) {
1127         $pfx= $part_name.'_';
1128     } else {
1129         if (@al && $al[0] eq '=') {
1130             $pfx= ''; shift @al;
1131         } else {
1132             $pfx= cano(\&cva_idstr,undef);
1133         }
1134     }
1135     $ctx_inobj= $ctx;
1136     $ctx= $ctx_save;
1137     if (defined $pfx) {
1138         foreach $id (keys %{ $ctx_inobj->{Loc} }) {
1139             next if $id eq $formal_id;
1140             $newid= $pfx.$id;
1141             next if exists $ctx_save->{Loc}{$newid};
1142             $newpt= cva_idnew($newid);
1143             %$newpt= %{ $ctx_inobj->{Loc}{$id} };
1144         }
1145     }
1146     if (defined $part_name) {
1147         my ($formalr_id, $actualr_id, $formalr, $actualr);
1148         while (@al) {
1149             die "part results come in pairs\n" unless @al>=2;
1150             ($formalr_id, $actualr_id, @al) = @al;
1151             if ($actualr_id =~ s/^\-//) {
1152                 $formalr_id= "-$formalr_id";
1153                 $formalr_id =~ s/^\-\-//;
1154             }
1155             {
1156                 local ($ctx) = $ctx_inobj;
1157                 $formalr= cva_idex($formalr_id);
1158             }
1159             $actualr= cva_idnew($actualr_id);
1160             %$actualr= %$formalr;
1161         }
1162     }
1163 }
1164
1165 sub cmd__do {
1166     my ($cmd);
1167 dv("cmd__do $ctx @al ",'$ctx',$ctx);
1168     $cmd= can(\&cva_cmd);
1169     my ($lm,$id,$loc,$io,$ad,$draw,$thendrawre);
1170     $io= defined $ctx->{InDefObj} ? "$ctx->{InDefObj}!" : $ctx->{InRunObj};
1171     o("%L cmd   $io $cmd @al\n");
1172     $ctx->{LocsMade}= [ ];
1173     {
1174         no strict 'refs';
1175         &{ "cmd_$cmd" };
1176     };
1177     die "too many args" if @al;
1178     foreach $lm (@{ $ctx->{LocsMade} }) {
1179         $id= $lm->{Id};
1180         $loc= $ctx->{Loc}{$id};
1181         $loc->{A} += $pi if $lm->{Neg};
1182         $ad= ang2deg($loc->{A});
1183         ol("%L point $io$id ".loc2dbg($loc)." ($lm->{Neg})\n");
1184         $draw= layer_draw($loc->{LayerKind}, $ctx->{Layer}{Level});
1185         if ($draw =~ m/[LM]/) {
1186             ol("    gsave\n".
1187                "      $loc->{X} $loc->{Y} translate $ad rotate\n");
1188             if ($draw =~ m/M/) {
1189                 ol("      0 $allwidthmin newpath moveto\n".
1190                    "      0 -$allwidthmin lineto\n".
1191                    "      $lmu_marklw setlinewidth stroke\n");
1192             }
1193             if ($draw =~ m/L/) {
1194                 ol("      /s ($id) def\n".
1195                    "      lf setfont\n".
1196                    "      /sx5  s stringwidth pop\n".
1197                    "      0.5 mul $lmu_txtboxpadx add def\n".
1198                    "      -90 rotate  0 $lmu_txtboxoff translate  newpath\n".
1199                    "      sx5 neg  0             moveto\n".
1200                    "      sx5 neg  $lmu_txtboxh  lineto\n".
1201                    "      sx5      $lmu_txtboxh  lineto\n".
1202                    "      sx5      0             lineto closepath\n".
1203                    "      gsave  1 setgray fill  grestore\n".
1204                    "      $lmu_txtboxlw setlinewidth stroke\n".
1205                    "      sx5 neg $lmu_txtboxpadx add  $lmu_txtboxtxty\n".
1206                    "      moveto s show\n");
1207             }
1208             ol("      grestore\n");
1209         }
1210     }
1211 }
1212
1213 sub cmd_showlibrary {
1214     my ($obj_id, $y, $x, $ctx_save, $width, $height);
1215     my ($max_x, $min_x, $max_y, $min_y, $nxty, $obj, $loc, $pat, $got, $glob);
1216     my ($adj);
1217     $x=$olu_left; $y=$olu_bottom; undef $nxty;
1218     $ctx_save= $ctx;
1219     foreach $obj_id (sort keys %objs) {
1220         $got= 1;
1221         foreach $glob (@al) {
1222             $pat= $glob;
1223             $got= !($pat =~ s/^\!//);
1224             die "bad pat" if $pat =~ m/[^0-9a-zA-Z_*?]/;
1225             $pat =~ s/\*/\.*/g; $pat =~ s/\?/./g;
1226             last if $obj_id =~ m/^$pat$/;
1227             $got= !$got;
1228         }
1229         next unless $got;           
1230         $obj= $objs{$obj_id};
1231         next unless $obj->{Part};
1232         ($min_x, $max_x, $min_y, $max_y) = bbox($obj->{Loc});
1233         newctx($ctx_save);
1234
1235         for (;;) {
1236             $width= $max_x - $min_x;
1237             $height= $max_y - $min_y;
1238             if ($width < $height) {
1239                 $ctx->{Trans}{A}= 0;
1240                 $ctx->{Trans}{X}= $x - $min_x;
1241                 $ctx->{Trans}{Y}= $y - $min_y + $olu_textheight;
1242             } else {
1243                 ($width,$height)=($height,$width);
1244                 $ctx->{Trans}{A}= 0.5 * $pi;
1245                 $ctx->{Trans}{X}= $x + $max_y;
1246                 $ctx->{Trans}{Y}= $y - $min_x + $olu_textheight;
1247             }
1248             $adj= length($obj_id) * $olu_textallowperc - $width;
1249             $adj=0 if $adj<0;
1250             $width += $adj;
1251             $ctx->{Trans}{X} += 0.5 * $adj;
1252             if ($x + $width > $olu_right && defined $nxty) {
1253                 $x= $olu_left;
1254                 $y= $nxty;
1255                 undef $nxty;
1256             } elsif ($y + $height > $olu_top && $y > $olu_bottom) {
1257                 oflushpage();
1258                 $x= $olu_left; $y= $olu_bottom;
1259                 undef $nxty;
1260             } else {
1261                 last;
1262             }
1263         }
1264             
1265         $ctx->{InRunObj}= $ctx_save->{InRunObj}."${obj_id}//";
1266         $ctx->{Draw}= $ctx_save->{Draw};
1267         cmd__runobj($obj_id);
1268         ol("    gsave\n".
1269            "      /s ($obj_id) def\n".
1270            "      lf setfont\n      ".
1271            ($x + 0.5*$width)." ".($y - $olu_textheight)." moveto\n".
1272            "      s stringwidth pop -0.5 mul  0  rmoveto\n".
1273            "      s show grestore\n");
1274         $x += $width + $olu_gap_x;
1275         upd_max(\$nxty, $y + $height + $olu_gap_y + $olu_textheight);
1276     }
1277     @al= ();
1278     $ctx= $ctx_save;
1279 }
1280
1281 sub cmd__one {
1282     cmd__do();
1283 }
1284
1285 print
1286     "%!\n".
1287     "  /lf /Courier-New findfont $lmu_marktpt scalefont def\n".
1288     "  $ps_page_shift 0 translate 90 rotate\n"
1289     or die $!;
1290
1291 if ($page_x || $page_y) {
1292     print
1293         "  /Courier-New findfont 15 scalefont setfont\n".
1294         "  30 30 moveto (${page_x}x${page_y}) show\n"
1295         or die $!;
1296 }
1297
1298 print
1299     "  -$ps_page_xmul $page_x mul  -$ps_page_ymul $page_y mul  translate\n".
1300     "  $ptscale $ptscale scale\n"
1301     or die $!;
1302
1303 newctx();
1304
1305 open DEBUG, ($debug ? ">&2" : ">/dev/null") or die $!;
1306
1307 if ($debug) {
1308     select(DEBUG); $|=1;
1309     select(STDOUT); $|=1;
1310 }
1311
1312 $ctx->{Draw}= '';
1313
1314 @al= qw(layer 5);
1315 cmd__one();
1316
1317 while (<>) {
1318     next if m/^\s*\#/;
1319     chomp; s/^\s+//; s/\s+$//;
1320     @al= split /\s+/, $_;
1321     next unless @al;
1322     print DEBUG "=== @al\n";
1323     last if $al[0] eq 'eof';
1324     push @{ $ctx->{CmdLog} }, [ @al ] if exists $ctx->{CmdLog};
1325     cmd__one();
1326 }
1327
1328 {
1329     my ($min_x, $max_x, $min_y, $max_y) = bbox($ctx->{Loc});
1330     my ($bboxstr);
1331     if (defined $min_x) {
1332         $bboxstr= sprintf("width  %.2d (%.2d..%2.d)\n".
1333                           "height %.2d (%.2d..%2.d)\n",
1334                           $max_x - $min_x, $min_x, $max_x,
1335                           $max_y - $min_y, $min_y, $max_y);
1336     } else {
1337         $bboxstr= "no locs, no bbox\n";
1338     }
1339     if (!$quiet) { print STDERR $bboxstr; }
1340     $bboxstr =~ s/^/\%L bbox /mg;
1341     print $bboxstr or die $!;
1342
1343     if ($scale < 1.5) {
1344         my ($tick_x, $tick_y, $ticklen);
1345         $ticklen= 10;
1346         printf("    gsave 0.5 setgray 0.33 setlinewidth\n".
1347                "      /regmark {\n".
1348                "        newpath moveto\n".
1349                "        -%d 0 rmoveto %d 0 rlineto\n".
1350                "        -%d -%d rmoveto 0 %d rlineto stroke\n".
1351                "      } def\n",
1352                $ticklen, $ticklen*2, $ticklen, $ticklen, $ticklen*2)
1353             or die $!;
1354         for ($tick_x= $min_x; $tick_x < $max_x; $tick_x += 150) {
1355             for ($tick_y= $min_y; $tick_y < $max_y; $tick_y += 150) {
1356                 printf("      %f %f regmark\n",
1357                        $tick_x, $tick_y)
1358                     or die $!;
1359             }
1360         }
1361         printf("    grestore\n")
1362             or die $!;
1363     }
1364 }
1365
1366 oflushpage();