chiark / gitweb /
1ee20e8b84440c66cb0cc5b5e2ce17a8108276d7
[reprap-play.git] / commitid.scad.pl
1 #!/usr/bin/perl -w
2
3 # commitid.scad.pl - a program for annotating solid models with commit info
4 # Copyright (C)2016 Ian Jackson.  See below.  There is NO WARRANTY.
5
6
7 # USAGE
8 # =====
9 #
10 #   .../commitid.scad.pl [OPTION...] [STRING...] >commitid.scad.new \
11 #     && mv -f commitid.scad.new commitid.scad
12 #
13 # Run without arguments, commitid.scad.pl will output an openscad file
14 # which contains 2D and 3D models of the current git commit count and
15 # commit object id (commit hash), useful for identifying printed
16 # parts.
17 #
18 # See below for details.  You probably want these two sections, as a
19 # quick starting point:
20 #    General form of provided openscad modules
21 #    Autoscaling modules
22 #
23 # We can also generate models of short mainly-numeric strings
24 # specified on the command line.
25 #
26 #
27 # Options:
28 #
29 #   --git    Generate git commit indications, as shown below
30 #            (this is the default if no strings are requested with -t).
31 #            Ie, produce the `Autoscaling modules' and `Specific layouts'.
32 #
33 #   --git=objid
34 #            Generate git commit indication based on commit object only
35 #            (ie avoid counting commits).  Ie, do not generate `Small'
36 #            and `Full' layouts (and never select them for `Best').
37 #
38 #   -i       Do not generate `+' dirty indication if git-untracked files
39 #            are present (ie, missing .gitignore entries).  The `*'
40 #            dirty tree indication (for modified files) cannot be disabled.
41 #
42 #   [-t[LAYOUT]] TEXT
43 #            Generate a layout LAYOUT containing TEXT.  TEXT can
44 #            contain newlines (a final newline usually undesirable, as
45 #            it will generate a blank line).  If LAYOUT is not specified,
46 #            generates Arg0, Arg1, Arg2, etc., for successive such
47 #            TEXTs.  The permissible character set in is TEXT is:
48 #                 space 0-9 a-f + *
49 #
50 #
51 # OPENSCAD INTERFACE
52 # ==================
53 #
54 # Dynamic variables for configuration
55 # -----------------------------------
56 #
57 # We honour the following variables to control various scaling factors:
58 #
59 #                             default value  notes
60 #    $Commitid_pixelsz         0.8             \ multiplied together
61 #    $Commitid_scale           1.0             /
62 #    $Commitid_depth           pixelsz/2       \ multiplied together
63 #    $Commitid_depth_scale     1.0             / 
64 #    $Commitid_max_best_scale  2.0             limits XY scaling in *Best*
65 #
66 # FYI the font is nominally 3x5 pixels, with 1-pixel inter-line and
67 # inter-character gaps.  (It's not strictly speaking a 3x5 bitmap
68 # font, size it contains partial pixels and diagonals.)
69 #
70 #
71 # Non-`module'-specific functions
72 # -------------------------------
73 #
74 # We provide the following functions (which depend on the config
75 # variables, but not on anything else) and compute useful values:
76 #
77 #   function Commitid_pixelsz()   Actual size of each nominal pixel
78 #   function Commitid_depth()     Depth to use (the amount characters
79 #                                  should be raised or sunken)
80 #
81 # General form of provided openscad modules
82 # -----------------------------------------
83 #
84 #   module Commitid_MODULE_2D(...)  A collection of polygons forming characters
85 #   module Commitid_MODULE(...)     The above, extruded up and down in Z
86 #   function Commitid_MODULE_sz()   A 2-vector giving the X,Y size
87 #
88 # Except for *Best* modules, the XY origin is in the bottom left
89 # corner without any margin.  Likewise Commitid_MODULE_sz does not
90 # include any margin.
91 #
92 # For 3D versions, the model is 2*depth deep and the XY plane bisects
93 # the model.  This means it's convenient to either add or subtract from
94 # a workpiece whose face is in the XY plane.
95 #
96 #
97 # Autoscaling modules
98 # -------------------
99 #
100 # These modules take a specification of the available XY space, and
101 # select and generate a suitable specific identification layout:
102
103 #   module Commitid_BestCount_2D(max_sz, margin=Commitid_pixelsz())
104 #   module Commitid_BestCount   (max_sz, margin=Commitid_pixelsz())
105 #   module Commitid_BestObjid_2D(max_sz, margin=Commitid_pixelsz())
106 #   module Commitid_BestObjid   (max_sz, margin=Commitid_pixelsz())
107 #
108 # max_sz should be [x,y].
109 #
110 # BestCount includes (as much as it can of) the git commit count,
111 # ie the result of
112 #     git rev-list --first-parent --count HEAD
113 # (and it may include some of the git revision ID too).
114 #
115 # BestObjid includes as much as it can of the git commit object hash,
116 # and never includes any of the count.
117 #
118 # All of these will autoscale and autorotate the selected model, and
119 # will include an internal margin of the specified size (by default,
120 # one pixel around each edge).  If no margin is needed, pass margin=0.
121 #
122 # There are no `function Commitid_Best*_sz'.  If they existed they
123 # would simply return max_sz.
124 #
125 #
126 # Output format
127 # -------------
128 #
129 # In general the output, although it may be over multiple lines,
130 # is always in this order
131 #     git commit object id (hash)
132 #     dirty indicator
133 #     git commit count
134 #
135 # Not all layouts have all these parts.  The commit object id may
136 # sometimes be split over multiple lines, but the count will not be.
137 # If both commit id and commit count appear they will be separated
138 # by (at least) a newline, or a dirty indicator, or a space.
139 #
140 # The commit id is truncated to fit, from the right.
141 #
142 # The commit count is truncated from the _left_, leaving the least
143 # significant decimal digits.
144 #
145 # The dirty indicator can be
146 #
147 #   *   meaning the working tree contains differences from HEAD
148 #
149 #   +   meaning the working tree contains untracked files
150 #       (ie files you have failed to `git add' and also failed
151 #       to add to gitignore).  (But see the -i option.)
152 #
153 #
154 # Specific layouts
155 # ----------------
156 #
157 # If you want to control the exact layout (and make space for it in
158 # your design), you can use these:
159 #
160 #    module Commitid_LAYOUT_2D()
161 #    module Commitid_LAYOUT()
162 #    function Commitid_LAYOUT_sz()
163 #
164 # Here LAYOUT is one of the following (giving for example, `module
165 # Commitid_Full8_2D').  In the examples, we will assume that the tree
166 # is dirty, the commit count is 123456, and the commit object id
167 # starts abcdeffedbcaabcdef...  In the examples `_' shows where a
168 # space would be printed.
169 #
170 #   Small2 Small3 ... Small10
171 #       A single line containing as much of the count will fit, eg:
172 #            Small5    3456*
173 #            Small8    _*123456
174 #       The objectid is included if more than one character of of it
175 #       will fit without makign the output ambiguous:
176 #            Small9    ab*123456
177 #
178 #   Small2S Small4S ... Small10S
179 #   Small3T Small9T
180 #       Same as Small but split into two lines (S)
181 #       or three lines (T).  Eg:
182 #            Small4S    *4       Small6T   _*
183 #                       56                 34
184 #                                          56
185 #   Git2 Git3 ... Git10
186 #   Git4S Git6S ... Git10S
187 #   Git6T Git9T
188 #       Just the commit object hash, in one, two (S) or three (T)
189 #       lines.  E.g.:
190 #            Git5    abcd*
191 #
192 #   Full4 Full6 ... Full20:
193 #       The commit object hash plus the commit count, on
194 #       separate lines, eg:
195 #            Full6    abcdef     Full8     abcdeffe
196 #                     *23456               _*123456
197 #
198 #   Full6T Full9T ... Full30T
199 #       As Full but the commit object id is split over two lines
200 #       producing a 3-line layout, eg:
201 #            Full9T    abc       Full21T   abcdeff
202 #                      de*                 edbcaa*
203 #                      456                 _123456
204 #
205 # Other LAYOUTs
206 # -------------
207 #
208 #   FontDemo
209 #
210 #       A demonstration of the built-in 18-character font
211 #
212 #   Arg0 Arg1, ...
213 #
214 #       Strings passed on command line (without -t, or bare -t,
215 #       rather than with -tLAYOUT).
216 #
217 #   LAYOUT
218 #
219 #       Generated by passing -tLAYOUT on the command line.
220 #
221
222
223 use strict;
224
225 $SIG{__WARN__} = sub { die @_; };
226
227 sub p { print @_ or die $!; }
228
229 p <<'END';
230 // *** AUTOGENERATED - DO NOT EDIT *** //
231 function Commitid_pixelsz() =
232   ($Commitid_pixelsz       ? $Commitid_pixelsz       : 0.8) *
233   ($Commitid_scale         ? $Commitid_scale         : 1.0);
234 function Commitid_depth() =
235   ($Commitid_depth         ? $Commitid_depth         : Commitid_pixelsz()/2) *
236   ($Commitid_depth_scale   ? $Commitid_depth_scale   : 1.0);
237 function Commitid__scale() =
238   Commitid_pixelsz() / 0.2;
239 END
240
241 sub chrmodname ($) {
242     my ($chr) = @_;
243     my $chrx = sprintf '%#x', ord $chr;
244     return "Commitid__chr_$chrx";
245 }
246
247 our $gtm_demo_i = -1;
248 our $gtm_demo_j;
249 our @gtm_demo_o;
250
251 sub gentextmodule_demo_start_batch () {
252     $gtm_demo_j = 0;
253     $gtm_demo_i++;
254 }
255
256 sub gen3dmodule ($@) {
257     my ($modb,@argl) = (@_);
258     p "module ${modb}(".(join ', ', @argl)."){\n";
259     p " d=Commitid_depth();\n";
260     p " translate([0,0,-d]) linear_extrude(height=d*2)\n";
261     p "  ${modb}_2D(".(join ',', map { m/=/ ? $` : $_ } @argl).");\n";
262     p "}\n";
263 }
264
265 sub gentextmodule ($@) {
266     my ($form, @lines) = @_;
267     my $modb = "Commitid_$form";
268     p "module ${modb}_2D(){\n";
269     p " // |$_|\n" foreach @lines;
270     p " scale(Commitid__scale()){\n";
271     my $y = @lines;
272     my $cols = 1;
273     foreach my $line (@lines) {
274         $y--;
275         my $x = 0;
276         foreach my $chr (split //, $line) {
277             p sprintf "  translate([%d * 0.8, %d * 1.2]) %s();\n",
278                 $x, $y, chrmodname $chr
279                 if $chr =~ m/\S/;
280             $x++;
281         }
282         $cols = $x if $x > $cols;
283     }
284     p " }\n";
285     p "}\n";
286     gen3dmodule($modb);
287
288     p sprintf "function %s_sz() = Commitid__scale() * 0.1 * [ %d, %d ];\n",
289         $modb, 2 * ($cols * 4 - 1), 2 * (@lines * 6 - 1);
290
291     push @gtm_demo_o, <<END;
292  translate([$gtm_demo_i * st[0], $gtm_demo_j * st[1]]) {
293   difference(){
294    color("blue") translate([-e,-e]) square(${modb}_sz() + 2*[e,e]);
295    square(${modb}_sz());
296   }
297   ${modb}_2D();
298 }
299 END
300     $gtm_demo_j++;
301 }
302
303 our @demo;
304
305 sub parsefont () {
306     my %cellmap;
307     for (;;) {
308         $_ = <DATA> // die;
309         last if %cellmap && !m/\S/;
310         next unless m/\S/;
311         chomp;
312         s{^(.) }{};
313         $cellmap{$1} = $_;
314     }
315     my %chrpolys;
316     while (<DATA>) {
317         next unless m/\S/;
318         chomp;
319         my @chrs = split / /, $_;
320         <DATA> !~ m/\S/ or die;
321         foreach my $row (reverse 0..4) {
322             $_ = <DATA>;
323             chomp;
324             s{^}{ };
325             $_ .= ' ' x 8;
326             m{\S/\S} and die;
327             s{/(?=\s)}{L}g;
328             s{/(?=\S)}{r}g;
329             s{\\(?=\s)}{l}g;
330             s{\\(?=\S)}{R}g;
331             p "// $_\n";
332             foreach my $chr (@chrs) {
333                 s{^ }{} or die "$chr $_ ?";
334                 foreach my $col (0..2) {
335                     my @verts;
336                     if (s{^ }{}) {
337                     } elsif (s{^\S}{}) {
338                         my $f = $cellmap{$&};
339                         die unless $f;
340                         $f =~ s/\b\d/ sprintf '%05d', $col*2000 + $&*1025 /ge;
341                         $f =~ s/\d\b/ sprintf '%05d', $row*2000 + $&*1025 /ge;
342                         push @{ $chrpolys{$chr} }, [ split / /, $f ];
343                     } else {
344                         die "$_ ?";
345                     }
346                 }
347             }
348             die "$_ ?" if m{\S};
349         }    
350     }
351
352     my $demo = '';
353     my $democols = 6;
354     foreach my $chr (sort keys %chrpolys) {
355         my $mod = chrmodname $chr;
356         p "module $mod () {\n";
357         foreach my $poly (@{ $chrpolys{$chr} }) {
358             p " polygon([";
359             my $delim = "";
360             foreach my $pt (@$poly) {
361                 p $delim;
362                 $pt =~ s{\d{5}}{$&,};
363                 $pt =~ s{\b\d}{$&.}g;
364                 p "[$pt]";
365                 $delim = ',';
366             }
367             p "]);\n";
368         }
369         p "}\n";
370         $demo .= $chr;
371     }
372     @demo = reverse $demo =~ m{.{1,$democols}}go;
373 }
374
375 parsefont();
376
377 our $do_git; # contains may chars 'c' (count) and/or 'o' (object)
378 our $do_git_untracked = 1;
379 our $argcounter;
380
381 our @forms;
382
383 sub rjustt ($$;$) { # right justify and truncate (ie, pad and truncate at left)
384                     # always includes prefix
385     my ($sz, $whole, $prefix) = @_;
386     $prefix //= '';
387     my $lw = length $whole;
388     my $spare = $sz - $lw - (length $prefix);
389     return
390         ($spare > 0 ? (' ' x $spare) : '').
391         $prefix.
392         substr($whole, ($spare < 0 ? -$spare : 0));
393 }
394
395 sub ljustt ($$;$) {
396     my ($sz, $whole, $suffix) = @_;
397     $suffix //= '';
398     $sz -= length $suffix;
399     return sprintf "%-${sz}.${sz}s%s", $whole, $suffix;
400 }
401
402 sub genform ($@) {
403     my ($form, @lines) = @_;
404     gentextmodule($form, @lines);
405     my $f = {
406         Form => $form,
407         Chars => (length join '', @lines),
408         Lines => (scalar @lines),
409         Ambiguous => ($form =~ m/Full/ && !grep { m/\W/ } @lines),
410     };
411     push @forms, $f;
412 }
413
414 sub genform_q ($$$) {
415     my ($form, $s, $lines) = @_;
416     $gtm_demo_j++;
417     my $l = length $s;
418     return if $l % $lines;
419     my $e = $l/$lines;
420     return if $e < 2;
421     $gtm_demo_j--;
422     genform($form, $s =~ m/.{$e}/g);
423 }
424
425 sub genform_plusq ($$) {
426     my ($form, $s) = @_;
427     genform($form, $s);
428     genform_q("${form}S", $s, 2);
429     genform_q("${form}T", $s, 3);
430 }
431
432 our @gcmd;
433
434 sub gitrun_start () {
435     open F, "-|", @gcmd or die "$gcmd[0]: start: $!";
436 }
437
438 sub gitrun_done (;$) {
439     my ($errok) = @_;
440     $?=0; $!=0;
441     return if close F;
442     return if $errok;
443     die $! if $!;
444     die "@gcmd failed ($?)\n";
445 }
446
447 sub gitoutput (@) {
448     (@gcmd) = (qw(git), @_);
449     gitrun_start;
450     $_ = <F>;
451     gitrun_done;
452     defined or die "@gcmd produced no output";
453     chomp or die "@gcmd produced no final newline";
454     $_;
455 }
456
457 sub do_git () {
458     return unless $do_git;
459
460     @gcmd = qw(git status --porcelain);
461     push @gcmd, qw(--untracked=no) unless $do_git_untracked;
462
463     my $git_dirty = '';
464     gitrun_start;
465     while (<F>) {
466         if (m/^\?\?/ && $do_git_untracked) {
467             $git_dirty = '+';
468             next;
469         }
470         $git_dirty = '*';
471         last;
472     }
473     gitrun_done($git_dirty eq '*');
474
475     my $git_count;
476     my $git_object;
477
478     if ($do_git =~ m/c/) {
479         $git_count = gitoutput qw(rev-list --first-parent --count HEAD);
480     }
481     if ($do_git =~ m/o/) {
482         $git_object = gitoutput qw(rev-parse HEAD);
483     }
484
485     foreach my $sz (2..10) {
486         gentextmodule_demo_start_batch();
487
488         if (defined($git_count)) {
489             my $smallstr = rjustt($sz, $git_count, $git_dirty);
490             if (defined($git_object) && $sz >= length($git_count) + 3) {
491                 $smallstr = $git_object;
492                 $smallstr .= ($git_dirty || ' ');
493                 $smallstr .= $git_count;
494                 $smallstr = rjustt($sz, $smallstr);
495             }
496             genform_plusq("Small$sz", $smallstr);
497         }
498
499         genform_plusq("Git$sz", ljustt($sz, $git_object, $git_dirty))
500             if defined $git_object;
501
502         if (defined $git_count && defined $git_object) {
503             genform("Full".($sz*2),
504                     ljustt($sz, $git_object),
505                     rjustt($sz, $git_count, $git_dirty));
506
507             my $e = $sz;
508             genform("Full".($e*3)."T",
509                     ljustt($e*2, $git_object, $git_dirty)
510                     =~ m/.{$e}/g,
511                     rjustt($e, $git_count));
512         }
513     }
514 }
515
516 sub do_some_best ($$) {
517     my ($modname, $formre) = @_;
518     my $fullmodname = "Commitid_${modname}_2D";
519     my @argl = qw(max_sz margin=Commitid_pixelsz());
520     p "module $fullmodname(".(join ', ', @argl).") {\n";
521     my $mbs = '$Commitid_max_best_scale';
522     p " sc_max = $mbs ? $mbs : 2;\n";
523     p " sz = max_sz - 2*[margin,margin];\n";
524     my @do;
525     foreach my $f (
526         sort {
527             $b->{Chars} <=> $a->{Chars} or
528             $a->{Lines} <=> $b->{Chars}
529         }
530         grep {
531             $_->{Form} =~ m/$formre/ &&
532             !$_->{Ambiguous}
533         }
534         @forms
535     ) {
536         my $form = $f->{Form};
537         p " sz_$form = Commitid_${form}_sz();\n";
538         foreach my $rot (qw(0 1)) {
539             my $id = "${form}_r${rot}";
540             p " sc_$id = min(sc_max";
541             foreach my $xy (qw(0 1)) {
542                 p ",sz[$xy]/sz_$form","[",(($xy xor $rot)+0),"]";
543             }
544             p ");\n";
545             push @do, " if (sc_$id >= 1.0";
546             push @do, " && sc_$id >= sc_${form}_r1" if !$rot;
547             push @do, ") {\n";
548             push @do, "  translate([margin,margin]) scale(sc_$id)\n";
549             push @do, "   rotate(90) translate([0,-sz_$form"."[1]])\n" if $rot;
550             push @do, "   Commitid_${form}_2D();\n";
551             push @do, " } else";
552         }
553     }
554     push @do, <<END;
555  {
556   echo("$fullmodname could not fit anything in", max_sz);
557  }
558 END
559     p $_ foreach @do;
560     p "}\n";
561
562     gen3dmodule "Commitid_$modname", @argl;
563 }
564
565 sub do_git_best () {
566     return unless $do_git;
567
568     # Auto-computer for `best fit'
569     #
570     # We have two best fit approaches: with count, and git-object-id-only
571     #
572     # For `with count', we only ever include the git object id if the
573     # result would be unambigous.  That means that at least one space
574     # or punctuation was generated.
575     #
576     # We sort the options by firstly number of characters
577     # (decreasing), and then by number of lines (increasing) and
578     # try each one both ways round.
579
580     do_some_best('BestCount', 'Small|Full') if $do_git =~ m/c/;
581     do_some_best('BestObjid', 'Git|Full') if $do_git =~ m/o/;
582 }
583
584 while (@ARGV) {
585     $_ = shift;
586     if (m/^--(no)?-git$/) {
587         $do_git = $1 ? '' : 'co';
588     } elsif (m/^---git=objid$/i) {
589         $do_git = 'o';
590     } elsif (m/^-i$/) {
591         $do_git_untracked = 0;
592     } elsif (m/^-t(.*)$/) {
593         my $form = $1;
594         die "bad usage: -t needs string argument\n";
595         $_ = shift;
596         gentextmodule($form, split /\n/, $_);
597         $argcounter //= 0;
598     } elsif (m/^[^-]/) {
599         gentextmodule("Arg$argcounter", $_);
600         $argcounter++;
601     } else {
602         die "bad usage: unknown option \`$_'\n";
603     }
604 }
605
606 $do_git //= defined($argcounter) ? '' : 'co';
607
608 gentextmodule_demo_start_batch();
609 gentextmodule('FontDemo', @demo);
610
611 do_git();
612 do_git_best();
613
614 p "module Commitid_2DDemo(){\n";
615 p " st = Commitid__scale() * [ 10, 5 ];\n";
616 p " e  = Commitid_pixelsz();\n";
617 p $_ foreach @gtm_demo_o;
618 p "}\n";
619
620 flush STDOUT or die $!;
621 close STDOUT or die $!;
622
623 __DATA__
624
625 # 00 20 22 02
626 l 00 20 02
627 r 00 20 22
628 L 00 22 02
629 R 20 22 02
630 > 00 20 22 02 11
631 < 00 20 11 22 02
632
633 0 1 2 3 4 5 6 7 8 9
634
635 /#\  r  /#\ ##\ # # ### //  ### /#\ /#\
636 # # /#    #   # # # #   #     # # # # #
637 # #  #  /#/ ##< \## ##\ ##\  // >#< \##
638 # #  #  #     #   #   # # #  #  # #   #
639 \#/ /#\ ### ##/   # ##/ \#/  #  \#/ ##/
640
641 a b c d e f
642
643     #         #     /##
644     #   /##   # /#\ #
645 /## ##\ #   /## #r# ###
646 # # # # #   # # #/  #
647 \## ##/ \## \## \#/ #
648
649 + *
650
651     # #
652  #  \#/
653 ### ###
654  #  /#\
655     # #