chiark / gitweb /
cfb31f849f85c005f6214d8527a120b4b8a52da8
[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 gentextmodule ($@) {
137     my ($form, @lines) = @_;
138     my $modb = "Commitid_$form";
139     p "module ${modb}_2D(){\n";
140     p " // |$_|\n" foreach @lines;
141     p " scale(Commitid__scale()){\n";
142     my $y = @lines;
143     my $cols = 1;
144     foreach my $line (@lines) {
145         $y--;
146         my $x = 0;
147         foreach my $chr (split //, $line) {
148             p sprintf "  translate([%d * 0.8, %d * 1.2]) %s();\n",
149                 $x, $y, chrmodname $chr
150                 if $chr =~ m/\S/;
151             $x++;
152         }
153         $cols = $x if $x > $cols;
154     }
155     p " }\n";
156     p "}\n";
157     p "module ${modb}(){\n";
158     p " d=Commitid_depth();\n";
159     p " translate([0,0,-d]) linear_extrude(height=d*2) ${modb}_2D();\n";
160     p "}\n";
161
162     p sprintf "function %s_sz() = Commitid__scale() * 0.1 * [ %d, %d ];\n",
163         $modb, 2 * ($cols * 4 - 1), 2 * (@lines * 6 - 1);
164
165     push @gtm_demo_o, <<END;
166  translate([$gtm_demo_i * st[0], $gtm_demo_j * st[1]]) {
167   difference(){
168    color("blue") translate([-e,-e]) square(${modb}_sz() + 2*[e,e]);
169    square(${modb}_sz());
170   }
171   ${modb}_2D();
172 }
173 END
174     $gtm_demo_j++;
175 }
176
177 our @demo;
178
179 sub parsefont () {
180     my %cellmap;
181     for (;;) {
182         $_ = <DATA> // die;
183         last if %cellmap && !m/\S/;
184         next unless m/\S/;
185         chomp;
186         s{^(.) }{};
187         $cellmap{$1} = $_;
188     }
189     my %chrpolys;
190     while (<DATA>) {
191         next unless m/\S/;
192         chomp;
193         my @chrs = split / /, $_;
194         <DATA> !~ m/\S/ or die;
195         foreach my $row (reverse 0..4) {
196             $_ = <DATA>;
197             chomp;
198             s{^}{ };
199             $_ .= ' ' x 8;
200             m{\S/\S} and die;
201             s{/(?=\s)}{L}g;
202             s{/(?=\S)}{r}g;
203             s{\\(?=\s)}{l}g;
204             s{\\(?=\S)}{R}g;
205             p "// $_\n";
206             foreach my $chr (@chrs) {
207                 s{^ }{} or die "$chr $_ ?";
208                 foreach my $col (0..2) {
209                     my @verts;
210                     if (s{^ }{}) {
211                     } elsif (s{^\S}{}) {
212                         my $f = $cellmap{$&};
213                         die unless $f;
214                         $f =~ s/\b\d/ sprintf '%05d', $col*2000 + $&*1025 /ge;
215                         $f =~ s/\d\b/ sprintf '%05d', $row*2000 + $&*1025 /ge;
216                         push @{ $chrpolys{$chr} }, [ split / /, $f ];
217                     } else {
218                         die "$_ ?";
219                     }
220                 }
221             }
222             die "$_ ?" if m{\S};
223         }    
224     }
225
226     my $demo = '';
227     my $democols = 6;
228     foreach my $chr (sort keys %chrpolys) {
229         my $mod = chrmodname $chr;
230         p "module $mod () {\n";
231         foreach my $poly (@{ $chrpolys{$chr} }) {
232             p " polygon([";
233             my $delim = "";
234             foreach my $pt (@$poly) {
235                 p $delim;
236                 $pt =~ s{\d{5}}{$&,};
237                 $pt =~ s{\b\d}{$&.}g;
238                 p "[$pt]";
239                 $delim = ',';
240             }
241             p "]);\n";
242         }
243         p "}\n";
244         $demo .= $chr;
245     }
246     @demo = reverse $demo =~ m{.{1,$democols}}go;
247 }
248
249 parsefont();
250
251 our $do_git; # contains may chars 'c' (count) and/or 'o' (object)
252 our $do_git_untracked = 1;
253 our $argcounter;
254
255 our @forms;
256
257 sub rjustt ($$;$) { # right justify and truncate (ie, pad and truncate at left)
258                     # always includes prefix
259     my ($sz, $whole, $prefix) = @_;
260     $prefix //= '';
261     my $lw = length $whole;
262     my $spare = $sz - $lw - (length $prefix);
263     return
264         ($spare > 0 ? (' ' x $spare) : '').
265         $prefix.
266         substr($whole, ($spare < 0 ? -$spare : 0));
267 }
268
269 sub ljustt ($$;$) {
270     my ($sz, $whole, $suffix) = @_;
271     $suffix //= '';
272     $sz -= length $suffix;
273     return sprintf "%-${sz}.${sz}s%s", $whole, $suffix;
274 }
275
276 sub genform ($@) {
277     my ($form, @lines) = @_;
278     gentextmodule($form, @lines);
279     my $f = {
280         Form => $form,
281         Chars => (length join '', @lines),
282         Lines => (scalar @lines),
283         Ambiguous => ($form =~ m/Full/ && !grep { m/\W/ } @lines),
284     };
285     push @forms, $f;
286 }
287
288 sub genform_q ($$$) {
289     my ($form, $s, $lines) = @_;
290     $gtm_demo_j++;
291     my $l = length $s;
292     return if $l % $lines;
293     my $e = $l/$lines;
294     return if $e < 2;
295     $gtm_demo_j--;
296     genform($form, $s =~ m/.{$e}/g);
297 }
298
299 sub genform_plusq ($$) {
300     my ($form, $s) = @_;
301     genform($form, $s);
302     genform_q("${form}S", $s, 2);
303     genform_q("${form}T", $s, 3);
304 }
305
306 our @gcmd;
307
308 sub gitrun_start () {
309     open F, "-|", @gcmd or die "$gcmd[0]: start: $!";
310 }
311
312 sub gitrun_done (;$) {
313     my ($errok) = @_;
314     $?=0; $!=0;
315     return if close F;
316     return if $errok;
317     die $! if $!;
318     die "@gcmd failed ($?)\n";
319 }
320
321 sub gitoutput (@) {
322     (@gcmd) = (qw(git), @_);
323     gitrun_start;
324     $_ = <F>;
325     gitrun_done;
326     defined or die "@gcmd produced no output";
327     chomp or die "@gcmd produced no final newline";
328     $_;
329 }
330
331 sub do_git () {
332     return unless $do_git;
333
334     @gcmd = qw(git status --porcelain);
335     push @gcmd, qw(--untracked=no) unless $do_git_untracked;
336
337     my $git_dirty = '';
338     gitrun_start;
339     while (<F>) {
340         if (m/^\?\?/ && $do_git_untracked) {
341             $git_dirty = '+';
342             next;
343         }
344         $git_dirty = '*';
345         last;
346     }
347     gitrun_done($git_dirty eq '*');
348
349     my $git_count;
350     my $git_object;
351
352     if ($do_git =~ m/c/) {
353         $git_count = gitoutput qw(rev-list --first-parent --count HEAD);
354     }
355     if ($do_git =~ m/o/) {
356         $git_object = gitoutput qw(rev-parse HEAD);
357     }
358
359     foreach my $sz (2..10) {
360         gentextmodule_demo_start_batch();
361
362         if (defined($git_count)) {
363             my $smallstr = rjustt($sz, $git_count, $git_dirty);
364             if (defined($git_object) && $sz >= length($git_count) + 3) {
365                 $smallstr = $git_object;
366                 $smallstr .= ($git_dirty || ' ');
367                 $smallstr .= $git_count;
368                 $smallstr = rjustt($sz, $smallstr);
369             }
370             genform_plusq("Small$sz", $smallstr);
371         }
372
373         genform_plusq("Git$sz", ljustt($sz, $git_object, $git_dirty))
374             if defined $git_object;
375
376         if (defined $git_count && defined $git_object) {
377             genform("Full".($sz*2),
378                     ljustt($sz, $git_object),
379                     rjustt($sz, $git_count, $git_dirty));
380
381             my $e = $sz;
382             genform("Full".($e*3)."T",
383                     ljustt($e*2, $git_object, $git_dirty)
384                     =~ m/.{$e}/g,
385                     rjustt($e, $git_count));
386         }
387     }
388 }
389
390 sub do_some_best ($$) {
391     my ($modname, $formre) = @_;
392     my $fullmodname = "Commitid_${modname}_2D";
393     p "module $fullmodname(max_sz) {\n";
394     p ' sc_max = $Commitid_max_best_scale ? $Commitid_max_best_scale : 2;'."\n";
395     my @do;
396     foreach my $f (
397         sort {
398             $b->{Chars} <=> $a->{Chars} or
399             $a->{Lines} <=> $b->{Chars}
400         }
401         grep {
402             $_->{Form} =~ m/$formre/ &&
403             !$_->{Ambiguous}
404         }
405         @forms
406     ) {
407         my $form = $f->{Form};
408         p " sz_$form = Commitid_${form}_sz();\n";
409         foreach my $rot (qw(0 1)) {
410             my $id = "${form}_r${rot}";
411             p " sc_$id = min(sc_max";
412             foreach my $xy (qw(0 1)) {
413                 p ",max_sz[$xy]/sz_$form","[",(($xy xor $rot)+0),"]";
414             }
415             p ");\n";
416             push @do, " if (sc_$id >= 1.0) {\n";
417             push @do, "  scale(sc_$id)\n";
418             push @do, "   rotate(90) translate([0,-sz_$form"."[1]])\n" if $rot;
419             push @do, "   Commitid_${form}_2D();\n";
420             push @do, " } else";
421         }
422     }
423     push @do, <<END;
424  {
425   echo("$fullmodname could not fit anything in", max_sz);
426  }
427 END
428     p $_ foreach @do;
429     p "}\n";
430 }
431
432 sub do_git_best () {
433     return unless $do_git;
434
435     # Auto-computer for `best fit'
436     #
437     # We have two best fit approaches: with count, and git-object-id-only
438     #
439     # For `with count', we only ever include the git object id if the
440     # result would be unambigous.  That means that at least one space
441     # or punctuation was generated.
442     #
443     # We sort the options by firstly number of characters
444     # (decreasing), and then by number of lines (increasing) and
445     # try each one both ways round.
446
447     do_some_best('BestCount', 'Small|Full') if $do_git =~ m/c/;
448     do_some_best('BestObjid', 'Git|Full') if $do_git =~ m/o/;
449 }
450
451 while (@ARGV) {
452     $_ = shift;
453     if (m/^--(no)?-git$/) {
454         $do_git = $1 ? '' : 'co';
455     } elsif (m/^---git=object$/) {
456         $do_git = 'o';
457     } elsif (m/^-i$/) {
458         $do_git_untracked = 0;
459     } elsif (m/^-t(.*)$/) {
460         my $form = $1;
461         die "bad usage: -t needs string argument\n";
462         $_ = shift;
463         gentextmodule($form, split /\n/, $_);
464         $argcounter //= 0;
465     } elsif (m/^[^-]/) {
466         gentextmodule("Arg$argcounter", $_);
467         $argcounter++;
468     } else {
469         die "bad usage: unknown option \`$_'\n";
470     }
471 }
472
473 $do_git //= defined($argcounter) ? '' : 'co';
474
475 gentextmodule_demo_start_batch();
476 gentextmodule('FontDemo', @demo);
477
478 do_git();
479 do_git_best();
480
481 p "module Commitid_2DDemo(){\n";
482 p " st = Commitid__scale() * [ 10, 5 ];\n";
483 p " e  = Commitid_pixelsz();\n";
484 p $_ foreach @gtm_demo_o;
485 p "}\n";
486
487 flush STDOUT or die $!;
488 close STDOUT or die $!;
489
490 __DATA__
491
492 # 00 20 22 02
493 l 00 20 02
494 r 00 20 22
495 L 00 22 02
496 R 20 22 02
497 > 00 20 22 02 11
498 < 00 20 11 22 02
499
500 0 1 2 3 4 5 6 7 8 9
501
502 /#\  r  /#\ ##\ # # ### //  ### /#\ /#\
503 # # /#    #   # # # #   #     # # # # #
504 # #  #  /#/ ##< \## ##\ ##\  // >#< \##
505 # #  #  #     #   #   # # #  #  # #   #
506 \#/ /#\ ### ##/   # ##/ \#/  #  \#/ ##/
507
508 a b c d e f
509
510     #         #     /##
511     #   /##   # /#\ #
512 /## ##\ #   /## #r# ###
513 # # # # #   # # #/  #
514 \## ##/ \## \## \#/ #
515
516 + *
517
518     # #
519  #  \#/
520 ### ###
521  #  /#\
522     # #