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.
10 # .../commitid.scad.pl [OPTION...] [STRING...] >commitid.scad.new \
11 # && mv -f commitid.scad.new commitid.scad
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
18 # See below for details. You probably want these two sections, as a
19 # quick starting point:
20 # General form of provided openscad modules
23 # We can also generate models of short mainly-numeric strings
24 # specified on the command line.
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'.
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').
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.
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:
54 # Dynamic variables for configuration
55 # -----------------------------------
57 # We honour the following variables to control various scaling factors:
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*
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.)
71 # Non-`module'-specific functions
72 # -------------------------------
74 # We provide the following functions (which depend on the config
75 # variables, but not on anything else) and compute useful values:
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)
81 # General form of provided openscad modules
82 # -----------------------------------------
84 # module Commitid_MODULE_2D(...) Collection of polygons forming characters
85 # module Commitid_MODULE(...) The above, extruded up and down in Z
86 # module Commitid_MODULE_M_2D(...) Mirror writing
87 # module Commitid_MODULE_M(...) 3D mirror writing
88 # function Commitid_MODULE_sz() A 2-vector giving the X,Y size
90 # Except for *Best* modules, the XY origin is in the bottom left
91 # corner without any margin. Likewise Commitid_MODULE_sz does not
94 # For 3D versions, the model is 2*depth deep and the XY plane bisects
95 # the model. This means it's convenient to either add or subtract from
96 # a workpiece whose face is in the XY plane.
98 # The _M versions are provided to avoid doing inconvenient translation
99 # and rotation to get the flipped version in the right place.
102 # Autoscaling modules
103 # -------------------
105 # These modules take a specification of the available XY space, and
106 # select and generate a suitable specific identification layout:
108 # module Commitid_BestCount_2D (max_sz, margin=Commitid_pixelsz())
109 # module Commitid_BestCount (max_sz, margin=Commitid_pixelsz())
110 # module Commitid_BestCount_M_2D(max_sz, margin=Commitid_pixelsz())
111 # module Commitid_BestCount_M (max_sz, margin=Commitid_pixelsz())
112 # module Commitid_BestObjid_2D (max_sz, margin=Commitid_pixelsz())
113 # module Commitid_BestObjid (max_sz, margin=Commitid_pixelsz())
114 # module Commitid_BestObjid_M_2D(max_sz, margin=Commitid_pixelsz())
115 # module Commitid_BestObjid_M (max_sz, margin=Commitid_pixelsz())
117 # max_sz should be [x,y].
119 # BestCount includes (as much as it can of) the git commit count,
121 # git rev-list --first-parent --count HEAD
122 # (and it may include some of the git revision ID too).
124 # BestObjid includes as much as it can of the git commit object hash,
125 # and never includes any of the count.
127 # All of these will autoscale and autorotate the selected model, and
128 # will include an internal margin of the specified size (by default,
129 # one pixel around each edge). If no margin is needed, pass margin=0.
131 # There are no `function Commitid_Best*_sz'. If they existed they
132 # would simply return max_sz.
138 # In general the output, although it may be over multiple lines,
139 # is always in this order
140 # git commit object id (hash)
144 # Not all layouts have all these parts. The commit object id may
145 # sometimes be split over multiple lines, but the count will not be.
146 # If both commit id and commit count appear they will be separated
147 # by (at least) a newline, or a dirty indicator, or a space.
149 # The commit id is truncated to fit, from the right.
151 # The commit count is truncated from the _left_, leaving the least
152 # significant decimal digits.
154 # The dirty indicator can be
156 # * meaning the working tree contains differences from HEAD
158 # + meaning the working tree contains untracked files
159 # (ie files you have failed to `git add' and also failed
160 # to add to gitignore). (But see the -i option.)
166 # If you want to control the exact layout (and make space for it in
167 # your design), you can use these:
169 # module Commitid_LAYOUT_2D()
170 # module Commitid_LAYOUT()
171 # module Commitid_LAYOUT_M_2D()
172 # module Commitid_LAYOUT_M()
173 # function Commitid_LAYOUT_sz()
175 # Here LAYOUT is one of the following (giving for example, `module
176 # Commitid_Full8_2D'). In the examples, we will assume that the tree
177 # is dirty, the commit count is 123456, and the commit object id
178 # starts abcdeffedbcaabcdef... In the examples `_' shows where a
179 # space would be printed.
181 # Small2 Small3 ... Small10
182 # A single line containing as much of the count will fit, eg:
185 # The objectid is included if more than one character of of it
186 # will fit without makign the output ambiguous:
189 # Small2S Small4S ... Small10S
191 # Same as Small but split into two lines (S)
192 # or three lines (T). Eg:
193 # Small4S *4 Small6T _*
196 # Git2 Git3 ... Git10
197 # Git4S Git6S ... Git10S
199 # Just the commit object hash, in one, two (S) or three (T)
203 # Full4 Full6 ... Full20:
204 # The commit object hash plus the commit count, on
205 # separate lines, eg:
206 # Full6 abcdef Full8 abcdeffe
209 # Full6T Full9T ... Full30T
210 # As Full but the commit object id is split over two lines
211 # producing a 3-line layout, eg:
212 # Full9T abc Full21T abcdeff
221 # A demonstration of the built-in 18-character font
225 # Strings passed on command line (without -t, or bare -t,
226 # rather than with -tLAYOUT).
230 # Generated by passing -tLAYOUT on the command line.
234 # COPYRIGHT, LICENCE AND LACK-OF-WARRANTY INFORMATION
235 # ===================================================
237 # This program is Free Software and a Free Cultural Work.
239 # You can redistribute it and/or modify it under the terms of the
240 # GNU General Public License as published by the Free Software
241 # Foundation, either version 3 of the License, or (at your option)
244 # This program is distributed in the hope that it will be useful,
245 # but WITHOUT ANY WARRANTY; without even the implied warranty of
246 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
247 # GNU General Public License for more details.
249 # You should have received a copy of the GNU General Public License
250 # along with this program. If not, see <http://www.gnu.org/licenses/>.
252 # Alternatively, at your option:
254 # This work is licensed under the Creative Commons
255 # Attribution-ShareAlike 4.0 International License.
257 # There is NO WARRANTY.
262 $SIG{__WARN__} = sub { die @_; };
264 sub p { print @_ or die $!; }
267 // *** AUTOGENERATED - DO NOT EDIT *** //
268 function Commitid_pixelsz() =
269 ($Commitid_pixelsz ? $Commitid_pixelsz : 0.8) *
270 ($Commitid_scale ? $Commitid_scale : 1.0);
271 function Commitid_depth() =
272 ($Commitid_depth ? $Commitid_depth : Commitid_pixelsz()/2) *
273 ($Commitid_depth_scale ? $Commitid_depth_scale : 1.0);
274 function Commitid__scale() =
275 Commitid_pixelsz() / 0.2;
280 my $chrx = sprintf '%#x', ord $chr;
281 return "Commitid__chr_$chrx";
284 our $gtm_demo_i = -1;
288 sub gentextmodule_demo_start_batch () {
293 sub argl_formal (@) { join ', ', @_; }
294 sub argl_actual (@) { join ',', map { m/=/ ? $` : $_ } @_; }
296 sub gen3dmodule ($@) {
297 my ($modb,$size,@argl) = (@_);
298 $size ||= "${modb}_sz()";
299 p "module ${modb}_M_2D(".argl_formal(@argl)."){\n";
300 p " translate([${size}[0],0])\n";
301 p " mirror([1,0,0])\n";
302 p " ${modb}_2D(".argl_actual(@argl).");\n";
304 foreach my $mir ('','_M') {
305 my $mm = "${modb}${mir}";
306 p "module ${mm}(".argl_formal(@argl)."){\n";
307 p " d=Commitid_depth();\n";
308 p " translate([0,0,-d]) linear_extrude(height=d*2)\n";
309 p " ${mm}_2D(".argl_actual(@argl).");\n";
314 sub gentextmodule ($@) {
315 my ($form, @lines) = @_;
316 my $modb = "Commitid_$form";
317 p "module ${modb}_2D(){\n";
318 p " // |$_|\n" foreach @lines;
319 p " scale(Commitid__scale()){\n";
322 foreach my $line (@lines) {
325 foreach my $chr (split //, $line) {
326 p sprintf " translate([%d * 0.8, %d * 1.2]) %s();\n",
327 $x, $y, chrmodname $chr
331 $cols = $x if $x > $cols;
335 gen3dmodule($modb,'');
337 p sprintf "function %s_sz() = Commitid__scale() * 0.1 * [ %d, %d ];\n",
338 $modb, 2 * ($cols * 4 - 1), 2 * (@lines * 6 - 1);
340 push @gtm_demo_o, <<END;
341 translate([$gtm_demo_i * st[0], $gtm_demo_j * st[1]]) {
343 color("blue") translate([-e,-e]) square(${modb}_sz() + 2*[e,e]);
344 square(${modb}_sz());
358 last if %cellmap && !m/\S/;
368 my @chrs = split / /, $_;
369 <DATA> !~ m/\S/ or die;
370 foreach my $row (reverse 0..4) {
381 foreach my $chr (@chrs) {
382 s{^ }{} or die "$chr $_ ?";
383 foreach my $col (0..2) {
387 my $f = $cellmap{$&};
389 $f =~ s/\b\d/ sprintf '%05d', $col*2000 + $&*1025 /ge;
390 $f =~ s/\d\b/ sprintf '%05d', $row*2000 + $&*1025 /ge;
391 push @{ $chrpolys{$chr} }, [ split / /, $f ];
403 foreach my $chr (sort keys %chrpolys) {
404 my $mod = chrmodname $chr;
405 p "module $mod () {\n";
406 foreach my $poly (@{ $chrpolys{$chr} }) {
409 foreach my $pt (@$poly) {
411 $pt =~ s{\d{5}}{$&,};
412 $pt =~ s{\b\d}{$&.}g;
421 @demo = reverse $demo =~ m{.{1,$democols}}go;
426 our $do_git; # contains may chars 'c' (count) and/or 'o' (object)
427 our $do_git_untracked = 1;
431 our %included; # 0 = not at all; 1 = truncated; 2 = full
434 # right justify and truncate (ie, pad and truncate at left)
435 # always includes prefix
436 # sets $included{$what}
437 my ($sz, $what, $whole, $prefix) = @_;
439 my $lw = length $whole;
440 my $spare = $sz - $lw - (length $prefix);
441 $included{$what}= 1 + ($spare > 0);
443 ($spare > 0 ? (' ' x $spare) : '').
445 substr($whole, ($spare < 0 ? -$spare : 0));
449 my ($sz, $what, $whole, $suffix) = @_;
451 $sz -= length $suffix;
452 $included{$what} = 1 + ($sz >= length $whole);
453 return sprintf "%-${sz}.${sz}s%s", $whole, $suffix;
457 $included{$_}=0 foreach qw(Objid Count);
461 my ($form, @lines) = @_;
462 gentextmodule($form, @lines);
465 Chars => (length join '', @lines),
466 Lines => (scalar @lines),
467 Ambiguous => ($form =~ m/Full/ && !grep { m/\W/ } @lines),
468 Included => { %included },
473 sub genform_q ($$$) {
474 my ($form, $s, $lines) = @_;
477 return if $l % $lines;
481 genform($form, $s =~ m/.{$e}/g);
484 sub genform_plusq ($$) {
487 genform_q("${form}S", $s, 2);
488 genform_q("${form}T", $s, 3);
493 sub gitrun_start () {
494 open F, "-|", @gcmd or die "$gcmd[0]: start: $!";
497 sub gitrun_done (;$) {
503 die "@gcmd failed ($?)\n";
507 (@gcmd) = (qw(git), @_);
511 defined or die "@gcmd produced no output";
512 chomp or die "@gcmd produced no final newline";
517 return unless $do_git;
519 @gcmd = qw(git status --porcelain);
520 push @gcmd, qw(--untracked=no) unless $do_git_untracked;
525 if (m/^\?\?/ && $do_git_untracked) {
532 gitrun_done($git_dirty eq '*');
537 if ($do_git =~ m/c/) {
538 $git_count = gitoutput qw(rev-list --first-parent --count HEAD);
540 if ($do_git =~ m/o/) {
541 $git_object = gitoutput qw(rev-parse HEAD);
543 print STDERR join ' ', map { $_ // '?' }
544 "-- commitid", $git_object, $git_dirty, $git_count, "--\n";
546 foreach my $sz (2..10) {
547 gentextmodule_demo_start_batch();
549 if (defined($git_count)) {
551 my $smallstr = rjustt($sz, 'Count', $git_count, $git_dirty);
552 my $forgitobj = $sz - length($git_count) - 1;
553 if (defined($git_object) && $forgitobj >= 2) {
554 $smallstr = ljustt($forgitobj, 'Objid', $git_object).
558 genform_plusq("Small$sz", $smallstr);
562 genform_plusq("Git$sz", ljustt($sz, 'Objid', $git_object, $git_dirty))
563 if defined $git_object;
565 if (defined $git_count && defined $git_object) {
567 genform("Full".($sz*2),
568 ljustt($sz, 'Objid', $git_object),
569 rjustt($sz, 'Count', $git_count, $git_dirty));
573 genform("Full".($e*3)."T",
574 ljustt($e*2, 'Objid', $git_object, $git_dirty)
576 rjustt($e, 'Count', $git_count));
581 sub do_some_best ($$) {
582 my ($bestwhat, $formre) = @_;
583 my $modname = "Best$bestwhat";
584 my $fullmodname = "Commitid_${modname}_2D";
585 my @argl = qw(max_sz margin=Commitid_pixelsz());
586 p "module $fullmodname(".argl_formal(@argl).") {\n";
587 my $mbs = '$Commitid_max_best_scale';
588 p " sc_max = $mbs ? $mbs : 2;\n";
589 p " sz = max_sz - 2*[margin,margin];\n";
593 $b->{Included}{$bestwhat} <=> $a->{Included}{$bestwhat} or
594 $b->{Chars} <=> $a->{Chars} or
595 $a->{Lines} <=> $b->{Chars}
598 $_->{Form} =~ m/$formre/ &&
603 my $form = $f->{Form};
604 p " sz_$form = Commitid_${form}_sz();\n";
605 foreach my $rot (qw(0 1)) {
606 my $id = "${form}_r${rot}";
607 p " sc_$id = min(sc_max";
608 foreach my $xy (qw(0 1)) {
609 p ",sz[$xy]/sz_$form","[",(($xy xor $rot)+0),"]";
612 push @do, " if (sc_$id >= 1.0";
613 push @do, " && sc_$id >= sc_${form}_r1" if !$rot;
615 push @do, " translate([margin,margin]) scale(sc_$id)\n";
616 push @do, " rotate(90) translate([0,-sz_$form"."[1]])\n" if $rot;
617 push @do, " Commitid_${form}_2D();\n";
623 echo("$fullmodname could not fit anything in", max_sz);
629 gen3dmodule "Commitid_$modname", 'max_sz', @argl;
633 return unless $do_git;
635 # Auto-computer for `best fit'
637 # We have two best fit approaches: with count, and git-object-id-only
639 # For `with count', we only ever include the git object id if the
640 # result would be unambigous. That means that at least one space
641 # or punctuation was generated.
643 # We sort the options by firstly number of characters
644 # (decreasing), and then by number of lines (increasing) and
645 # try each one both ways round.
647 do_some_best('Count', 'Small|Full') if $do_git =~ m/c/;
648 do_some_best('Objid', 'Git|Full') if $do_git =~ m/o/;
653 if (m/^--(no)?-git$/) {
654 $do_git = $1 ? '' : 'co';
655 } elsif (m/^---git=objid$/i) {
658 $do_git_untracked = 0;
659 } elsif (m/^-t(.*)$/) {
661 die "bad usage: -t needs string argument\n";
663 gentextmodule($form, split /\n/, $_);
666 gentextmodule("Arg$argcounter", $_);
669 die "bad usage: unknown option \`$_'\n";
673 $do_git //= defined($argcounter) ? '' : 'co';
675 gentextmodule_demo_start_batch();
676 gentextmodule('FontDemo', @demo);
681 p "module Commitid_2DDemo(){\n";
682 p " st = Commitid__scale() * [ 10, 5 ];\n";
683 p " e = Commitid_pixelsz();\n";
684 p $_ foreach @gtm_demo_o;
687 flush STDOUT or die $!;
688 close STDOUT or die $!;
702 /#\ r /#\ ##\ # # ### /#/ ### /#\ /#\
703 # # /# # # # # # # # # # # #
704 # # # /#/ ##< \## ##\ ##\ // >#< \##
705 # # # # # # # # # # # # #
706 \#/ /#\ ### ##/ # ##/ \#/ # \#/ ##/
712 /## ##\ # /## #r# ###
714 \## ##/ \## \## \#/ #