12 our $output_layer= '*';
14 our $ps_page_shift= 615;
15 our $ps_page_xmul= 765.4;
16 our $ps_page_ymul= 538.6;
20 our $drawers= 'arsclmno';
21 our %chdraw_emap= qw(A ARSc
34 while (@ARGV && $ARGV[0] =~ m/^\-/) {
35 last if $ARGV[0] eq '-';
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; }
47 ((?:[a-z]|\*|\?|\[[a-z][-a-z]*\])*?)
48 (\~?) (\d*) (\=*|\-+|\++) (\d*|\*)
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;
57 $c= '=' if !length $c;
58 if (length $v && $v ne '*') {
59 die '-[eE]GN[D]CCV not allowed' if length $c > 1;
63 die '-[eE]GN+/-* not allowed' if $v eq '*';
65 $limit= ($sense * $d) + length($c) - 1;
67 ($output_layer eq '*' ? $d
68 : $_[0]) * $sense >= $limit
72 $lfn= sub { !$invert; };
74 $limit= length($c) - 1;
77 ($output_layer eq '*' ? 1
78 : abs($_[0] - $d) <= $limit)
82 #print STDERR "output layer $output_layer; asking re $_[0] rel $d lim $limit invert $invert result $lfn_result\n";
87 foreach $c (split //, $cc) {
89 die "bad -e option $c" unless defined $chdraw_emap{$c};
90 $ccc .= $chdraw_emap{$c};
92 die "bad -E option $c" unless $c =~ m/[$drawers]/i;
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";
102 die "-S option must come right at the start and have numeric arg";
104 die "unknown option -$_";
109 our $ptscale= 72/25.4 / $scale;
112 our $psu_edgelw= 0.5;
113 our $psu_ticklw= 0.1;
114 our $psu_ticksperu= 1;
115 our $psu_ticklen= 5.0;
117 our $psu_sleeperlen= 17;
118 our $psu_sleeperlw= 15;
119 our $psu_raillw= 1.0;
120 our $psu_thinlw= 1.0;
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;
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;
136 our $olu_textheight= 15;
137 our $olu_textallowperc= $lmu_marktpt * 5.0/11;
139 our $pi= atan2(0,-1);
143 return 27 unless defined $radius;
144 $radius= abs($radius);
145 return ($radius >= 450 ? 33 :
146 $radius >= 400 ? 35 :
149 sub allwidth ($) { return allwidth2($_[0]) * 0.5; }
151 our $allwidthmax= allwidth(0);
152 our $allwidthmin= allwidth(undef);
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}
178 # $objs{$id}{Part} # 1 iff object is a part
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
186 our @al; # current cmd
191 our $param; # for parametric_curve
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
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.
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);
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) = @_;
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};
231 sub ev_decompose ($$$) {
232 # ev_decompose(B_R, A,SUM)
233 # computes B_R s.t. ev_compose({}, A, B_R) gives SUM
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});
244 sub ev_lincomb ($$$$) {
245 # ev_linkcomb(RES,A,B,P)
246 # gives P*A + (1-P)*B
247 my ($r,$a,$b,$p) = @_;
249 map { $r->{$_} = $q * $a->{$_} + $p * $b->{$_} } qw(X Y A);
252 sub a_normalise ($$) {
254 # adds or subtracts 2*$pi to/from A until it is in [ Z , Z+2*$pi >
257 $r= $z + fmod($a - $z, 2.0*$pi);
258 $r += 2*$pi if $r < $z;
261 sub ev_bearing ($$) {
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
268 $r= atan2($b->{Y} - $a->{Y},
270 $r= a_normalise($r,$a->{A});
274 sub v_rotateright ($) {
276 # returns image of A rotated 90 deg clockwise
278 return { X => $a->{Y}, Y => -$a->{X} };
280 sub v_dotproduct ($$) {
283 return $a->{X} * $b->{X} + $a->{Y} * $b->{Y};
285 sub v_scalarmult ($$) {
287 # multiplies V by scalar S and returns product
289 return { X => $s * $v->{X}, Y => $s * $v->{Y} };
293 # vector sum of all inputs
296 $r= { X => 0.0, Y => 0.0 };
297 foreach $i (@i) { $r->{X} += $i->{X}; $r->{Y} += $i->{Y}; }
300 sub v_subtract ($$) {
302 # returns vector from A to B, ie B - A
304 return { X => $b->{X} - $a->{X},
305 Y => $b->{Y} - $a->{Y} };
311 my ($x,$y) = ($v->{X}, $v->{Y});
312 return sqrt($x*$x + $y*$y);
316 # returns distance from A to B
317 return v_len(v_subtract($_[0],$_[1]));
322 $$limr= $now unless defined $$limr && $$limr <= $now;
326 $$limr= $now unless defined $$limr && $$limr >= $now;
330 my ($converter,$defaulter)=@_;
332 return &$defaulter unless @al;
334 $v= &$converter($spec);
335 dv('canf ','$spec',$spec, '$v',$v);
338 sub can ($) { my ($c)=@_; canf($c, sub { die "too few args"; }); }
339 sub cano ($$) { my ($c,$def)=@_; canf($c, sub { return $def }); }
341 sub signum ($) { return ($_[0] > 0) - ($_[0] < 0); }
345 my ($min_x, $max_x, $min_y, $max_y);
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})));
353 return ($min_x, $max_x, $min_y, $max_y);
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;
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])) }
366 $sp =~ m/^([-0-9eE.]*[0-9.])([A-Za-z]*)$/
367 or die "lexically invalid quantity";
369 $u=$ua->{'-'} unless length $u;
370 defined $ua->{$u} or die "unknown unit $u";
372 print DEBUG "cva_units($sp,)=$r ($n $u $ua->{$u})\n";
377 die "invalid id" unless $sp =~ m/^[a-z][_0-9A-Za-z]*$/;
382 my ($id,$r,$d,$k,$neg,$na,$obj_id,$vflip,$locs);
383 if ($sp =~ s/^(\^?)(\w+)\!//) {
386 die "invalid obj $obj_id in loc" unless exists $objs{$obj_id};
387 $locs= $objs{$obj_id}{Loc};
392 $neg= $sp =~ s/^\-//;
394 die "unknown $id" unless defined $locs->{$id};
397 foreach $k (sort keys %$r) { $d .= " $k=$r->{$k}"; }
398 printf DEBUG "%s\n", $d;
400 $r= { X => $r->{X}, Y => -$r->{Y}, A => -$r->{A} };
404 $na= a_normalise($na,0);
405 $r= { X => $r->{X}, Y => $r->{Y}, A => $na };
412 $neg = $sp =~ s/^\-//;
414 die "duplicate $id" if exists $ctx->{Loc}{$id};
415 $ctx->{Loc}{$id}{LayerKind}= $ctx->{Layer}{Kind};
416 push @{ $ctx->{LocsMade} }, {
420 return $ctx->{Loc}{$id};
422 sub cva_cmd ($) { return cva_idstr($_[0]); }
425 return $sp if grep { $_ eq $sp } @$el;
426 die "invalid option (permitted: @$el)";
428 sub cvam_enum { my (@e) = @_; return sub { cva__enum($_[0],\@e); }; }
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);
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 });
451 $pfx . ($pfx =~ m/\}$|\]$/ ? '' : '->');
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;
462 sub dv1_kind ($$$$$$$) {
463 my ($pfx,$expr,$ref,$ref_exp,$ixfmt,$ixesfn,$ixmapfn) = @_;
465 return 0 if $ref ne $ref_exp;
467 foreach $ix (&$ixesfn) {
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);
474 printf DEBUG "%s%s= $ixfmt\n", $pfx, $expr, ' ';
479 return 0 unless $debug;
480 my ($pfx,$expr,$v) = @_;
483 #print STDERR "dv1 >$pfx|$ref<\n";
485 printf DEBUG "%s%s= %s\n", $pfx,$expr, dv__evr($v);
487 } elsif ($ref eq 'SCALAR') {
488 dv1($pfx, ($expr =~ m/^\$/ ? "\$$expr" : '${'.$expr.'}'), $$v);
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;
510 sub o ($) { $o .= $_[0]; }
511 sub ol ($) { $ol .= $_[0]; }
513 print $o, $ol, " showpage\n"
520 sub o_path_begin () {
522 $o_path_verb= 'moveto';
524 sub o_path_point ($) {
526 o(" $pt $o_path_verb\n");
527 $o_path_verb= 'lineto';
529 sub o_path_stroke ($) {
531 o(" $width setlinewidth stroke\n");
535 my ($a,$b,$width)=@_;
539 o_path_stroke($width);
542 sub current_draw () {
544 $r= $ctx->{Draw} =~ m/X/ ? '' : $ctx->{Draw};
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}));
559 # dv("psu_coords ", '$ends',$ends, '$inunit',$inunit, '$across',$across,
560 # '\\%ea_zo', \%ea_zo);
561 return $ea_zo{X}." ".$ea_zo{Y};
564 sub parametric__o_pt ($) {
566 o_path_point("$pt->{X} $pt->{Y}");
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();
589 o(" $psu_thinlw setlinewidth\n");
591 for ($param=$p0; $param<$p1; $param += $ppu) {
592 parametric__o_pt(&$calcfn);
595 parametric__o_pt(&$calcfn);
598 return unless $draw =~ m/[ARS]/;
599 for ($pa= $p0; $pa<$p1; $pa=$pb) {
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;
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) {
615 o_line(psu_coords(\@ends,0,$side*$railctr),
616 psu_coords(\@ends,1.5,$side*$railctr),
621 o_line(psu_coords(\@ends,$sleeperctr,-$sleeperend),
622 psu_coords(\@ends,$sleeperctr,+$sleeperend),
627 foreach $side qw(-1 1) {
628 o_line(psu_coords(\@ends,0,$side*$allwidth),
629 psu_coords(\@ends,1.5,$side*$allwidth),
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),
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
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),
662 # joins_xxx all take $results, $from, $to, $minradius
663 # where $results->[]{Path}{K} etc. and $results->[]{SolKinds}[]
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));
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)) {
684 o("% twoarcs $m insoluble\n");
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);
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");
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' ] };
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 });
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}));
731 $k= ev_compose({}, $c, { X=>0, Y=>$lr*$minradius, A=>0 });
732 $l= ev_compose({}, $d, { X=>0, Y=>$lr*$minradius, A=>0 });
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);
746 $path= [{ T => Arc, F => $from, C => $c,
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) }];
757 SolKinds => [ 'arcsline', ($inv<0 ? 'cross' : 'loop') ] };
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; }
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);
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);
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; }
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' ] };
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");
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});
841 die "unknown segment $segment->{T}";
844 o("% length $len bends @bends.\n");
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 '!');
857 die "unknown sort criterion $crit";
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];
869 $bestscores= $scores;
871 die "no solution" unless defined $bestpath;
872 o("% chose path $bestpath @al\n");
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});
880 die "unknown segment";
886 my ($from,$to,$len) = @_;
887 parametric_segment(0.0, 1.0, abs($len) + 1e-6, undef, sub {
888 ev_lincomb({}, $from, $to, $param);
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') {
909 die "len of straight spec by angle";
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);
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);
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}));
928 } elsif ($how eq 'parallel') {
931 } elsif ($how eq 'uptoang') {
932 $beta= input_absang($ang);
934 } elsif ($how eq 'len') {
935 $sign_ang= signum($len);
936 $beta= $from->{A} - $sign_r * $len / abs($radius);
939 $sign_ang= signum($ang);
940 $beta= $from->{A} - $sign_r * $ang;
943 printf DEBUG "ctr->{Y}=$ctr->{Y} radius=$radius beta=$beta\n";
944 $beta += $sign_ang * $sign_r * 4.0 * $pi;
946 $delta= $beta - $from->{A};
947 last if $sign_ang * $sign_r * $delta <= 0;
948 $beta -= $sign_ang * $sign_r * $beta_interval * $pi;
950 printf DEBUG "ctr->{Y}=$ctr->{Y} radius=$radius beta=$beta\n";
951 arc($to, ,$ctr,$from, $radius,$delta);
953 printf DEBUG "to $to->{X} $to->{Y} $to->{A}\n";
958 return "$loc->{X} $loc->{Y} ".ang2deg($loc->{A});
961 return $_[0] * 180 / $pi;
963 sub input_absang ($) {
964 return $_[0] * $ctx->{Trans}{R} + $ctx->{Trans}{A};
966 sub input_abscoords ($$) {
968 ($in->{X}, $in->{Y}) = @_;
970 $out= ev_compose({}, $ctx->{Trans}, $in);
971 return ($out->{X}, $out->{Y});
977 Trans => { X => 0.0, Y => 0.0, A => 0.0, R => 1.0 },
979 DrawMap => sub { $_[0]; }
981 %{ $ctx->{Layer} }= %{ $ctx_save->{Layer} }
982 if defined $ctx_save;
988 sub cmd_defobj { cmd__defobj(0); }
989 sub cmd_defpart { cmd__defobj(1); }
990 sub cmd__defobj ($) {
993 $id= can(\&cva_idstr);
994 die "nested defobj" if $defobj_save;
995 die "repeated defobj" if exists $objs{$id};
997 $defobj_ispart= $ispart;
998 newctx($defobj_save);
1000 $ctx->{InDefObj}= $id;
1001 $ctx->{Draw}= $defobj_save->{Draw}.'X';
1002 $ctx->{DrawMap}= sub { ''; };
1003 $ctx->{Layer}= { Level => 5, Kind => '' };
1008 $id= $ctx->{InDefObj};
1009 die "unmatched enddef" unless defined $id;
1010 foreach $bit (qw(CmdLog Loc)) {
1011 $objs{$id}{$bit}= $ctx->{$bit};
1013 $objs{$id}{Part}= $defobj_ispart;
1015 $defobj_save= undef;
1016 $defobj_ispart= undef;
1019 sub cmd__runobj ($) {
1023 dv("cmd__runobj $obj_id ",'$ctx',$ctx);
1024 foreach $c (@{ $objs{$obj_id}{CmdLog} }) {
1026 next if $al[0] eq 'enddef';
1031 sub layer_draw ($$) {
1036 } elsif ($k eq 's') {
1038 } elsif ($k eq 'l') {
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}) {
1051 $r .= $cc if $cc =~ m/[A-Z]/;
1054 #print STDERR "layer $k$l gives $r (before map)\n";
1055 $r= &{ $ctx->{DrawMap} }($r);
1061 $kl= can(\&cva_identity);
1062 $kl =~ m/^([A-Za-z_]*)(\d*|\=|\*)$/ or die "invalid layer spec";
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);
1071 sub cmd_part { cmd__obj(Part); }
1072 sub cmd_obj { cmd__obj(1); }
1073 sub cmd_objflip { cmd__obj(-1); }
1077 my ($obj_id, $ctx_save, $pfx, $actual, $formal_id, $formal, $formcv);
1078 my ($part_name, $ctx_inobj, $obj, $id, $newid, $newpt);
1080 $part_name= can(\&cva_idstr);
1081 $how= (@al && $al[0] =~ s/^\^//) ? -1 : +1;
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}");
1091 $actual= can(\&cva_idex);
1092 $formal_id= can(\&cva_idstr);
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;
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}:";
1110 $ctx->{InRunObj}= $ctx_save->{InRunObj}."${obj_id}::";
1112 $ctx->{DrawMap}= sub {
1114 $i= &{ $ctx_save->{DrawMap} }($i);
1124 $ctx->{Draw}= &{ $ctx->{DrawMap} }($ctx_save->{Draw});
1125 cmd__runobj($obj_id);
1126 if (defined $part_name) {
1127 $pfx= $part_name.'_';
1129 if (@al && $al[0] eq '=') {
1130 $pfx= ''; shift @al;
1132 $pfx= cano(\&cva_idstr,undef);
1138 foreach $id (keys %{ $ctx_inobj->{Loc} }) {
1139 next if $id eq $formal_id;
1141 next if exists $ctx_save->{Loc}{$newid};
1142 $newpt= cva_idnew($newid);
1143 %$newpt= %{ $ctx_inobj->{Loc}{$id} };
1146 if (defined $part_name) {
1147 my ($formalr_id, $actualr_id, $formalr, $actualr);
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/^\-\-//;
1156 local ($ctx) = $ctx_inobj;
1157 $formalr= cva_idex($formalr_id);
1159 $actualr= cva_idnew($actualr_id);
1160 %$actualr= %$formalr;
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}= [ ];
1177 die "too many args" if @al;
1178 foreach $lm (@{ $ctx->{LocsMade} }) {
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]/) {
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");
1193 if ($draw =~ m/L/) {
1194 ol(" /s ($id) def\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");
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);
1217 $x=$olu_left; $y=$olu_bottom; undef $nxty;
1219 foreach $obj_id (sort keys %objs) {
1221 foreach $glob (@al) {
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$/;
1230 $obj= $objs{$obj_id};
1231 next unless $obj->{Part};
1232 ($min_x, $max_x, $min_y, $max_y) = bbox($obj->{Loc});
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;
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;
1248 $adj= length($obj_id) * $olu_textallowperc - $width;
1251 $ctx->{Trans}{X} += 0.5 * $adj;
1252 if ($x + $width > $olu_right && defined $nxty) {
1256 } elsif ($y + $height > $olu_top && $y > $olu_bottom) {
1258 $x= $olu_left; $y= $olu_bottom;
1265 $ctx->{InRunObj}= $ctx_save->{InRunObj}."${obj_id}//";
1266 $ctx->{Draw}= $ctx_save->{Draw};
1267 cmd__runobj($obj_id);
1269 " /s ($obj_id) def\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);
1287 " /lf /Courier-New findfont $lmu_marktpt scalefont def\n".
1288 " $ps_page_shift 0 translate 90 rotate\n".
1289 " -$ps_page_xmul $page_x mul -$ps_page_ymul $page_y mul translate\n".
1290 " $ptscale $ptscale scale\n"
1295 open DEBUG, ($debug ? ">&2" : ">/dev/null") or die $!;
1298 select(DEBUG); $|=1;
1299 select(STDOUT); $|=1;
1309 chomp; s/^\s+//; s/\s+$//;
1310 @al= split /\s+/, $_;
1312 print DEBUG "=== @al\n";
1313 last if $al[0] eq 'eof';
1314 push @{ $ctx->{CmdLog} }, [ @al ] if exists $ctx->{CmdLog};
1321 my ($min_x, $max_x, $min_y, $max_y) = bbox($ctx->{Loc});
1323 if (defined $min_x) {
1324 $bboxstr= sprintf("width %.2d (%.2d..%2.d)\n".
1325 "height %.2d (%.2d..%2.d)\n",
1326 $max_x - $min_x, $min_x, $max_x,
1327 $max_y - $min_y, $min_y, $max_y);
1329 $bboxstr= "no locs, no bbox\n";
1331 if (!$quiet) { print STDERR $bboxstr; }
1332 $bboxstr =~ s/^/\%L bbox /mg;
1333 print $bboxstr or die $!;