18 our $output_layer= '*';
20 our $subsegmovfeatpos='f';
21 our $subsegcmapangscale;
23 our $ps_page_shift= 615;
24 our $ps_page_xmul= 765.354;
25 our $ps_page_ymul= 538.583;
29 our @ident_strings= ();
33 our $drawers= 'arqscldmnoge';
34 our %chdraw_emap= qw(A ARScgd
50 while (@ARGV && $ARGV[0] =~ m/^\-/) {
51 last if $ARGV[0] eq '-';
56 if (s/^D(\d+)//) { $debug= $1; }
57 elsif (s/^D//) { $debug++; }
58 elsif (s/^q//) { $quiet=1; }
59 elsif (s/^l(\d+|\*)//) { $output_layer=$1; }
60 elsif (s/^S([0-9.]+)$//) { $scale= $1 * 1.0; }
61 elsif (s/^P(\d+)x(\d+)$//) { $page_x= $1; $page_y= $2; }
62 elsif (s/^GR//) { $subsegcmapreq=1; }
63 elsif (s/^GP(\d+|f)$//) { $subsegmovfeatpos=$1; }
64 elsif (s/^GL(.*)$//) {
66 my ($sscmf, $datum, $csss, $angbits);
68 $sscmf= new IO::File $sscmfn, 'r'
69 or die "$sscmfn: cannot open: $!\n";
71 $!=0; $_= <$sscmf>; die $! unless defined $_;
74 m,^C\s+(\w*/(?:[A-Za-z_]+)?)\s+(0x[0-9a-f]+)\s+(\d+)\s*$,
75 or die "$sscmfn:$.: syntax error in subseg cmap\n";
76 ($csss,$datum,$angbits)= ($1,$2,$3);
77 if (!defined $subsegcmapangscale) {
78 $subsegcmapangscale= 1<<$angbits;
80 die "angbits varies" if $subsegcmapangscale != 1<<$angbits;
84 die "sorry, cannot put any movfeatpos or segment in red";
86 $subsegcmap{$csss}= sprintf("%.6f %.6f",
87 (($datum >> 8) & 0xff)/255.0,
88 (($datum >> 16) & 0xff)/255.0);
90 $sscmf->error and die "$sscmfn: error reading: $!\n";
93 ((?:[a-z]|\*|\?|\[[a-z][-a-z]*\])*?)
94 (\~?) (\d*) (\=*|\-+|\++) (\d*|\*)
96 my ($ee,$g,$n,$d,$c,$v,$cc) = ($1,$2,$3,$4,$5,$6,$7);
97 my ($eo, $invert, $lfn, $ccc, $sense,$limit);
98 $g =~ s/\?/\./g; $g =~ s/\*/\.\*/g;
99 die '-[eE]GND[=]* not allowed' if $v eq '*' && length $d;
100 $d= $output_layer if !length $d;
103 $c= '=' if !length $c;
104 if (length $v && $v ne '*') {
105 die '-[eE]GN[D]CCV not allowed' if length $c > 1;
108 if ($c =~ m/^[-+]/) {
109 die '-[eE]GN+/-* not allowed' if $v eq '*';
110 $sense= ($&.'1') + 0;
111 $limit= ($sense * $d) + length($c) - 1;
113 ($output_layer eq '*' ? $d
114 : $_[0]) * $sense >= $limit
117 } elsif ($v eq '*') {
118 $lfn= sub { !$invert; };
120 $limit= length($c) - 1;
123 ($output_layer eq '*' ? 1
124 : abs($_[0] - $d) <= $limit)
128 #print STDERR "output layer $output_layer; asking re $_[0] rel $d lim $limit invert $invert result $lfn_result\n";
133 foreach $c (split //, $cc) {
135 die "bad -e option $c" unless defined $chdraw_emap{$c};
136 $ccc .= $chdraw_emap{$c};
138 die "bad -E option $c" unless $c =~ m/[$drawers]/i;
143 $eo->{LayerCheck}= $lfn;
144 $eo->{DrawMods}= $ccc;
145 #print STDERR "created eo $eo re $eo->{GlobRe} n=$n d=$d v=$v c=$c limit=$limit cc=$cc\n";
148 die "-S option must come right at the start and have numeric arg";
150 die "unknown option -$_";
155 our $ptscale= 72/25.4 / $scale;
158 our $psu_edgelw= 0.5;
159 our $psu_ticklw= 0.1;
160 our $psu_ticksperu= 1;
161 our $psu_ticklen= 5.0;
163 our $psu_sleeperlen= 17;
164 our $psu_sleeperlw= 15;
165 our $psu_raillw= 1.0;
166 our $psu_thinlw= 1.0;
169 $psu_subseglw{'e'}= 20.0;
170 $psu_subseglw{'m'}= 15.0;
171 $psu_subseglw{'q'}= 20.0;
173 our $lmu_segtxtoff= -8;
176 our $lmu_marktpt= 11;
177 our $lmu_txtboxtxty= $lmu_marktpt * 0.300;
178 our $lmu_txtboxh= $lmu_marktpt * 1.100;
179 our $lmu_txtboxpadx= $lmu_marktpt * 0.335;
180 our $lmu_txtboxoff= $lmu_marklw / 2;
181 our $lmu_txtboxlw= 1;
182 our $lmu_lenlabeloffctr= -$lmu_marklw * 1.0;
183 our $lmu_lenlabeloff= $lmu_marklw * 0.5;
185 our $olu_left= 10 * $scale;
186 our $olu_right= 217 * $scale - $olu_left;
187 our $olu_bottom= 25 * $scale;
188 our $olu_top= 270 * $scale - $olu_bottom;
191 our $olu_textheight= 15;
192 our $olu_textallowperc= $lmu_marktpt * 5.0/11;
194 our $pi= atan2(0,-1);
198 return 27 unless defined $radius;
199 $radius= abs($radius);
200 return ($radius >= 450 ? 33 :
201 $radius >= 400 ? 35 :
204 sub allwidth ($) { return allwidth2($_[0]) * 0.5; }
206 our $allwidthmax= allwidth(0);
207 our $allwidthmin= allwidth(undef);
210 # $ctx->{CmdLog}= undef } not in defobj
211 # $ctx->{CmdLog}[]= [ command args ] } in defobj
212 # $ctx->{Parent}= $parent_ctx or undef
213 # $ctx->{LocsMade}[]{Id}= $id
214 # $ctx->{LocsMade}[]{Neg}= 1 or 0
215 # $ctx->{Loc}{$id}{X}
216 # $ctx->{Loc}{$id}{Y}
217 # $ctx->{Loc}{$id}{A}
218 # $ctx->{Loc}{$id}{LayerKind}
219 # $ctx->{Trans}{X} # transformation. is ev representing
220 # $ctx->{Trans}{Y} # new origin. (is applied at _input_
221 # $ctx->{Trans}{A} # not at plot-time)
222 # $ctx->{Trans}{R} # but multiply all y coords by this!
223 # $ctx->{Draw} # sequence of one or more chrs from uc $drawers
224 # # possibly including X meaning never draw
225 # # anything now (eg in defobj)
226 # $ctx->{DrawMap} # =$fn s.t.
227 # # &$fn($drawchrs_spec_by_layer_cmdline)
228 # # = $drawchrs_we_should_use_due_to_obj_etc
229 # $ctx->{SegName} # initial segment name (at start of object or file)
230 # # or nonexistent if in object in unknown segment
231 # # may have leading `-'
232 # $ctx->{SegMapN}{$s}= $o
233 # $ctx->{SegMapNM}{$s}= $o
234 # $ctx->{SavedSegment} # exists iff segment command used, is a $csss
235 # $ctx->{Layer}{Level}
236 # $ctx->{Layer}{Kind}
240 # $objs{$id}{Part} # 1 iff object is a part
242 # $eopts[]{GlobRe} # regexp for K
243 # $eopts[]{LayerCheck} # =$fn where &$fn($l) is true iff layer matches
244 # $eopts[]{DrawMods} # modifier chars for drawing
246 # @segments= ( $csss0, $dist0, $csss1, $dist1, ..., $csssn )
247 # # here each csss may have preceding `-'
249 # $subsegcmap{$csss} = "$green $blue"
250 # # $csss is canonical subseg spec; always has '/'
251 # $segcmap{$bareseg} = "$postscript"
253 # $seggraphends{"$bareseg"}[]{X}
254 # $seggraphends{"$bareseg"}[]{Y}
255 # $seggraphends{"$bareseg"}[]{A}
256 # $seggraphends{"-$bareseg"}[]...
266 our @al; # current cmd
271 our $param; # for parametric_segment
275 # Operate on Enhanced Vectors which are a location (coordinates) and a
276 # direction at that location. Representation is a hash with members X
277 # Y and A (angle of the direction in radians, anticlockwise from
278 # East). May be absolute, or interpreted as relative, according to
281 # Each function's first argument is a hashref whose X Y A members will
282 # be created or overwritten; this hashref will be returned (so you can
283 # use it `functionally' by passing {}). The other arguments may be ev
284 # hashrefs, or other info. The results are in general undefined if
285 # one of the arguments is the same hash as the result.
287 sub ev_byang ($$;$) {
288 # ev_byang(R, ANG,[LEN])
289 # result is evec LEN (default=1.0) from origin pointing in direction ANG
290 my ($res,$ang,$len)=@_;
291 $len=1.0 unless defined $len;
292 $res->{X}= $len * cos($ang);
293 $res->{Y}= $len * sin($ang);
297 sub ev_compose ($$$) {
298 # ev_compose(SUM_R, A,B);
299 # appends B to A, result is end of new B
300 # (B's X is forwards from end of A, Y is translating left from end of A)
301 # A may have a member R, which if provided then it should be 1.0 or -1.0,
302 # and B's Y and A will be multiplied by R first (ie, we can reflect);
303 my ($sum,$a,$b) = @_;
305 $r= defined $a->{R} ? $a->{R} : 1.0;
306 $sum->{X}= $a->{X} + $b->{X} * cos($a->{A}) - $r * $b->{Y} * sin($a->{A});
307 $sum->{Y}= $a->{Y} + $r * $b->{Y} * cos($a->{A}) + $b->{X} * sin($a->{A});
308 $sum->{A}= $a->{A} + $r * $b->{A};
311 sub ev_decompose ($$$) {
312 # ev_decompose(B_R, A,SUM)
313 # computes B_R s.t. ev_compose({}, A, B_R) gives SUM
316 $r= defined $a->{R} ? $a->{R} : 1.0;
317 $brx= $sum->{X} - $a->{X};
318 $bry= $r * ($sum->{Y} - $a->{Y});
319 $b->{X}= $brx * cos($a->{A}) + $bry * sin($a->{A});
320 $b->{Y}= $bry * cos($a->{A}) - $brx * sin($a->{A});
321 $b->{A}= $r * ($sum->{A} - $a->{A});
324 sub ev_lincomb ($$$$) {
325 # ev_linkcomb(RES,A,B,P)
326 # gives P*A + (1-P)*B
327 my ($r,$a,$b,$p) = @_;
329 map { $r->{$_} = $q * $a->{$_} + $p * $b->{$_} } qw(X Y A);
332 sub a_normalise ($$) {
334 # adds or subtracts 2*$pi to/from A until it is in [ Z , Z+2*$pi >
337 $r= $z + fmod($a - $z, 2.0*$pi);
338 $r += 2*$pi if $r < $z;
341 sub ev_bearing ($$) {
343 # returns bearing of B from A
344 # value returned is in [ A->{A}, A->{A} + 2*$pi >
345 # A->{A} and B->{A} are otherwise ignored
348 $r= atan2($b->{Y} - $a->{Y},
350 $r= a_normalise($r,$a->{A});
354 sub v_rotateright ($) {
356 # returns image of A rotated 90 deg clockwise
358 return { X => $a->{Y}, Y => -$a->{X} };
360 sub v_dotproduct ($$) {
363 return $a->{X} * $b->{X} + $a->{Y} * $b->{Y};
365 sub v_scalarmult ($$) {
367 # multiplies V by scalar S and returns product
369 return { X => $s * $v->{X}, Y => $s * $v->{Y} };
373 # vector sum of all inputs
375 #print STDERR "add ".join('|',keys %{$i[0]}),"<\n";
376 #map { print STDERR " ".join('|',keys %{$_}),"<\n"; } @i;
378 $r= { X => 0.0, Y => 0.0 };
379 foreach $i (@i) { $r->{X} += $i->{X}; $r->{Y} += $i->{Y}; }
384 #print STDERR "mean ".join('|',keys %{$i[0]}),"<\n";
385 #map { print STDERR " ".join('|',keys %{$_}),"<\n"; } @i;
386 my ($r) = v_add($i[0],@i[1..$#i]);
391 sub v_subtract ($$) {
393 # returns vector from A to B, ie B - A
395 return { X => $b->{X} - $a->{X},
396 Y => $b->{Y} - $a->{Y} };
402 my ($x,$y) = ($v->{X}, $v->{Y});
403 return sqrt($x*$x + $y*$y);
407 # returns distance from A to B
408 return v_len(v_subtract($_[0],$_[1]));
413 $$limr= $now unless defined $$limr && $$limr <= $now;
417 $$limr= $now unless defined $$limr && $$limr >= $now;
421 my ($converter,$defaulter)=@_;
423 return &$defaulter unless @al;
425 $v= &$converter($spec);
426 dv('canf ','$spec',$spec, '$v',$v);
429 sub can ($) { my ($c)=@_; canf($c, sub { die "too few args"; }); }
430 sub cano ($$) { my ($c,$def)=@_; canf($c, sub { return $def }); }
432 sub signum ($) { return ($_[0] > 0) - ($_[0] < 0); }
436 my ($min_x, $max_x, $min_y, $max_y);
438 foreach $loc (values %$objhash) {
439 upd_min(\$min_x, $loc->{X} - abs($allwidthmax * sin($loc->{A})));
440 upd_max(\$max_x, $loc->{X} + abs($allwidthmax * sin($loc->{A})));
441 upd_min(\$min_y, $loc->{Y} - abs($allwidthmax * cos($loc->{A})));
442 upd_max(\$max_y, $loc->{Y} + abs($allwidthmax * cos($loc->{A})));
444 return ($min_x, $max_x, $min_y, $max_y);
447 our %units_len= qw(- mm mm 1 cm 10 m 1000);
448 our %units_ang= qw(- d r 1); $units_ang{'d'}= 2*$pi / 360;
450 sub cva_len ($) { my ($sp)=@_; cva_units($sp,\%units_len); }
451 sub cva_identity ($) { my ($sp)=@_; $sp; }
452 sub cva_ang ($) { my ($sp)=@_; cva_units($sp,\%units_ang); }
453 sub cva_absang ($) { input_absang(cva_ang($_[0])) }
457 $sp =~ m/^([-0-9eE.]*[0-9.])([A-Za-z]*)$/
458 or die "lexically invalid quantity";
460 $u=$ua->{'-'} unless length $u;
461 defined $ua->{$u} or die "unknown unit $u";
463 print DEBUG "cva_units($sp,)=$r ($n $u $ua->{$u})\n";
468 die "invalid id" unless $sp =~ m/^[a-z][_0-9A-Za-z]*$/;
473 my ($id,$r,$d,$k,$neg,$na,$obj_id,$vflip,$locs);
474 if ($sp =~ s/^(\^?)(\w+)\!//) {
477 die "invalid obj $obj_id in loc" unless exists $objs{$obj_id};
478 $locs= $objs{$obj_id}{Loc};
483 $neg= $sp =~ s/^\-//;
485 die "unknown $id" unless defined $locs->{$id};
488 foreach $k (sort keys %$r) { $d .= " $k=$r->{$k}"; }
489 printf DEBUG "%s\n", $d;
491 $r= { X => $r->{X}, Y => -$r->{Y}, A => -$r->{A} };
495 $na= a_normalise($na,0);
496 $r= { X => $r->{X}, Y => $r->{Y}, A => $na };
503 $neg = $sp =~ s/^\-//;
505 die "duplicate $id" if exists $ctx->{Loc}{$id};
506 $ctx->{Loc}{$id}{LayerKind}= $ctx->{Layer}{Kind};
507 push @{ $ctx->{LocsMade} }, {
511 return $ctx->{Loc}{$id};
513 sub cva_cmd ($) { return cva_idstr($_[0]); }
516 return $sp if grep { $_ eq $sp } @$el;
517 die "invalid option (permitted: @$el)";
519 sub cvam_enum { my (@e) = @_; return sub { cva__enum($_[0],\@e); }; }
523 $nl= can(\&cva_idnew);
524 $i->{X}= can(\&cva_len);
525 $i->{Y}= can(\&cva_len);
526 $i->{A}= can(\&cva_ang);
527 ev_compose($nl, $ctx->{Trans}, $i);
530 my ($from,$to,$len,$right,$turn);
531 $from= can(\&cva_idex);
532 $to= can(\&cva_idnew);
533 $len= cano(\&cva_len,0);
534 $right= cano(\&cva_len,0) * $ctx->{Trans}{R};
535 $turn= cano(\&cva_ang, 0) * $ctx->{Trans}{R};
536 my ($u)= ev_compose({}, $from, { X => $len, Y => -$right, A => 0 });
537 ev_compose($to, $u, { X => 0, Y => 0, A => $turn });
542 $pfx . ($pfx =~ m/\}$|\]$/ ? '' : '->');
546 return 'undef' if !defined $v;
547 return $v if $v !~ m/\W/ && $v =~ m/[A-Z]/ && $v =~ m/^[a-z_]/i;
548 return $v if $v =~ m/^[0-9.]+/;
549 $v =~ s/[\\\']/\\$&/g;
553 sub dv1_kind ($$$$$$$) {
554 my ($pfx,$expr,$ref,$ref_exp,$ixfmt,$ixesfn,$ixmapfn) = @_;
556 return 0 if $ref ne $ref_exp;
558 foreach $ix (&$ixesfn) {
560 my ($v)= &$ixmapfn($ix);
561 #print STDERR "dv1_kind($pfx,$expr,$ref,$ref_exp,$ixmapfn) ix=$ix v=$v\n";
562 dv1($pfx,$expr.sprintf($ixfmt,dv__evr($ix)),$v);
565 printf DEBUG "%s%s= $ixfmt\n", $pfx, $expr, ' ';
570 return 0 unless $debug;
571 my ($pfx,$expr,$v) = @_;
574 #print STDERR "dv1 >$pfx|$ref<\n";
576 printf DEBUG "%s%s= %s\n", $pfx,$expr, dv__evr($v);
578 } elsif ($ref eq 'SCALAR') {
579 dv1($pfx, ($expr =~ m/^\$/ ? "\$$expr" : '${'.$expr.'}'), $$v);
582 $expr.='->' unless $expr =~ m/\]$|\}$/;
583 return if dv1_kind($pfx,$expr,$ref,'ARRAY','[%s]',
584 sub { ($[ .. $#$v) },
585 sub { $v->[$_[0]] });
586 return if dv1_kind($pfx,$expr,$ref,'HASH','{%s}',
587 sub { sort keys %$v },
588 sub { $v->{$_[0]} });
589 printf DEBUG "%s%s is %s\n", $pfx, $expr, $ref;
601 sub o ($) { $o .= $_[0]; }
602 sub ol ($) { $ol .= $_[0]; }
604 return if $subsegcmapreq;
606 print $o, $ol, " showpage\n"
613 sub o_path_begin () {
615 $o_path_verb= 'moveto';
617 sub o_path_point ($) {
619 o(" $pt $o_path_verb\n");
620 $o_path_verb= 'lineto';
622 sub o_path_stroke ($) {
624 o(" $width setlinewidth stroke\n");
626 sub o_path_strokeonly () {
630 sub o_transform ($) {
633 $ad= ang2deg($pt->{A});
635 " $pt->{X} $pt->{Y} translate\n".
640 my ($a,$b,$width)=@_;
644 o_path_stroke($width);
647 sub current_draw () {
649 $r= $ctx->{Draw} =~ m/X/ ? '' : $ctx->{Draw};
653 sub psu_coords ($$$) {
654 my ($ends,$inunit,$across)=@_;
655 # $ends->[0]{X} etc.; $inunit 0 to 1 (but go to 1.5);
656 # $across in mm, +ve to right.
657 my (%ea_zo, $zo, $prop);
658 $ea_zo{X}=$ea_zo{Y}=0;
659 foreach $zo (qw(0 1)) {
660 $prop= $zo ? $inunit : (1.0 - $inunit);
661 $ea_zo{X} += $prop * ($ends->[$zo]{X} - $across * sin($ends->[0]{A}));
662 $ea_zo{Y} += $prop * ($ends->[$zo]{Y} + $across * cos($ends->[0]{A}));
664 # dv("psu_coords ", '$ends',$ends, '$inunit',$inunit, '$across',$across,
665 # '\\%ea_zo', \%ea_zo);
666 return $ea_zo{X}." ".$ea_zo{Y};
669 sub parametric__o_pt ($) {
671 o_path_point("$pt->{X} $pt->{Y}");
674 our $segused_incurrent;
675 our $segused_currentpt;
676 our $segmentpart_counter=0;
677 our $segused_restorecounter;
679 sub segment_used__print ($) {
681 if ($segused_incurrent > 0 && $segused_restorecounter==1) {
683 $segmentpart_counter++." ".
684 $ctx->{Layer}{Level}.$ctx->{Layer}{Kind}." ".
686 $segused_incurrent." ".
687 loc2dbg($segused_currentpt)." ".
690 $segused_incurrent= undef;
691 $segused_currentpt= undef;
694 sub segment_used__len ($$) {
696 $segused_incurrent += $used;
698 return if @segments < 3;
699 $segments[1] -= $used;
700 return if $segments[1] > 0;
702 segment_used__print($pt);
703 segment_used_begin($pt);
705 @segments= @segments[2..$#segments];
706 o("% segments @segments\n");
709 sub segment_state_save () {
710 return [ 0, $segused_incurrent, $segused_currentpt,
711 $segmentpart_counter, @segments ];
713 sub segment_state_restore ($) {
715 ($segused_restorecounter, $segused_incurrent, $segused_currentpt,
716 $segmentpart_counter, @segments) = @$r;
720 sub segment__check_graphends () {
721 my ($bare,$ge,$i,$key);
723 $segments[0] =~ m/^\-?(\w+)/ or return;
725 foreach $i (qw(0 1)) {
726 $key= ('', '-')[$i].$bare;
727 $ge= $seggraphends{$key};
728 defined $ge or return;
729 #print STDERR "$key @$ge\n";
730 #map { print STDERR " ".join('|',keys %{$_}),"<\n"; } @$ge;
731 $seggraphend[$i]= v_mean(@$ge);
732 #print STDERR "SGE $i $seggraphend[$i]{X} $seggraphend[$i]{Y}\n";
736 sub segment_used_begin ($) {
737 $segused_incurrent= 0;
738 $segused_currentpt= $_[0];
739 segment__check_graphends();
741 sub segment_used_middle ($$) {
743 segment_used__len($used,$pt);
744 segment__check_graphends();
746 sub segment_used_end ($$) {
748 segment_used__len($used,$pt);
749 segment_used__print($pt);
751 sub parametric_segment ($$$$$) {
752 my ($p0,$p1,$lenperp,$minradius,$calcfn) = @_;
753 # makes $param (global) go from $p0 to $p1 ($p1>$p0)
754 # $lenperp is the length of one unit p, ie the curve
755 # must have a uniform `density' in parameter space
756 # $calcfn is invoked with $param set and should return a loc
757 # (ie, ref to X =>, Y =>, A =>).
758 my ($pa,$pb,@ends,$side,$ppu,$e,$v,$tick,$draw,$allwidth,%seglabel);
759 return unless $ctx->{Draw} =~ m/[ARSCGQE]/;
760 $ppu= $psu_ulen/$lenperp;
761 $allwidth= allwidth($minradius);
762 my ($railctr)=($psu_gauge + $psu_raillw)*0.5;
763 my ($tickend)=($allwidth - $psu_ticklen);
764 my ($tickpitch)=($psu_ulen / $psu_ticksperu);
765 my ($sleeperctr)=($psu_ulen*0.5);
766 my ($sleeperend)=($psu_sleeperlen*0.5);
767 print DEBUG "ps $p0 $p1 $lenperp ($ppu)\n";
768 $draw= current_draw();
769 if ($draw =~ m/[QGE]/) {
770 my ($pt,$going,$red,$csegbare,$movfeat,$movstroke);
771 my ($used_last,$me,$segsave,$diff);
773 $segsave= segment_state_save();
774 foreach $me ($draw =~ m/Q/ ? qw(q) : qw(e m)) {
775 segment_state_restore($segsave);
777 o("% segments @segments\n");
780 segment_used_begin($pt);
782 $movstroke= " cmapreq-stroke\n";
783 $csegbare= $segments[0];
784 $csegbare =~ s/^\-//;
785 if ($subsegcmapreq) {
786 if (!exists $subsegcmap{$csegbare}) {
787 print "$csegbare\n" or die $!;
788 $subsegcmap{$csegbare}++;
792 $csegbare =~ m,^[^/]*,;
793 #print STDERR "looking for \`$&' $me\n";
794 $movstroke= $segcmap{$&};
795 $movstroke= "% no-colour "
796 unless defined $movstroke;
797 } elsif ($draw =~ m/G/) {
798 $movfeat= $csegbare =~ s,(/\D+)(\d+)$,$1, ? $2 : 'f';
799 die "unknown subsegment colour for $csegbare\n"
800 unless exists $subsegcmap{$csegbare};
801 $red= $pt->{A} / (2*$pi);
802 $red *= $subsegcmapangscale;
803 $red += $subsegcmapangscale*2;
804 $red += $subsegcmapangscale/2
805 if $segments[0] =~ m/^\-/;
806 $red %= $subsegcmapangscale;
807 $red += $subsegcmapangscale if $me eq 'e';
808 $red= sprintf("%f", $red / 255.0);
809 $movstroke= " $red $subsegcmap{$csegbare}".
811 if ($subsegmovfeatpos ne $movfeat ||
812 ($me eq 'e' && $csegbare =~ m,^/,)) {
813 $movstroke= "% no-stroke ";
816 $movstroke= "!! seglabels-only ";
819 " $psu_subseglw{$me} setlinewidth stroke\n";
821 if ($draw =~ m/[QG]/) {
823 parametric__o_pt($pt);
828 if ($draw =~ m/E/ && @seggraphend==2) {
829 $diff= v_len(v_subtract($pt, $seggraphend[0])) -
830 v_len(v_subtract($pt, $seggraphend[1]));
831 if (abs($diff) < $psu_ulen*3) {
832 $segments[0] =~ m/^(\-?)(\w+)/;
833 $seglabel{$2}{X}= $pt->{X};
834 $seglabel{$2}{Y}= $pt->{Y};
835 $seglabel{$2}{A}= $pt->{A};
836 $seglabel{$2}{A} += $pi if length($1);
839 segment_used_middle($psu_ulen,$pt);
840 if ($draw =~ m/[QG]/) {
841 parametric__o_pt($pt);
845 $used_last= $p1-($param-$ppu);
848 segment_used_end($used_last * $lenperp, $pt);
849 parametric__o_pt($pt);
856 o(" $psu_thinlw setlinewidth\n");
858 for ($param=$p0; $param<$p1; $param += $ppu) {
859 parametric__o_pt(&$calcfn);
862 parametric__o_pt(&$calcfn);
867 foreach $seg (keys %seglabel) {
868 $pt= $seglabel{$seg};
871 ol(" /s ($seg) def\n".
874 " s stringwidth pop -0.5 mul $lmu_segtxtoff moveto\n".
879 if ($draw =~ m/[ARS]/) { for ($pa= $p0; $pa<$p1; $pa=$pb) {
881 $param= $pa; $ends[0]= @ends ? $ends[1] : &$calcfn;
882 $param= $pb; $ends[1]= &$calcfn;
883 #print DEBUG "pa $pa $ends[0]{X} $ends[0]{Y} $ends[0]{A}\n";
884 #print DEBUG "pb $pb $ends[1]{X} $ends[1]{Y} $ends[1]{A}\n";
885 $e= $pb<=$p1 ? 1.0 : ($p1-$pa)/$ppu;
888 o_path_point(psu_coords(\@ends,0,-$allwidth));
889 o_path_point(psu_coords(\@ends,0,$allwidth));
890 o_path_point(psu_coords(\@ends,$e,$allwidth));
891 o_path_point(psu_coords(\@ends,$e,-$allwidth));
892 o(" closepath clip\n");
893 foreach $side qw(-1 1) {
895 o_line(psu_coords(\@ends,0,$side*$railctr),
896 psu_coords(\@ends,1.5,$side*$railctr),
901 o_line(psu_coords(\@ends,$sleeperctr,-$sleeperend),
902 psu_coords(\@ends,$sleeperctr,+$sleeperend),
907 foreach $side qw(-1 1) {
908 o_line(psu_coords(\@ends,0,$side*$allwidth),
909 psu_coords(\@ends,1.5,$side*$allwidth),
911 for ($tick=0; $tick<1.5; $tick+=$tickpitch/$psu_ulen) {
912 o_line(psu_coords(\@ends,$tick,$side*$allwidth),
913 psu_coords(\@ends,$tick,$side*$tickend),
922 $param= ($p0+$p1)*0.5;
924 $len= sprintf "%.0f", $lenperp * abs($p1-$p0);
925 $off= $draw =~ m/C/ ? $lmu_lenlabeloff : $lmu_lenlabeloffctr;
936 my ($to, $ctr,$from, $radius,$delta) = @_;
937 # does parametric_segment to draw an arc centred on $ctr
938 # ($ctr->{A} ignored)
939 # from $from with radius $radius (this must be consistent!)
940 # and directionally-subtending an angle $delta.
941 # sets $to->... to be the other end, and returns $to
943 $to->{A}= $beta= $from->{A} + $delta;
944 $to->{X}= $ctr->{X} - $radius * sin($beta);
945 $to->{Y}= $ctr->{Y} + $radius * cos($beta);
946 return if abs($delta*$radius) < 1e-9;
947 parametric_segment(0.0,1.0, abs($radius*$delta), $radius, sub {
948 my ($beta) = $from->{A} + $delta * $param;
949 return { X => $ctr->{X} - $radius * sin($beta),
950 Y => $ctr->{Y} + $radius * cos($beta),
955 # joins_xxx all take $results, $from, $to, $minradius
956 # where $results->[]{Path}{K} etc. and $results->[]{SolKinds}[]
958 sub joins_twoarcs ($$$$) {
959 my ($results, $from,$to,$minradius) = @_;
960 # two circular arcs of equal maximum possible radius
961 # algorithm courtesy of Simon Tatham (`Railway problem',
962 # pers.comm. to ijackson@chiark 23.1.2004)
963 my ($sigma,$distfact, $theta,$phi, $a,$b,$c,$d, $m,$r, $radius);
964 my ($cvec,$cfrom,$cto,$midpt, $delta1,$delta2, $path,$reverse);
965 $sigma= ev_bearing($from,$to);
966 $distfact= v_dist($from,$to);
967 $theta= 0.5 * $pi - ($from->{A} - $sigma);
968 $phi= 0.5 * $pi - ($to->{A} + $pi - $sigma);
969 $a= 2 * (1 + cos($theta - $phi));
970 $b= 2 * (cos($theta) - cos($phi));
972 $d= sqrt($b*$b - 4*$a*$c);
973 o("% twoarcs theta=".ang2deg($theta)." phi=".ang2deg($phi).
974 " ${a}r^2 + ${b}r + ${c} = 0\n");
975 foreach $m (qw(-1 1)) {
977 o("% twoarcs $m insoluble\n");
980 $r= -0.5 * (-$b + $m*$d) / $a;
981 $radius= -$r * $distfact;
982 o("% twoarcs $m radius $radius ");
983 if (abs($radius) < $minradius) { o("too-small\n"); next; }
984 $cfrom= ev_compose({}, $from, { X=>0, Y=>-$radius, A=>-0.5*$pi });
985 $cto= ev_compose({}, $to, { X=>0, Y=> $radius, A=> 0.5*$pi });
986 $midpt= ev_lincomb({}, $cfrom, $cto, 0.5);
987 $reverse= signum($r);
992 $delta1= ev_bearing($cfrom, $midpt) - $cfrom->{A};
993 $delta2= ev_bearing($cto, $midpt) - $cto->{A};
994 o("ok deltas ".ang2deg($delta1)." ".ang2deg($delta2)."\n");
1000 $path= [{ T=>Arc, F=>$from, C=>$cfrom, R=> $radius, D=>$delta1 },
1001 { T=>Arc, F=>$to, C=>$cto, R=>-$radius, D=>$delta2 }];
1002 push @$results, { Path => $path,
1003 SolKinds => [ 'twoarcs', 'cross' ] };
1007 sub joins_arcsline ($$$$) {
1008 my ($results, $from,$to,$minradius) = @_;
1009 # two circular arcs of specified radius
1010 # with an intervening straight
1011 my ($lr,$inv, $c,$d,$alpha,$t,$k,$l,$rpmsina,$rcosa,$linelen, $path);
1012 if ($minradius<=1e-6) { o("% arcsline no-radius\n"); return; }
1013 foreach $lr (qw(-1 +1)) {
1014 foreach $inv (qw(-1 +1)) {
1015 $c=ev_compose({},$from,{X=>0,Y=>-$lr*$minradius, A=>0 });
1016 $d=ev_compose({},$to,{X=>0, Y=>-$inv*$lr*$minradius, A=>$pi });
1018 o("% arcsline $lr $inv t=$t ");
1019 if ($t < 1e-6) { o("concentric"); next; }
1020 $c->{A}= $d->{A}= ev_bearing($c,$d);
1021 o("bearing ".ang2deg($c->{A}));
1024 $k= ev_compose({}, $c, { X=>0, Y=>$lr*$minradius, A=>0 });
1025 $l= ev_compose({}, $d, { X=>0, Y=>$lr*$minradius, A=>0 });
1028 my ($cosalpha) = 2.0 * $minradius / $t;
1029 if ($cosalpha > (1.0 - 1e-6)) { o(" too-close\n"); next; }
1030 $alpha= acos($cosalpha);
1031 $rpmsina= $lr * $minradius * sin($alpha);
1032 $rcosa= $minradius * $cosalpha;
1033 $k= ev_compose({}, $c, { X=>$rcosa, Y=>$rpmsina, A=>0 });
1034 $l= ev_compose({}, $d, { X=>-$rcosa, Y=>-$rpmsina, A=>0 });
1035 $k->{A}= $l->{A}= ev_bearing($k,$l);
1036 o(" alpha=".ang2deg($alpha)." kl^=".ang2deg($k->{A})."\n");
1037 $linelen= v_dist($k,$l);
1039 $path= [{ T => Arc, F => $from, C => $c,
1041 D => -$lr * a_normalise
1042 ($lr * ($from->{A} - $k->{A}), 0) },
1043 { T => Line, A => $k, B => $l, L => $linelen },
1044 { T => Arc, F => $l, C => $d,
1045 R => $inv*$lr*$minradius,
1046 D => -$lr*$inv * a_normalise
1047 (-$lr*$inv * ($to->{A} - $l->{A}), 0) }];
1050 SolKinds => [ 'arcsline', ($inv<0 ? 'cross' : 'loop') ] };
1055 sub joins_arcline ($$$$) {
1056 my ($results, $from,$to,$minradius) = @_;
1057 # one circular arc and a straight line
1058 my ($swap,$echoice,$path, $ap,$bp,$av,$bv, $e,$f, $ae,$af,$afae);
1059 my ($dak,$ak,$kj,$k,$j,$aja,$jl,$l,$jc,$lc,$c,$rj,$rb);
1060 foreach $swap (qw(-1 +1)) {
1061 foreach $echoice (qw(0 1)) {
1062 $ap= $from; $bp= { %$to }; $bp->{A} += $pi;
1063 ($ap,$bp)= ($bp,$ap) if $swap<0;
1064 $av= ev_byang({}, $ap->{A});
1065 $bv= ev_byang({}, $bp->{A});
1066 $e= ev_byang({}, 0.5 * ($ap->{A} + $bp->{A} + $echoice * $pi));
1067 $f= v_rotateright($e);
1068 o("% arcline $swap $echoice e ".loc2dbg($e)."\n");
1069 $ae= v_dotproduct($av,$e);
1070 $af= v_dotproduct($av,$f);
1071 o("% arcline $swap $echoice a.e=$ae a.f=$af ");
1072 if (abs($ae) < 1e-6) { o(" singular\n"); next; }
1074 o("a.f/a.e=$afae\n");
1075 $dak= v_dotproduct(v_subtract($ap,$bp), $e);
1076 $ak= v_scalarmult($dak, $e);
1077 $kj= v_scalarmult($dak * $afae, $f);
1078 $k= v_add($ap, $ak);
1080 $aja= v_dotproduct(v_subtract($ap,$j), $av);
1081 o("% arcline $swap $echoice d_ak=$dak aj.a=$aja ");
1082 if ($aja < 0) { o(" backwards aj\n"); next; }
1083 $jl= v_scalarmult(0.5, v_subtract($j, $bp));
1084 $lc= v_scalarmult(-v_dotproduct($jl, $f) * $afae, $e);
1087 $rj= v_dotproduct(v_subtract($j,$c), v_rotateright($av));
1088 $rb= v_dotproduct(v_subtract($c,$bp), v_rotateright($bv));
1089 o("r_j=$rj r_b=$rb ");
1090 if ($rj * $rb < 0) { o(" backwards b\n"); next; }
1091 if (abs($rj) < $minradius) { o(" too-small\n"); next; }
1095 $path= [{ T => Line, A => $ap, B => $j, L => $aja },
1096 { T => Arc, F => $j, C => $c, R => $rj,
1097 D => -signum($rj) * a_normalise
1098 (-signum($rj) * ($bp->{A} + $pi - $j->{A}), 0) }];
1099 $path= [ reverse @$path ] if $swap<0;
1100 push @$results, { Path => $path, SolKinds => [ 'arcline' ] };
1106 my ($from,$to,$minradius);
1107 my (@results,$result);
1108 my ($path,$segment,$bestpath,$len,$scores,$bestscores,@bends,$skl);
1109 my ($crit,$cs,$i,$cmp);
1110 $from= can(\&cva_idex);
1111 $to= can(\&cva_idex);
1112 $minradius= can(\&cva_len);
1113 o("% join ".loc2dbg($from)."..".loc2dbg($to)." $minradius\n");
1114 joins_twoarcs(\@results, $from,$to,$minradius);
1115 joins_arcsline(\@results, $from,$to,$minradius);
1116 joins_arcline(\@results, $from,$to,$minradius);
1117 foreach $result (@results) {
1118 $path= $result->{Path};
1119 $skl= $result->{SolKinds};
1120 o("% possible path @$skl $path\n");
1123 foreach $segment (@$path) {
1124 if ($segment->{T} eq Arc) {
1125 o("% Arc C ".loc2dbg($segment->{C}).
1126 " R $segment->{R} D ".ang2deg($segment->{D})."\n");
1127 $len += abs($segment->{R} * $segment->{D});
1128 push @bends, -abs($segment->{R}) * $segment->{D}; # right +ve
1129 } elsif ($segment->{T} eq Line) {
1130 o("% Line A ".loc2dbg($segment->{A}).
1131 " B ".loc2dbg($segment->{A})." L $segment->{L}\n");
1132 $len += abs($segment->{L});
1134 die "unknown segment $segment->{T}";
1137 o("% length $len bends @bends.\n");
1139 foreach $crit (@al, 'short') {
1140 if ($crit eq 'long') { $cs= $len; }
1141 elsif ($crit eq 'short') { $cs= -$len; }
1142 elsif ($crit =~ m/^(begin|end|)(left|right)$/) {
1143 if ($1 eq 'begin') { $cs= $bends[0]; }
1144 elsif ($1 eq 'end') { $cs= $bends[$#bends]; }
1145 else { $cs=0; map { $cs += $_ } @bends; }
1146 $cs= -$cs if $2 eq 'left';
1147 } elsif ($crit =~ m/^(\!?)(twoarcs|arcs?line|cross|loop)$/) {
1148 $cs= !!(grep { $2 eq $_ } @$skl) != ($1 eq '!');
1150 die "unknown sort criterion $crit";
1154 o("% scores @$scores\n");
1155 if (defined $bestpath) {
1156 for ($i=0,$cmp=0; !$cmp && $i<@$scores; $i++) {
1157 $cmp= $scores->[$i] <=> $bestscores->[$i];
1162 $bestscores= $scores;
1164 die "no solution" unless defined $bestpath;
1165 o("% chose path $bestpath @al\n");
1167 foreach $segment (@$bestpath) {
1168 if ($segment->{T} eq 'Arc') {
1169 arc({}, $segment->{C},$segment->{F},$segment->{R},$segment->{D});
1170 } elsif ($segment->{T} eq 'Line') {
1171 line($segment->{A}, $segment->{B}, $segment->{L});
1173 die "unknown segment";
1179 my ($from,$to,$len) = @_;
1181 ($from,$to,$len) = ($to,$from,-$len);
1183 parametric_segment(0.0, 1.0, $len + 1e-6, undef, sub {
1184 ev_lincomb({}, $from, $to, $param);
1189 my ($from,$to,$radius,$len,$upto,$ctr,$beta,$ang,$how,$sign_r);
1190 $from= can(\&cva_idex);
1191 $to= can(\&cva_idnew);
1192 printf DEBUG "from $from->{X} $from->{Y} $from->{A}\n";
1193 $how= can(cvam_enum(qw(len upto ang uptoang parallel)));
1194 if ($how eq 'len') { $len= can(\&cva_len); }
1195 elsif ($how =~ m/ang$/) { $ang= can(\&cva_ang); }
1196 elsif ($how eq 'parallel' || $how eq 'upto') { $upto= can(\&cva_idex); }
1197 $radius= cano(\&cva_len, 'Inf'); # +ve is right hand bend
1198 if ($radius eq 'Inf') {
1199 # print DEBUG "extend inf $len\n";
1200 if ($how eq 'upto') {
1201 $len= ($upto->{X} - $from->{X}) * cos($from->{A})
1202 + ($upto->{Y} - $from->{Y}) * sin($from->{A});
1203 } elsif ($how eq 'len') {
1205 die "len of straight spec by angle";
1207 printf DEBUG "len $len\n";
1208 $to->{X}= $from->{X} + $len * cos($from->{A});
1209 $to->{Y}= $from->{Y} + $len * sin($from->{A});
1210 $to->{A}= $from->{A};
1211 line($from,$to,$len);
1213 my ($sign_r, $sign_ang, $ctr, $beta_interval, $beta, $delta);
1214 print DEBUG "radius >$radius<\n";
1215 $radius *= $ctx->{Trans}{R};
1216 $sign_r= signum($radius);
1218 $ctr->{X}= $from->{X} + $radius * sin($from->{A});
1219 $ctr->{Y}= $from->{Y} - $radius * cos($from->{A});
1220 if ($how eq 'upto') {
1221 $beta= atan2(-$sign_r * ($upto->{X} - $ctr->{X}),
1222 $sign_r * ($upto->{Y} - $ctr->{Y}));
1223 $beta_interval= 1.0;
1224 } elsif ($how eq 'parallel') {
1226 $beta_interval= 1.0;
1227 } elsif ($how eq 'uptoang') {
1228 $beta= input_absang($ang);
1229 $beta_interval= 2.0;
1230 } elsif ($how eq 'len') {
1231 $sign_ang= signum($len);
1232 $beta= $from->{A} - $sign_r * $len / abs($radius);
1233 $beta_interval= 2.0;
1235 $sign_ang= signum($ang);
1236 $beta= $from->{A} - $sign_r * $ang;
1237 $beta_interval= 2.0;
1239 printf DEBUG "ctr->{Y}=$ctr->{Y} radius=$radius beta=$beta\n";
1240 $beta += $sign_ang * $sign_r * 4.0 * $pi;
1242 $delta= $beta - $from->{A};
1243 last if $sign_ang * $sign_r * $delta <= 0;
1244 $beta -= $sign_ang * $sign_r * $beta_interval * $pi;
1246 printf DEBUG "ctr->{Y}=$ctr->{Y} radius=$radius beta=$beta\n";
1247 arc($to, ,$ctr,$from, $radius,$delta);
1249 printf DEBUG "to $to->{X} $to->{Y} $to->{A}\n";
1254 return "$loc->{X} $loc->{Y} ".ang2deg($loc->{A});
1257 return $_[0] * 180 / $pi;
1259 sub input_absang ($) {
1260 return $_[0] * $ctx->{Trans}{R} + $ctx->{Trans}{A};
1262 sub input_abscoords ($$) {
1264 ($in->{X}, $in->{Y}) = @_;
1266 $out= ev_compose({}, $ctx->{Trans}, $in);
1267 return ($out->{X}, $out->{Y});
1271 my ($ctx_save) = @_;
1273 Trans => { X => 0.0, Y => 0.0, A => 0.0, R => 1.0 },
1275 DrawMap => sub { $_[0]; },
1279 if (defined $ctx_save) {
1280 %{ $ctx->{Layer} }= %{ $ctx_save->{Layer} };
1281 $ctx->{Parent}= $ctx_save;
1288 sub cmd_defobj { cmd__defobj(0); }
1289 sub cmd_defpart { cmd__defobj(1); }
1290 sub cmd__defobj ($) {
1293 $id= can(\&cva_idstr);
1294 die "nested defobj" if $defobj_save;
1295 die "repeated defobj" if exists $objs{$id};
1297 $defobj_ispart= $ispart;
1298 newctx($defobj_save);
1299 $ctx->{CmdLog}= [ ];
1300 $ctx->{InDefObj}= $id;
1301 $ctx->{Draw}= $defobj_save->{Draw}.'X';
1302 $ctx->{DrawMap}= sub { ''; };
1303 $ctx->{Layer}= { Level => 5, Kind => '' };
1308 $id= $ctx->{InDefObj};
1309 die "unmatched enddef" unless defined $id;
1310 foreach $bit (qw(CmdLog Loc)) {
1311 $objs{$id}{$bit}= $ctx->{$bit};
1313 $objs{$id}{Part}= $defobj_ispart;
1315 $defobj_save= undef;
1316 $defobj_ispart= undef;
1319 sub cmd__runobj ($) {
1323 dv("cmd__runobj $obj_id ",'$ctx',$ctx);
1324 foreach $c (@{ $objs{$obj_id}{CmdLog} }) {
1326 next if $al[0] eq 'enddef';
1331 sub cva_segment ($) {
1333 die "invalid segment" if $sp =~ m/\W/;
1337 sub cva_segment_n ($) {
1339 die "invalid segment" if $sp =~ m/[^-0-9A-Za-z_]/;
1343 sub cva_subsegspec ($) {
1345 die "invalid subsegment spec" unless
1346 $sp =~ m,^(\-?)([0-9A-Za-z_]*)(?:/(?:([A-Za-z_]+)(\d+))?)?$,;
1347 my ($sign,$segname,$movfeat,$movconf)=($1,$2,$3,$4);
1349 if (!exists $ctx->{SegName}) {
1355 $ctx->{SegName} =~ m/^\-?/ or die;
1357 $segname= $'.$segname;
1359 for ($map_ctx= $ctx;
1361 $map_ctx= $map_ctx->{Parent}) {
1362 if (defined $movfeat &&
1363 exists $map_ctx->{SegMapNM}{"$segname/$movfeat"}) {
1364 $movfeat= $map_ctx->{SegMapNM}{"$segname/$movfeat"};
1366 if (exists $map_ctx->{SegMapN}{$segname}) {
1367 $map_ctx->{SegMapN}{$segname} =~ m/^\-?/ or die;
1375 return $sign.$segname.'/'.
1376 (defined $movfeat ? sprintf "%s%d", $movfeat, $movconf : '');
1381 $ctx->{SavedSegment}= pop @segments
1382 unless exists $ctx->{SavedSegment};
1385 $csss= can(\&cva_subsegspec);
1386 $length= can(\&cva_len);
1387 push @segments, $csss, $length;
1389 $csss= can(\&cva_subsegspec);
1390 push @segments, $csss;
1395 $sp =~ m,^\w+(?:/[a-zA-Z_]+)?$,
1396 or die "invalid (sub)segment mapping S \`$sp'";
1402 $sp =~ m,^\-?\w+$, or die "invalid segment mapping N' \`$sp'";
1408 $sp =~ m,^[a-zA-Z_]+$, or die "invalid segment mapping M' \`$sp'";
1415 $s= can(\&cva_segmap_s);
1417 $ctx->{SegMapNM}{$s}= can(\&cva_segmap_m);
1419 $ctx->{SegMapN}{$s}= can(\&cva_segmap_n);
1426 $seg= can(\&cva_segment);
1427 $segcmap{$seg}= "@al";
1432 my ($from,$sp) = @_;
1433 $from= can(\&cva_idex);
1434 $sp= can(\&cva_segment_n);
1435 #print STDERR "setting $from ".join('|',keys %$from),"<\n";
1436 push @{ $seggraphends{$sp} }, $from;
1439 sub layer_draw ($$) {
1444 } elsif ($k eq 's') {
1446 } elsif ($k eq 'l') {
1451 foreach $eo (@eopts) {
1452 #print STDERR "$. layer $k$l eo $eo re $eo->{GlobRe} then $eo->{DrawMods} now $r\n";
1453 next unless $k =~ m/^$eo->{GlobRe}$/;
1454 #print STDERR "$. layer $k$l eo re $eo->{GlobRe} match\n";
1455 next unless &{ $eo->{LayerCheck} }($l);
1456 #print STDERR "$. layer $k$l eo re $eo->{GlobRe} checked\n";
1457 foreach $cc (split //, $eo->{DrawMods}) {
1459 $r .= $cc if $cc =~ m/[A-Z]/;
1462 #print STDERR "layer $k$l gives $r (before map)\n";
1463 $r= &{ $ctx->{DrawMap} }($r);
1469 $kl= can(\&cva_identity);
1470 $kl =~ m/^([A-Za-z_]*)(\d*|\=|\*)$/ or die "invalid layer spec";
1472 $l= $output_layer if $l eq '*';
1473 $l= $ctx->{Layer}{Level} if $l =~ m/^\=?$/;
1474 $ctx->{Layer}{Kind}= $k;
1475 $ctx->{Layer}{Level}= $l;
1476 $ctx->{Draw}= layer_draw($k,$l);
1479 sub cmd_part { cmd__obj(Part); }
1480 sub cmd_obj { cmd__obj(1); }
1481 sub cmd_objflip { cmd__obj(-1); }
1485 my ($obj_id, $ctx_save, $pfx, $actual, $formal_id, $formal, $formcv);
1486 my ($part_name, $ctx_inobj, $obj, $id, $newid, $newpt);
1488 $part_name= can(\&cva_idstr);
1489 $how= (@al && $al[0] =~ s/^\^//) ? -1 : +1;
1491 $obj_id= can(\&cva_idstr);
1492 if (defined $part_name) {
1493 $formal_id= can(\&cva_idstr);
1494 $actual= cano(\&cva_idex, undef);
1495 if (!defined $actual) {
1496 $actual= cva_idex("${part_name}_${formal_id}");
1499 $actual= can(\&cva_idex);
1500 $formal_id= can(\&cva_idstr);
1502 $obj= $objs{$obj_id};
1503 dv("cmd__obj ",'$obj',$obj);
1504 die "unknown obj $obj_id" unless $obj;
1505 $formal= $obj->{Loc}{$formal_id};
1506 die "unknown formal $formal_id" unless $formal;
1509 $how *= $ctx_save->{Trans}{R};
1510 $ctx->{Trans}{R}= $how;
1511 $ctx->{Trans}{A}= $actual->{A} - $formal->{A}/$how;
1512 $formcv= ev_compose({}, $ctx->{Trans},$formal);
1513 $ctx->{Trans}{X}= $actual->{X} - $formcv->{X};
1514 $ctx->{Trans}{Y}= $actual->{Y} - $formcv->{Y};
1515 if (defined $part_name) {
1516 $ctx->{InRunObj}= $ctx_save->{InRunObj}."${part_name}:";
1518 $ctx->{InRunObj}= $ctx_save->{InRunObj}."${obj_id}::";
1520 if ($segments[0] =~ m,(.*[^-]+)/,) {
1521 $ctx->{SegName}= $1;
1523 $ctx->{DrawMap}= sub {
1525 $i= &{ $ctx_save->{DrawMap} }($i);
1535 $ctx->{Draw}= &{ $ctx->{DrawMap} }($ctx_save->{Draw});
1536 cmd__runobj($obj_id);
1537 if (defined $part_name) {
1538 $pfx= $part_name.'_';
1540 if (@al && $al[0] eq '=') {
1541 $pfx= ''; shift @al;
1543 $pfx= cano(\&cva_idstr,undef);
1546 if (exists $ctx->{SavedSegment}) {
1547 @segments= ($ctx->{SavedSegment});
1552 foreach $id (keys %{ $ctx_inobj->{Loc} }) {
1553 next if $id eq $formal_id;
1555 next if exists $ctx_save->{Loc}{$newid};
1556 $newpt= cva_idnew($newid);
1557 %$newpt= %{ $ctx_inobj->{Loc}{$id} };
1560 if (defined $part_name) {
1561 my ($formalr_id, $actualr_id, $formalr, $actualr);
1563 die "part results come in pairs\n" unless @al>=2;
1564 ($formalr_id, $actualr_id, @al) = @al;
1565 if ($actualr_id =~ s/^\-//) {
1566 $formalr_id= "-$formalr_id";
1567 $formalr_id =~ s/^\-\-//;
1570 local ($ctx) = $ctx_inobj;
1571 $formalr= cva_idex($formalr_id);
1573 $actualr= cva_idnew($actualr_id);
1574 %$actualr= %$formalr;
1581 dv("cmd__do $ctx @al ",'$ctx',$ctx);
1582 $cmd= can(\&cva_cmd);
1583 my ($lm,$id,$loc,$io,$ad,$draw,$thendrawre);
1584 $io= defined $ctx->{InDefObj} ? "$ctx->{InDefObj}!" : $ctx->{InRunObj};
1585 o("%L cmd $io $cmd @al\n");
1586 $ctx->{LocsMade}= [ ];
1591 die "too many args" if @al;
1592 foreach $lm (@{ $ctx->{LocsMade} }) {
1594 $loc= $ctx->{Loc}{$id};
1595 $loc->{A} += $pi if $lm->{Neg};
1596 $ad= ang2deg($loc->{A});
1597 ol("%L point $io$id ".loc2dbg($loc)." ($lm->{Neg})\n");
1598 $draw= layer_draw($loc->{LayerKind}, $ctx->{Layer}{Level});
1599 if ($draw =~ m/[LM]/) {
1601 " $loc->{X} $loc->{Y} translate $ad rotate\n");
1602 if ($draw =~ m/M/) {
1603 ol(" 0 $allwidthmin newpath moveto\n".
1604 " 0 -$allwidthmin lineto\n".
1605 " $lmu_marklw setlinewidth stroke\n");
1607 if ($draw =~ m/L/) {
1608 ol(" /s ($id) def\n".
1610 " /sx5 s stringwidth pop\n".
1611 " 0.5 mul $lmu_txtboxpadx add def\n".
1612 " -90 rotate 0 $lmu_txtboxoff translate newpath\n".
1613 " sx5 neg 0 moveto\n".
1614 " sx5 neg $lmu_txtboxh lineto\n".
1615 " sx5 $lmu_txtboxh lineto\n".
1616 " sx5 0 lineto closepath\n".
1617 " gsave 1 setgray fill grestore\n".
1618 " $lmu_txtboxlw setlinewidth stroke\n".
1619 " sx5 neg $lmu_txtboxpadx add $lmu_txtboxtxty\n".
1620 " moveto s show\n");
1628 my ($vs, @lt, $inf, $strft);
1630 $vs= $1 if $vs =~ m/^\$Revision\: ([0-9.]+)\ \$$/;
1631 if (!defined $file_filename) {
1632 $inf= "$vs (unknown file: $file_lineno)";
1633 } elsif (!stat $file_filename ||
1634 !(@lt= localtime((stat _)[9]))) {
1635 $inf= "$file_filename ($1 $!)";
1637 $strft= strftime "%Y-%m-%d %H:%M:%S +%Z", @lt;
1638 $inf= "$file_filename ($1 $strft)";
1640 push @ident_strings, $inf;
1644 sub cmd_showlibrary {
1645 my ($obj_id, $y, $x, $ctx_save, $width, $height);
1646 my ($max_x, $min_x, $max_y, $min_y, $nxty, $obj, $loc, $pat, $got, $glob);
1648 $x=$olu_left; $y=$olu_bottom; undef $nxty;
1650 foreach $obj_id (sort keys %objs) {
1652 foreach $glob (@al) {
1654 $got= !($pat =~ s/^\!//);
1655 die "bad pat" if $pat =~ m/[^0-9a-zA-Z_*?]/;
1656 $pat =~ s/\*/\.*/g; $pat =~ s/\?/./g;
1657 last if $obj_id =~ m/^$pat$/;
1661 $obj= $objs{$obj_id};
1662 next unless $obj->{Part};
1663 ($min_x, $max_x, $min_y, $max_y) = bbox($obj->{Loc});
1667 $width= $max_x - $min_x;
1668 $height= $max_y - $min_y;
1669 if ($width < $height) {
1670 $ctx->{Trans}{A}= 0;
1671 $ctx->{Trans}{X}= $x - $min_x;
1672 $ctx->{Trans}{Y}= $y - $min_y + $olu_textheight;
1674 ($width,$height)=($height,$width);
1675 $ctx->{Trans}{A}= 0.5 * $pi;
1676 $ctx->{Trans}{X}= $x + $max_y;
1677 $ctx->{Trans}{Y}= $y - $min_x + $olu_textheight;
1679 $adj= length($obj_id) * $olu_textallowperc - $width;
1682 $ctx->{Trans}{X} += 0.5 * $adj;
1683 if ($x + $width > $olu_right && defined $nxty) {
1687 } elsif ($y + $height > $olu_top && $y > $olu_bottom) {
1689 $x= $olu_left; $y= $olu_bottom;
1696 $ctx->{InRunObj}= $ctx_save->{InRunObj}."${obj_id}//";
1697 $ctx->{Draw}= $ctx_save->{Draw};
1698 cmd__runobj($obj_id);
1700 " /s ($obj_id) def\n".
1702 ($x + 0.5*$width)." ".($y - $olu_textheight)." moveto\n".
1703 " s stringwidth pop -0.5 mul 0 rmoveto\n".
1704 " s show grestore\n");
1705 $x += $width + $olu_gap_x;
1706 upd_max(\$nxty, $y + $height + $olu_gap_y + $olu_textheight);
1717 " /lf /Courier-New findfont $lmu_marktpt scalefont def\n".
1718 " /sf /Courier-Bold findfont $lmu_segtpt scalefont def\n".
1719 " $ps_page_shift 0 translate 90 rotate\n".
1722 if ($page_x || $page_y) {
1723 o(" /Courier-New findfont 15 scalefont setfont\n".
1724 " 30 30 moveto (${page_x}x${page_y}) show\n");
1727 o(" -$ps_page_xmul $page_x mul -$ps_page_ymul $page_y mul translate\n".
1728 " $ptscale $ptscale scale\n");
1732 open DEBUG, ($debug ? ">&2" : ">/dev/null") or die $!;
1735 select(DEBUG); $|=1;
1736 select(STDOUT); $|=1;
1740 $ctx->{SegName}= '';
1747 if (m/^\#line (\d+)$/) { $file_lineno= $1; next; }
1748 if (m/^\#line (\d+) (.*)$/) {
1751 $file_filename =~ s/^\"(.*)\"$/$1/;
1755 chomp; s/^\s+//; s/\s+$//;
1756 @al= split /\s+/, $_;
1758 print DEBUG "=== @al\n";
1759 last if $al[0] eq 'eof';
1760 push @{ $ctx->{CmdLog} }, [ @al ] if exists $ctx->{CmdLog};
1765 my ($min_x, $max_x, $min_y, $max_y) = bbox($ctx->{Loc});
1767 if (defined $min_x) {
1768 $bboxstr= sprintf("width %.2d (%.2d..%2.d)\n".
1769 "height %.2d (%.2d..%2.d)\n",
1770 $max_x - $min_x, $min_x, $max_x,
1771 $max_y - $min_y, $min_y, $max_y);
1773 $bboxstr= "no locs, no bbox\n";
1775 if (!$quiet) { print STDERR $bboxstr; }
1776 $bboxstr =~ s/^/\%L bbox /mg;
1777 o($bboxstr) or die $!;
1780 my ($tick_x, $tick_y, $ticklen);
1783 " gsave 0.5 setgray 0.33 setlinewidth\n".
1785 " newpath moveto\n".
1786 " -%d 0 rmoveto %d 0 rlineto\n".
1787 " -%d -%d rmoveto 0 %d rlineto stroke\n".
1789 $ticklen, $ticklen*2, $ticklen, $ticklen, $ticklen*2);
1790 for ($tick_x= $min_x; $tick_x < $max_x; $tick_x += 150) {
1791 for ($tick_y= $min_y; $tick_y < $max_y; $tick_y += 150) {
1792 o(sprintf " %f %f regmark\n", $tick_x, $tick_y);
1801 if (@ident_strings) {
1803 $is= join('; ', @ident_strings);
1804 $is =~ s/[()\\]/\\$&/g;
1806 "/Courier-New findfont 6 scalefont setfont\n".