chiark / gitweb /
commitid: commitid-best-test.scad: explicit margin
[reprap-play.git] / commitid.scad.pl
1 #!/usr/bin/perl -w
2 use strict;
3
4 $SIG{__WARN__} = sub { die @_; };
5
6 #  xxx much of the comment below is TODO
7 #
8 # Usage:
9 #
10 #   .../commitid.scad.pl [OPTION...] [STRING...] >commitid.scad.new \
11 #     && mv -f commitid.scad.new commitid.scad
12 #
13 # Options:
14 #
15 #   --git    generate git commit indications, as shown below
16 #            (this is the default if no strings are requested with -t)
17 #
18 #   --git=object
19 #            generate git commit indication based on commit object only
20 #            (ie avoid counting commits)
21 #
22 #   -i       do not generate `+' if git-untracked files are present
23 #
24 #   [-t[FORM]] TEXT
25 #            generate a form FORM containing TEXT
26 #            TEXT can contain newlines (final newline usually undesirable)
27 #            if FORM not specified, generates Arg0 Arg1 Arg2 in sequence
28 #            character set is SPC 0-9 a-f + *
29 #
30 # We generate a physical indication of which commit was used.
31 #
32 # We provide for scaling factors with dynamic variables:
33 #    $Commitid_pixelsz        if not set, we use 0.8 } multiplied
34 #    $Commitid_scale          if not set, we use 1.0 }  together
35 #    $Commitid_depth          if not set, we use xy pixel size from above / 2
36 #    $Commitid_depth_scale    if not set, we use 1.0 (multiplies depth above)
37 #    $Commitid_max_best_scale if not set, we use 2.0 (max mult of xy in Best)
38 #
39 # For each form we have
40 #
41 #    module Commitid_Form_2D() { ... }
42 #    module Commitid_Form() { ... }
43 #    function Commitid_Form_sz()     => [ x, y ]
44 #
45 #  These have their origin in the bottom left corner.  The 3D model
46 #  is a positive, has its origin halfway through, and is twice the
47 #  depth in height, so it can be added or subtracted.
48 #
49 # And we provide
50 #
51 #   function Commitid_pixelsz()    // $Commitid_pixelsz * $Commitid_scale
52 #   function Commitid_depth()      // see above
53 #
54 # We can generate these forms:
55 #
56 #  In each case:
57 #    if tree is dirty, * is suffixed or prefixed to count or commitid
58 #    if tree has untracked files, + is added
59 #    (where it is added depends on the Form; in any case it does not
60 #    change the size, but steals space from digits)
61 #
62 #   Small2 Small3 ... Small10:
63 #       git rev-list --first-parent --count HEAD
64 #       typically 3-4 characters but we allow for up to 6
65 #       padded with zeroes; if too long we reduce mod 10^n
66 #       eg if the count is 123456
67 #            Small5    3456*
68 #            Small8    _*123456    (where _ are spaces)
69 #       the git objectid is included if it will fit
70 #       unambiguously and usefully eg
71 #            Small9    ab*123456
72 #
73 #   Small2S Small4S ... Small10S:
74 #   Small3T Small9T:
75 #       same but split into two lines (S) or three lines (T) eg
76 #            Small4S  45     Small6T   _3
77 #                     6*               45
78 #                                      6*
79 #
80 #   Git2 Git3 ... Git10:
81 #   Git4S Git6S ... Git10S:
82 #   Git6T Git9T:
83 #       git-rev-parse HEAD   (prefix of requested length)
84 #       eg if the commitid is abcdef0123...
85 #            Git5    abcd*
86
87 #   Full4 Full6 ... Full20:
88 #       git-rev-list --first-parent --count HEAD
89 #       git-rev-parse HEAD
90 #       (all on two lines)
91 #       eg
92 #            Full6    abcdef       Full8     abcdef01
93 #                     23456*                 _123456*
94 #
95 #   Full6T Full9T ... Full30T
96 #       as Full but commit is split over two lines
97 #       for a 3-line message; eg
98 #             Full9T    abc
99 #                       de*
100 #                       456
101 #
102 #   FontDemo
103 #
104 #   Arg0, Arg1, ...
105 #       Strings passed on command line
106
107 sub p { print @_ or die $!; }
108
109 p <<'END';
110 // *** AUTOGENERATED - DO NOT EDIT *** //
111 function Commitid_pixelsz() =
112   ($Commitid_pixelsz       ? $Commitid_pixelsz       : 0.8) *
113   ($Commitid_scale         ? $Commitid_scale         : 1.0);
114 function Commitid_depth() =
115   ($Commitid_depth         ? $Commitid_depth         : Commitid_pixelsz()/2) *
116   ($Commitid_depth_scale   ? $Commitid_depth_scale   : 1.0);
117 function Commitid__scale() =
118   Commitid_pixelsz() / 0.2;
119 END
120
121 sub chrmodname ($) {
122     my ($chr) = @_;
123     my $chrx = sprintf '%#x', ord $chr;
124     return "Commitid__chr_$chrx";
125 }
126
127 our $gtm_demo_i = -1;
128 our $gtm_demo_j;
129 our @gtm_demo_o;
130
131 sub gentextmodule_demo_start_batch () {
132     $gtm_demo_j = 0;
133     $gtm_demo_i++;
134 }
135
136 sub gen3dmodule ($@) {
137     my ($modb,@argl) = (@_);
138     p "module ${modb}(".(join ', ', @argl)."){\n";
139     p " d=Commitid_depth();\n";
140     p " translate([0,0,-d]) linear_extrude(height=d*2)\n";
141     p "  ${modb}_2D(".(join ',', map { m/=/ ? $` : $_ } @argl).");\n";
142     p "}\n";
143 }
144
145 sub gentextmodule ($@) {
146     my ($form, @lines) = @_;
147     my $modb = "Commitid_$form";
148     p "module ${modb}_2D(){\n";
149     p " // |$_|\n" foreach @lines;
150     p " scale(Commitid__scale()){\n";
151     my $y = @lines;
152     my $cols = 1;
153     foreach my $line (@lines) {
154         $y--;
155         my $x = 0;
156         foreach my $chr (split //, $line) {
157             p sprintf "  translate([%d * 0.8, %d * 1.2]) %s();\n",
158                 $x, $y, chrmodname $chr
159                 if $chr =~ m/\S/;
160             $x++;
161         }
162         $cols = $x if $x > $cols;
163     }
164     p " }\n";
165     p "}\n";
166     gen3dmodule($modb);
167
168     p sprintf "function %s_sz() = Commitid__scale() * 0.1 * [ %d, %d ];\n",
169         $modb, 2 * ($cols * 4 - 1), 2 * (@lines * 6 - 1);
170
171     push @gtm_demo_o, <<END;
172  translate([$gtm_demo_i * st[0], $gtm_demo_j * st[1]]) {
173   difference(){
174    color("blue") translate([-e,-e]) square(${modb}_sz() + 2*[e,e]);
175    square(${modb}_sz());
176   }
177   ${modb}_2D();
178 }
179 END
180     $gtm_demo_j++;
181 }
182
183 our @demo;
184
185 sub parsefont () {
186     my %cellmap;
187     for (;;) {
188         $_ = <DATA> // die;
189         last if %cellmap && !m/\S/;
190         next unless m/\S/;
191         chomp;
192         s{^(.) }{};
193         $cellmap{$1} = $_;
194     }
195     my %chrpolys;
196     while (<DATA>) {
197         next unless m/\S/;
198         chomp;
199         my @chrs = split / /, $_;
200         <DATA> !~ m/\S/ or die;
201         foreach my $row (reverse 0..4) {
202             $_ = <DATA>;
203             chomp;
204             s{^}{ };
205             $_ .= ' ' x 8;
206             m{\S/\S} and die;
207             s{/(?=\s)}{L}g;
208             s{/(?=\S)}{r}g;
209             s{\\(?=\s)}{l}g;
210             s{\\(?=\S)}{R}g;
211             p "// $_\n";
212             foreach my $chr (@chrs) {
213                 s{^ }{} or die "$chr $_ ?";
214                 foreach my $col (0..2) {
215                     my @verts;
216                     if (s{^ }{}) {
217                     } elsif (s{^\S}{}) {
218                         my $f = $cellmap{$&};
219                         die unless $f;
220                         $f =~ s/\b\d/ sprintf '%05d', $col*2000 + $&*1025 /ge;
221                         $f =~ s/\d\b/ sprintf '%05d', $row*2000 + $&*1025 /ge;
222                         push @{ $chrpolys{$chr} }, [ split / /, $f ];
223                     } else {
224                         die "$_ ?";
225                     }
226                 }
227             }
228             die "$_ ?" if m{\S};
229         }    
230     }
231
232     my $demo = '';
233     my $democols = 6;
234     foreach my $chr (sort keys %chrpolys) {
235         my $mod = chrmodname $chr;
236         p "module $mod () {\n";
237         foreach my $poly (@{ $chrpolys{$chr} }) {
238             p " polygon([";
239             my $delim = "";
240             foreach my $pt (@$poly) {
241                 p $delim;
242                 $pt =~ s{\d{5}}{$&,};
243                 $pt =~ s{\b\d}{$&.}g;
244                 p "[$pt]";
245                 $delim = ',';
246             }
247             p "]);\n";
248         }
249         p "}\n";
250         $demo .= $chr;
251     }
252     @demo = reverse $demo =~ m{.{1,$democols}}go;
253 }
254
255 parsefont();
256
257 our $do_git; # contains may chars 'c' (count) and/or 'o' (object)
258 our $do_git_untracked = 1;
259 our $argcounter;
260
261 our @forms;
262
263 sub rjustt ($$;$) { # right justify and truncate (ie, pad and truncate at left)
264                     # always includes prefix
265     my ($sz, $whole, $prefix) = @_;
266     $prefix //= '';
267     my $lw = length $whole;
268     my $spare = $sz - $lw - (length $prefix);
269     return
270         ($spare > 0 ? (' ' x $spare) : '').
271         $prefix.
272         substr($whole, ($spare < 0 ? -$spare : 0));
273 }
274
275 sub ljustt ($$;$) {
276     my ($sz, $whole, $suffix) = @_;
277     $suffix //= '';
278     $sz -= length $suffix;
279     return sprintf "%-${sz}.${sz}s%s", $whole, $suffix;
280 }
281
282 sub genform ($@) {
283     my ($form, @lines) = @_;
284     gentextmodule($form, @lines);
285     my $f = {
286         Form => $form,
287         Chars => (length join '', @lines),
288         Lines => (scalar @lines),
289         Ambiguous => ($form =~ m/Full/ && !grep { m/\W/ } @lines),
290     };
291     push @forms, $f;
292 }
293
294 sub genform_q ($$$) {
295     my ($form, $s, $lines) = @_;
296     $gtm_demo_j++;
297     my $l = length $s;
298     return if $l % $lines;
299     my $e = $l/$lines;
300     return if $e < 2;
301     $gtm_demo_j--;
302     genform($form, $s =~ m/.{$e}/g);
303 }
304
305 sub genform_plusq ($$) {
306     my ($form, $s) = @_;
307     genform($form, $s);
308     genform_q("${form}S", $s, 2);
309     genform_q("${form}T", $s, 3);
310 }
311
312 our @gcmd;
313
314 sub gitrun_start () {
315     open F, "-|", @gcmd or die "$gcmd[0]: start: $!";
316 }
317
318 sub gitrun_done (;$) {
319     my ($errok) = @_;
320     $?=0; $!=0;
321     return if close F;
322     return if $errok;
323     die $! if $!;
324     die "@gcmd failed ($?)\n";
325 }
326
327 sub gitoutput (@) {
328     (@gcmd) = (qw(git), @_);
329     gitrun_start;
330     $_ = <F>;
331     gitrun_done;
332     defined or die "@gcmd produced no output";
333     chomp or die "@gcmd produced no final newline";
334     $_;
335 }
336
337 sub do_git () {
338     return unless $do_git;
339
340     @gcmd = qw(git status --porcelain);
341     push @gcmd, qw(--untracked=no) unless $do_git_untracked;
342
343     my $git_dirty = '';
344     gitrun_start;
345     while (<F>) {
346         if (m/^\?\?/ && $do_git_untracked) {
347             $git_dirty = '+';
348             next;
349         }
350         $git_dirty = '*';
351         last;
352     }
353     gitrun_done($git_dirty eq '*');
354
355     my $git_count;
356     my $git_object;
357
358     if ($do_git =~ m/c/) {
359         $git_count = gitoutput qw(rev-list --first-parent --count HEAD);
360     }
361     if ($do_git =~ m/o/) {
362         $git_object = gitoutput qw(rev-parse HEAD);
363     }
364
365     foreach my $sz (2..10) {
366         gentextmodule_demo_start_batch();
367
368         if (defined($git_count)) {
369             my $smallstr = rjustt($sz, $git_count, $git_dirty);
370             if (defined($git_object) && $sz >= length($git_count) + 3) {
371                 $smallstr = $git_object;
372                 $smallstr .= ($git_dirty || ' ');
373                 $smallstr .= $git_count;
374                 $smallstr = rjustt($sz, $smallstr);
375             }
376             genform_plusq("Small$sz", $smallstr);
377         }
378
379         genform_plusq("Git$sz", ljustt($sz, $git_object, $git_dirty))
380             if defined $git_object;
381
382         if (defined $git_count && defined $git_object) {
383             genform("Full".($sz*2),
384                     ljustt($sz, $git_object),
385                     rjustt($sz, $git_count, $git_dirty));
386
387             my $e = $sz;
388             genform("Full".($e*3)."T",
389                     ljustt($e*2, $git_object, $git_dirty)
390                     =~ m/.{$e}/g,
391                     rjustt($e, $git_count));
392         }
393     }
394 }
395
396 sub do_some_best ($$) {
397     my ($modname, $formre) = @_;
398     my $fullmodname = "Commitid_${modname}_2D";
399     my @argl = qw(max_sz margin=Commitid_pixelsz());
400     p "module $fullmodname(".(join ', ', @argl).") {\n";
401     my $mbs = '$Commitid_max_best_scale';
402     p " sc_max = $mbs ? $mbs : 2;\n";
403     p " sz = max_sz - 2*[margin,margin];\n";
404     my @do;
405     foreach my $f (
406         sort {
407             $b->{Chars} <=> $a->{Chars} or
408             $a->{Lines} <=> $b->{Chars}
409         }
410         grep {
411             $_->{Form} =~ m/$formre/ &&
412             !$_->{Ambiguous}
413         }
414         @forms
415     ) {
416         my $form = $f->{Form};
417         p " sz_$form = Commitid_${form}_sz();\n";
418         foreach my $rot (qw(0 1)) {
419             my $id = "${form}_r${rot}";
420             p " sc_$id = min(sc_max";
421             foreach my $xy (qw(0 1)) {
422                 p ",sz[$xy]/sz_$form","[",(($xy xor $rot)+0),"]";
423             }
424             p ");\n";
425             push @do, " if (sc_$id >= 1.0";
426             push @do, " && sc_$id >= sc_${form}_r1" if !$rot;
427             push @do, ") {\n";
428             push @do, "  translate([margin,margin]) scale(sc_$id)\n";
429             push @do, "   rotate(90) translate([0,-sz_$form"."[1]])\n" if $rot;
430             push @do, "   Commitid_${form}_2D();\n";
431             push @do, " } else";
432         }
433     }
434     push @do, <<END;
435  {
436   echo("$fullmodname could not fit anything in", max_sz);
437  }
438 END
439     p $_ foreach @do;
440     p "}\n";
441
442     gen3dmodule "Commitid_$modname", @argl;
443 }
444
445 sub do_git_best () {
446     return unless $do_git;
447
448     # Auto-computer for `best fit'
449     #
450     # We have two best fit approaches: with count, and git-object-id-only
451     #
452     # For `with count', we only ever include the git object id if the
453     # result would be unambigous.  That means that at least one space
454     # or punctuation was generated.
455     #
456     # We sort the options by firstly number of characters
457     # (decreasing), and then by number of lines (increasing) and
458     # try each one both ways round.
459
460     do_some_best('BestCount', 'Small|Full') if $do_git =~ m/c/;
461     do_some_best('BestObjid', 'Git|Full') if $do_git =~ m/o/;
462 }
463
464 while (@ARGV) {
465     $_ = shift;
466     if (m/^--(no)?-git$/) {
467         $do_git = $1 ? '' : 'co';
468     } elsif (m/^---git=object$/) {
469         $do_git = 'o';
470     } elsif (m/^-i$/) {
471         $do_git_untracked = 0;
472     } elsif (m/^-t(.*)$/) {
473         my $form = $1;
474         die "bad usage: -t needs string argument\n";
475         $_ = shift;
476         gentextmodule($form, split /\n/, $_);
477         $argcounter //= 0;
478     } elsif (m/^[^-]/) {
479         gentextmodule("Arg$argcounter", $_);
480         $argcounter++;
481     } else {
482         die "bad usage: unknown option \`$_'\n";
483     }
484 }
485
486 $do_git //= defined($argcounter) ? '' : 'co';
487
488 gentextmodule_demo_start_batch();
489 gentextmodule('FontDemo', @demo);
490
491 do_git();
492 do_git_best();
493
494 p "module Commitid_2DDemo(){\n";
495 p " st = Commitid__scale() * [ 10, 5 ];\n";
496 p " e  = Commitid_pixelsz();\n";
497 p $_ foreach @gtm_demo_o;
498 p "}\n";
499
500 flush STDOUT or die $!;
501 close STDOUT or die $!;
502
503 __DATA__
504
505 # 00 20 22 02
506 l 00 20 02
507 r 00 20 22
508 L 00 22 02
509 R 20 22 02
510 > 00 20 22 02 11
511 < 00 20 11 22 02
512
513 0 1 2 3 4 5 6 7 8 9
514
515 /#\  r  /#\ ##\ # # ### //  ### /#\ /#\
516 # # /#    #   # # # #   #     # # # # #
517 # #  #  /#/ ##< \## ##\ ##\  // >#< \##
518 # #  #  #     #   #   # # #  #  # #   #
519 \#/ /#\ ### ##/   # ##/ \#/  #  \#/ ##/
520
521 a b c d e f
522
523     #         #     /##
524     #   /##   # /#\ #
525 /## ##\ #   /## #r# ###
526 # # # # #   # # #/  #
527 \## ##/ \## \## \#/ #
528
529 + *
530
531     # #
532  #  \#/
533 ### ###
534  #  /#\
535     # #