chiark / gitweb /
commitid.scad.pl: Add $size parameter to gen3dmodule (nfc as yet)
[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 # COPYRIGHT, LICENCE AND LACK-OF-WARRANTY INFORMATION
224 # ===================================================
225 #
226 # This program is Free Software and a Free Cultural Work.
227 #
228 #   You can redistribute it and/or modify it under the terms of the
229 #   GNU General Public License as published by the Free Software
230 #   Foundation, either version 3 of the License, or (at your option)
231 #   any later version.
232 #
233 #   This program is distributed in the hope that it will be useful,
234 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
235 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
236 #   GNU General Public License for more details.
237 #
238 #   You should have received a copy of the GNU General Public License
239 #   along with this program.  If not, see <http://www.gnu.org/licenses/>.
240 #
241 # Alternatively, at your option:
242 #
243 #   This work is licensed under the Creative Commons
244 #   Attribution-ShareAlike 4.0 International License.
245 #
246 #   There is NO WARRANTY.
247
248
249 use strict;
250
251 $SIG{__WARN__} = sub { die @_; };
252
253 sub p { print @_ or die $!; }
254
255 p <<'END';
256 // *** AUTOGENERATED - DO NOT EDIT *** //
257 function Commitid_pixelsz() =
258   ($Commitid_pixelsz       ? $Commitid_pixelsz       : 0.8) *
259   ($Commitid_scale         ? $Commitid_scale         : 1.0);
260 function Commitid_depth() =
261   ($Commitid_depth         ? $Commitid_depth         : Commitid_pixelsz()/2) *
262   ($Commitid_depth_scale   ? $Commitid_depth_scale   : 1.0);
263 function Commitid__scale() =
264   Commitid_pixelsz() / 0.2;
265 END
266
267 sub chrmodname ($) {
268     my ($chr) = @_;
269     my $chrx = sprintf '%#x', ord $chr;
270     return "Commitid__chr_$chrx";
271 }
272
273 our $gtm_demo_i = -1;
274 our $gtm_demo_j;
275 our @gtm_demo_o;
276
277 sub gentextmodule_demo_start_batch () {
278     $gtm_demo_j = 0;
279     $gtm_demo_i++;
280 }
281
282 sub argl_formal (@) { join ', ', @_; }
283 sub argl_actual (@) { join ',', map { m/=/ ? $` : $_ } @_; }
284
285 sub gen3dmodule ($@) {
286     my ($modb,$size,@argl) = (@_);
287     $size ||= "${modb}_sz()";
288     p " // size = $size\n";
289     p "module ${modb}(".argl_formal(@argl)."){\n";
290     p " d=Commitid_depth();\n";
291     p " translate([0,0,-d]) linear_extrude(height=d*2)\n";
292     p "  ${modb}_2D(".argl_actual(@argl).");\n";
293     p "}\n";
294 }
295
296 sub gentextmodule ($@) {
297     my ($form, @lines) = @_;
298     my $modb = "Commitid_$form";
299     p "module ${modb}_2D(){\n";
300     p " // |$_|\n" foreach @lines;
301     p " scale(Commitid__scale()){\n";
302     my $y = @lines;
303     my $cols = 1;
304     foreach my $line (@lines) {
305         $y--;
306         my $x = 0;
307         foreach my $chr (split //, $line) {
308             p sprintf "  translate([%d * 0.8, %d * 1.2]) %s();\n",
309                 $x, $y, chrmodname $chr
310                 if $chr =~ m/\S/;
311             $x++;
312         }
313         $cols = $x if $x > $cols;
314     }
315     p " }\n";
316     p "}\n";
317     gen3dmodule($modb,'');
318
319     p sprintf "function %s_sz() = Commitid__scale() * 0.1 * [ %d, %d ];\n",
320         $modb, 2 * ($cols * 4 - 1), 2 * (@lines * 6 - 1);
321
322     push @gtm_demo_o, <<END;
323  translate([$gtm_demo_i * st[0], $gtm_demo_j * st[1]]) {
324   difference(){
325    color("blue") translate([-e,-e]) square(${modb}_sz() + 2*[e,e]);
326    square(${modb}_sz());
327   }
328   ${modb}_2D();
329 }
330 END
331     $gtm_demo_j++;
332 }
333
334 our @demo;
335
336 sub parsefont () {
337     my %cellmap;
338     for (;;) {
339         $_ = <DATA> // die;
340         last if %cellmap && !m/\S/;
341         next unless m/\S/;
342         chomp;
343         s{^(.) }{};
344         $cellmap{$1} = $_;
345     }
346     my %chrpolys;
347     while (<DATA>) {
348         next unless m/\S/;
349         chomp;
350         my @chrs = split / /, $_;
351         <DATA> !~ m/\S/ or die;
352         foreach my $row (reverse 0..4) {
353             $_ = <DATA>;
354             chomp;
355             s{^}{ };
356             $_ .= ' ' x 8;
357             m{\S/\S} and die;
358             s{/(?=\s)}{L}g;
359             s{/(?=\S)}{r}g;
360             s{\\(?=\s)}{l}g;
361             s{\\(?=\S)}{R}g;
362             p "// $_\n";
363             foreach my $chr (@chrs) {
364                 s{^ }{} or die "$chr $_ ?";
365                 foreach my $col (0..2) {
366                     my @verts;
367                     if (s{^ }{}) {
368                     } elsif (s{^\S}{}) {
369                         my $f = $cellmap{$&};
370                         die unless $f;
371                         $f =~ s/\b\d/ sprintf '%05d', $col*2000 + $&*1025 /ge;
372                         $f =~ s/\d\b/ sprintf '%05d', $row*2000 + $&*1025 /ge;
373                         push @{ $chrpolys{$chr} }, [ split / /, $f ];
374                     } else {
375                         die "$_ ?";
376                     }
377                 }
378             }
379             die "$_ ?" if m{\S};
380         }    
381     }
382
383     my $demo = '';
384     my $democols = 6;
385     foreach my $chr (sort keys %chrpolys) {
386         my $mod = chrmodname $chr;
387         p "module $mod () {\n";
388         foreach my $poly (@{ $chrpolys{$chr} }) {
389             p " polygon([";
390             my $delim = "";
391             foreach my $pt (@$poly) {
392                 p $delim;
393                 $pt =~ s{\d{5}}{$&,};
394                 $pt =~ s{\b\d}{$&.}g;
395                 p "[$pt]";
396                 $delim = ',';
397             }
398             p "]);\n";
399         }
400         p "}\n";
401         $demo .= $chr;
402     }
403     @demo = reverse $demo =~ m{.{1,$democols}}go;
404 }
405
406 parsefont();
407
408 our $do_git; # contains may chars 'c' (count) and/or 'o' (object)
409 our $do_git_untracked = 1;
410 our $argcounter;
411
412 our @forms;
413
414 sub rjustt ($$;$) { # right justify and truncate (ie, pad and truncate at left)
415                     # always includes prefix
416     my ($sz, $whole, $prefix) = @_;
417     $prefix //= '';
418     my $lw = length $whole;
419     my $spare = $sz - $lw - (length $prefix);
420     return
421         ($spare > 0 ? (' ' x $spare) : '').
422         $prefix.
423         substr($whole, ($spare < 0 ? -$spare : 0));
424 }
425
426 sub ljustt ($$;$) {
427     my ($sz, $whole, $suffix) = @_;
428     $suffix //= '';
429     $sz -= length $suffix;
430     return sprintf "%-${sz}.${sz}s%s", $whole, $suffix;
431 }
432
433 sub genform ($@) {
434     my ($form, @lines) = @_;
435     gentextmodule($form, @lines);
436     my $f = {
437         Form => $form,
438         Chars => (length join '', @lines),
439         Lines => (scalar @lines),
440         Ambiguous => ($form =~ m/Full/ && !grep { m/\W/ } @lines),
441     };
442     push @forms, $f;
443 }
444
445 sub genform_q ($$$) {
446     my ($form, $s, $lines) = @_;
447     $gtm_demo_j++;
448     my $l = length $s;
449     return if $l % $lines;
450     my $e = $l/$lines;
451     return if $e < 2;
452     $gtm_demo_j--;
453     genform($form, $s =~ m/.{$e}/g);
454 }
455
456 sub genform_plusq ($$) {
457     my ($form, $s) = @_;
458     genform($form, $s);
459     genform_q("${form}S", $s, 2);
460     genform_q("${form}T", $s, 3);
461 }
462
463 our @gcmd;
464
465 sub gitrun_start () {
466     open F, "-|", @gcmd or die "$gcmd[0]: start: $!";
467 }
468
469 sub gitrun_done (;$) {
470     my ($errok) = @_;
471     $?=0; $!=0;
472     return if close F;
473     return if $errok;
474     die $! if $!;
475     die "@gcmd failed ($?)\n";
476 }
477
478 sub gitoutput (@) {
479     (@gcmd) = (qw(git), @_);
480     gitrun_start;
481     $_ = <F>;
482     gitrun_done;
483     defined or die "@gcmd produced no output";
484     chomp or die "@gcmd produced no final newline";
485     $_;
486 }
487
488 sub do_git () {
489     return unless $do_git;
490
491     @gcmd = qw(git status --porcelain);
492     push @gcmd, qw(--untracked=no) unless $do_git_untracked;
493
494     my $git_dirty = '';
495     gitrun_start;
496     while (<F>) {
497         if (m/^\?\?/ && $do_git_untracked) {
498             $git_dirty = '+';
499             next;
500         }
501         $git_dirty = '*';
502         last;
503     }
504     gitrun_done($git_dirty eq '*');
505
506     my $git_count;
507     my $git_object;
508
509     if ($do_git =~ m/c/) {
510         $git_count = gitoutput qw(rev-list --first-parent --count HEAD);
511     }
512     if ($do_git =~ m/o/) {
513         $git_object = gitoutput qw(rev-parse HEAD);
514     }
515     print STDERR join ' ', map { $_ // '?' }
516         "-- commitid", $git_object, $git_dirty, $git_count, "--\n";
517
518     foreach my $sz (2..10) {
519         gentextmodule_demo_start_batch();
520
521         if (defined($git_count)) {
522             my $smallstr = rjustt($sz, $git_count, $git_dirty);
523             if (defined($git_object) && $sz >= length($git_count) + 3) {
524                 $smallstr = $git_object;
525                 $smallstr .= ($git_dirty || ' ');
526                 $smallstr .= $git_count;
527                 $smallstr = rjustt($sz, $smallstr);
528             }
529             genform_plusq("Small$sz", $smallstr);
530         }
531
532         genform_plusq("Git$sz", ljustt($sz, $git_object, $git_dirty))
533             if defined $git_object;
534
535         if (defined $git_count && defined $git_object) {
536             genform("Full".($sz*2),
537                     ljustt($sz, $git_object),
538                     rjustt($sz, $git_count, $git_dirty));
539
540             my $e = $sz;
541             genform("Full".($e*3)."T",
542                     ljustt($e*2, $git_object, $git_dirty)
543                     =~ m/.{$e}/g,
544                     rjustt($e, $git_count));
545         }
546     }
547 }
548
549 sub do_some_best ($$) {
550     my ($modname, $formre) = @_;
551     my $fullmodname = "Commitid_${modname}_2D";
552     my @argl = qw(max_sz margin=Commitid_pixelsz());
553     p "module $fullmodname(".argl_formal(@argl).") {\n";
554     my $mbs = '$Commitid_max_best_scale';
555     p " sc_max = $mbs ? $mbs : 2;\n";
556     p " sz = max_sz - 2*[margin,margin];\n";
557     my @do;
558     foreach my $f (
559         sort {
560             $b->{Chars} <=> $a->{Chars} or
561             $a->{Lines} <=> $b->{Chars}
562         }
563         grep {
564             $_->{Form} =~ m/$formre/ &&
565             !$_->{Ambiguous}
566         }
567         @forms
568     ) {
569         my $form = $f->{Form};
570         p " sz_$form = Commitid_${form}_sz();\n";
571         foreach my $rot (qw(0 1)) {
572             my $id = "${form}_r${rot}";
573             p " sc_$id = min(sc_max";
574             foreach my $xy (qw(0 1)) {
575                 p ",sz[$xy]/sz_$form","[",(($xy xor $rot)+0),"]";
576             }
577             p ");\n";
578             push @do, " if (sc_$id >= 1.0";
579             push @do, " && sc_$id >= sc_${form}_r1" if !$rot;
580             push @do, ") {\n";
581             push @do, "  translate([margin,margin]) scale(sc_$id)\n";
582             push @do, "   rotate(90) translate([0,-sz_$form"."[1]])\n" if $rot;
583             push @do, "   Commitid_${form}_2D();\n";
584             push @do, " } else";
585         }
586     }
587     push @do, <<END;
588  {
589   echo("$fullmodname could not fit anything in", max_sz);
590  }
591 END
592     p $_ foreach @do;
593     p "}\n";
594
595     gen3dmodule "Commitid_$modname", 'max_sz', @argl;
596 }
597
598 sub do_git_best () {
599     return unless $do_git;
600
601     # Auto-computer for `best fit'
602     #
603     # We have two best fit approaches: with count, and git-object-id-only
604     #
605     # For `with count', we only ever include the git object id if the
606     # result would be unambigous.  That means that at least one space
607     # or punctuation was generated.
608     #
609     # We sort the options by firstly number of characters
610     # (decreasing), and then by number of lines (increasing) and
611     # try each one both ways round.
612
613     do_some_best('BestCount', 'Small|Full') if $do_git =~ m/c/;
614     do_some_best('BestObjid', 'Git|Full') if $do_git =~ m/o/;
615 }
616
617 while (@ARGV) {
618     $_ = shift;
619     if (m/^--(no)?-git$/) {
620         $do_git = $1 ? '' : 'co';
621     } elsif (m/^---git=objid$/i) {
622         $do_git = 'o';
623     } elsif (m/^-i$/) {
624         $do_git_untracked = 0;
625     } elsif (m/^-t(.*)$/) {
626         my $form = $1;
627         die "bad usage: -t needs string argument\n";
628         $_ = shift;
629         gentextmodule($form, split /\n/, $_);
630         $argcounter //= 0;
631     } elsif (m/^[^-]/) {
632         gentextmodule("Arg$argcounter", $_);
633         $argcounter++;
634     } else {
635         die "bad usage: unknown option \`$_'\n";
636     }
637 }
638
639 $do_git //= defined($argcounter) ? '' : 'co';
640
641 gentextmodule_demo_start_batch();
642 gentextmodule('FontDemo', @demo);
643
644 do_git();
645 do_git_best();
646
647 p "module Commitid_2DDemo(){\n";
648 p " st = Commitid__scale() * [ 10, 5 ];\n";
649 p " e  = Commitid_pixelsz();\n";
650 p $_ foreach @gtm_demo_o;
651 p "}\n";
652
653 flush STDOUT or die $!;
654 close STDOUT or die $!;
655
656 __DATA__
657
658 # 00 20 22 02
659 l 00 20 02
660 r 00 20 22
661 L 00 22 02
662 R 20 22 02
663 > 00 20 22 02 11
664 < 00 20 11 22 02
665
666 0 1 2 3 4 5 6 7 8 9
667
668 /#\  r  /#\ ##\ # # ### /#/ ### /#\ /#\
669 # # /#    #   # # # #   #     # # # # #
670 # #  #  /#/ ##< \## ##\ ##\  // >#< \##
671 # #  #  #     #   #   # # #  #  # #   #
672 \#/ /#\ ### ##/   # ##/ \#/  #  \#/ ##/
673
674 a b c d e f
675
676     #         #     /##
677     #   /##   # /#\ #
678 /## ##\ #   /## #r# ###
679 # # # # #   # # #/  #
680 \## ##/ \## \## \#/ #
681
682 + *
683
684     # #
685  #  \#/
686 ### ###
687  #  /#\
688     # #