polyhedra.tcl: plain Tcl and TIP 759

The rotating polyhedra demo by Gerard Sookahet (2005), on the left as it was, and on the right with its maths written with the syntax of TIP 759. It takes up, proc by proc, the comparison made for Calc; the switch shows the Calc version in the right column instead, with the same left column.

TIP 759 features used: [( … )] expression substitution, native lists (a, b, c), TIP 282 assignments x = …;, expression scripts {( … )} as the body of proc, foreach…, tuple assignments (x, y, z) = $V;, and raw commands, without brackets, for the commands the expression parser knows (global scx scy vdist;, n = llength $lcoords;, lindex $M1 $i 0 * lindex $M2 0 $j); the procs of the demo keep their brackets. And user operators: a proc tcl::mathop::crossProd is used as $U \crossProd $V, with the precedence of *. Everything is parsed by Tcl and compiled with the proc: nothing to transform afterwards.

ProcLines: originalTIP 759TIP 759, operators in tcllibCalcCharacters: originalTIP 759TIP 759, operators in tcllibCalc
Barycenter13448201107 -47 %107 -47 %125 -38 %
CrossProduct53in tcllib712984 -35 %in tcllib86 -33 %
MatrixVectorProduct84in tcllib930594 -69 %in tcllib153 -50 %
MatrixProduct137in tcllib13279168 -40 %in tcllib270 -3 %
MatrixRotation28191922765426 -44 %426 -44 %424 -45 %
NormalVector19141419796318 -60 %318 -60 %452 -43 %
Projection1011in tcllib13432247 -43 %in tcllib293 -32 %
Transformations19141418492403 -18 %403 -18 %442 -10 %
Intensity18151518563299 -47 %299 -47 %378 -33 %
DisplayModel28232324595579 -3 %579 -3 %692 +16 %
Vector operators12in tcllib678in tcllib
Calc-specific code211034
package require math::linearalgebra135
Total1611269017245573403 -25 %2167 -52 %4349 -5 %

The columns TIP 759, operators in tcllib count the demo as it would be if the ten operators came from math::linearalgebra (see below the speed table): the definitions of \crossProd, \matrixProd, \matrixVectorProd, \project and the vector operators leave the file, and one package require line takes their place. Characters are counted with the white space the syntax needs, and only that: one blank between two words of a command (set a 1 counts 7), none for indentation, none around an operator in an expression ($X + $x counts as $X+$x), and one character for a line end that ends a command. Comments count, with one blank between words, and their line end. To check these rules, the code of each column was rewritten in this minimal form and run: the original, Calc (with its colon package) and TIP 759 give the same results as before. The Calc column of DisplayModel includes two changes that are not about the maths.

Speed: original and TIP 759

ProcOriginal, µs per callTIP 759TIP 759 isTIP 759, operators in Cthen
Barycenter2.365.682.4× slower3.101.3× slower
CrossProduct1.267.355.9× slower1.061.2× faster
MatrixVectorProduct1.924.982.6× slower2.171.1× slower
MatrixProduct21.547.332.9× faster7.392.9× faster
MatrixRotation54.0117.073.2× faster16.893.2× faster
NormalVector11.3259.265.2× slower10.81about the same
Projection2.285.372.4× slower2.701.2× slower
Transformations71.9179.62about the same42.211.7× faster
Intensity7.057.29about the same4.701.5× faster

Best of 2 × 5 runs of 20 000 calls each, on the branch tip-759h-tcl91-user-op built with -O2, the data a cube (8 vertices, 6 faces). The operators are timed as expr {$U \crossProd $V} and expr {$M \matrixProd $M}. DisplayModel needs Tk and is not timed.

The product of matrices is three times faster: lmap goes over the values, where the original updates each cell by index with lset in three loops. MatrixRotation, which calls it twice, gains as much.

The rest of the TIP 759 code is written with vector operators, as in a textbook: the cross product is the axial vector of the antisymmetric part of a tensor product, a matrix is transposed into column vectors for dot products. This is the most readable form, and here the slowest, but the cause is not the syntax: the operators are procs, and a proc call costs about a microsecond, several per operation, where the original wrote the arithmetic inline. The last two columns measure the same TIP 759 code with five operators written in C (\add, \sub, \dot, \crossProd and \transpose, a prototype of about 80 lines loaded as an extension into tcl::mathop; nothing else changes): most procs are then as fast as the original or faster, and a frame of the animation (Transformations, then Intensity) takes 47 µs for a cube, against 79 µs with the original, and 87 µs with the operators as procs. Barycenter and Projection stay a little slower than the original, mostly because lmap and the operators build a new list for each point. A geometry library compiled in C, on a compact representation of vectors of numbers, would remove that too.

Where the operators would live. None of these operators is specific to the demo: \add, \sub, \dot, \transpose, \tensorProd, \axial, \crossProd, \matrixProd, \matrixVectorProd, and even \project, are the common vocabulary of linear algebra and 3D graphics. Their definitions could be provided by the Tcl library math::linearalgebra of tcllib, as procs of tcl::mathop, possibly compiled in C. A single line, package require math::linearalgebra, would then define them all beforehand: the "Vector operators" section would shrink to that line, and the code of the demo would run at the speed of the C column.

changed line, original its replacement expression code: [( … )], {( … )} Calc code: :, its block, [: … ]
OriginalWith TIP 759With Calc

Barycenter −13 +4 −8 +3 2.4 µs → 5.7 µs, 2.4× slower

The barycenter as it is defined: the sum of the points, divided by their number. The points are added as vectors with the operator \add, so there are no separate x and y, and the same code works in 3D. Slower, as each \add is a proc call (see the speed table).
15proc Barycenter {lcoords} {
16 set X 0
17 set Y 0
18 set n [llength $lcoords]
19
20 foreach vtx $lcoords {
21 foreach {x y} $vtx {
22 set X [expr {$X + $x}]
23 set Y [expr {$Y + $y}]
24 }
25 }
26 return [list [expr {$X/$n}] [expr {$Y/$n}]]
27}
15proc Barycenter {lcoords {S {0 0}}} {(
16 foreach P $lcoords {( S = $S \add $P )};
17 lmap s $S {( $s / llength $lcoords )}
18)}
15proc Barycenter {lcoords} {
16 set X 0
17 set Y 0
18 set n [llength $lcoords]
19
20 foreach vtx $lcoords {
21 foreach {x y} $vtx {
22 set X [expr {$X + $x}]
23 set Y [expr {$Y + $y}]
24 }
25 }
26 return [list [expr {$X/$n}] [expr {$Y/$n}]]
27}
18proc Barycenter {lcoords} {
19 : { X = 0; Y = 0; n = llength(lcoords) }
20 
21 foreach vtx $lcoords {
22 : { (x, y) = vtx; X = X + x; Y = Y + y }
23 }
24 : list(X/n, Y/n)
25}

CrossProduct −5 +3 −3 +5 1.3 µs → 7.4 µs, 5.9× slower

CrossProduct becomes the operator \crossProd, defined as in a textbook: the cross product is the axial vector of the antisymmetric part of the tensor product, \axial (($V \tensorProd $U) \sub ($U \tensorProd $V)). It takes two vectors instead of six numbers. The operators it uses are defined with the others, under Vector operators.
29proc CrossProduct {x1 y1 z1 x2 y2 z2} {
30 return [list [expr {$y1*$z2 - $y2*$z1}] \
31 [expr {$z1*$x2 - $z2*$x1}] \
32 [expr {$x1*$y2 - $x2*$y1}]]
33}
20proc tcl::mathop::crossProd {U V} {(
21 \axial (($V \tensorProd $U) \sub ($U \tensorProd $V))
22)}
29proc CrossProduct {x1 y1 z1 x2 y2 z2} {
30 return [list [expr {$y1*$z2 - $y2*$z1}] \
31 [expr {$z1*$x2 - $z2*$x1}] \
32 [expr {$x1*$y2 - $x2*$y1}]]
33}
27proc CrossProduct {x1 y1 z1 x2 y2 z2} {
28 : {
29 list(y1*z2 - y2*z1,
30 z1*x2 - z2*x1,
31 x1*y2 - x2*y1)
32 }
33}

MatrixVectorProduct −8 +4 −6 +7 1.9 µs → 5.0 µs, 2.6× slower

MatrixVectorProduct becomes the operator \matrixVectorProd: $M \matrixVectorProd $V. The matrix is transposed into its three column vectors m, n, o (\transpose, a unary operator), and the result is the three dot products with V. The original computes this transposed product: its first coordinate is m00*x + m10*y + m20*z.
39proc MatrixVectorProduct {M V} {
40 set x [lindex $V 0]
41 set y [lindex $V 1]
42 set z [lindex $V 2]
43 return [list [expr {[lindex $M 0 0]*$x+[lindex $M 1 0]*$y+[lindex $M 2 0]*$z}] \
44 [expr {[lindex $M 0 1]*$x+[lindex $M 1 1]*$y+[lindex $M 2 1]*$z}] \
45 [expr {[lindex $M 0 2]*$x+[lindex $M 1 2]*$y+[lindex $M 2 2]*$z}]]
46}
28proc tcl::mathop::matrixVectorProd {M V} {(
29 (m, n, o) = \transpose $M;
30 ($V \dot $m, $V \dot $n, $V \dot $o)
31)}
39proc MatrixVectorProduct {M V} {
40 set x [lindex $V 0]
41 set y [lindex $V 1]
42 set z [lindex $V 2]
43 return [list [expr {[lindex $M 0 0]*$x+[lindex $M 1 0]*$y+[lindex $M 2 0]*$z}] \
44 [expr {[lindex $M 0 1]*$x+[lindex $M 1 1]*$y+[lindex $M 2 1]*$z}] \
45 [expr {[lindex $M 0 2]*$x+[lindex $M 1 2]*$y+[lindex $M 2 2]*$z}]]
46}
39proc MatrixVectorProduct {M V} {
40 : {
41 (x, y, z) = V;
42 ((m00,m01,m02), (m10,m11,m12), (m20,m21,m22)) = M;
43 list(m00*x + m10*y + m20*z,
44 m01*x + m11*y + m21*z,
45 m02*x + m12*y + m22*z)
46 }
47}

MatrixProduct −12 +6 −5 +5 21.5 µs → 7.3 µs, 2.9× faster

MatrixProduct becomes the operator \matrixProd. No index and no loop counter: lmap goes over the rows of M1, and each row of the result is the sum of the rows of M2 weighted by the row of M1. It is also faster than the version with loops (5.5 µs per call, against 19.6 µs for the original and 8.7 µs for for loops with an unrolled k, on the same build).
48proc MatrixProduct {M1 M2} {
49 set M {{0 0 0 0} {0 0 0 0} {0 0 0 0} {0 0 0 0}}
50
51 for {set i 0} {$i<4} {incr i} {
52 for {set j 0} {$j<4} {incr j} {
53 lset M $i $j 0
54 for {set k 0} {$k<4} {incr k} {
55 lset M $i $j [expr {[lindex $M $i $j]+[lindex $M1 $i $k]*[lindex $M2 $k $j]}]
56 }
57 }
58 }
59 return $M
60}
33proc tcl::mathop::matrixProd {M1 M2} {
34 lassign $M2 B0 B1 B2 B3
35 lmap row $M1 {(
36 (a0, a1, a2, a3) = $row;
37 lmap b0 $B0 b1 $B1 b2 $B2 b3 $B3 {( $a0*$b0 + $a1*$b1 + $a2*$b2 + $a3*$b3 )}
38 )}
39}
48proc MatrixProduct {M1 M2} {
49 set M {{0 0 0 0} {0 0 0 0} {0 0 0 0} {0 0 0 0}}
50
51 for {set i 0} {$i<4} {incr i} {
52 for {set j 0} {$j<4} {incr j} {
53 lset M $i $j 0
54 for {set k 0} {$k<4} {incr k} {
55 lset M $i $j [expr {[lindex $M $i $j]+[lindex $M1 $i $k]*[lindex $M2 $k $j]}]
56 }
57 }
58 }
59 return $M
60}
49proc MatrixProduct {M1 M2} {
50 : { L = (0, 0, 0, 0) ; M = (L, L, L, L) }
51 
52 for {set i 0} {$i<4} {incr i} {
53 for {set j 0} {$j<4} {incr j} {
54 lset M $i $j [: lindex(M1, i, 0) * lindex(M2, 0, j) + \
55 lindex(M1, i, 1) * lindex(M2, 1, j) + \
56 lindex(M1, i, 2) * lindex(M2, 2, j) + \
57 lindex(M1, i, 3) * lindex(M2, 3, j)]
58 }
59 }
60 return $M
61}

MatrixRotation −27 +18 −25 +19 54.0 µs → 17.1 µs, 3.2× faster

The code posted in the TIP 672 forum discussion, with one change: the product, at the end, is written with the operator, $Mx \matrixProd $My \matrixProd $Mz, left to right, instead of nested [MatrixProduct …].
62proc MatrixRotation { ax ay az } {
63 set sax [expr {sin($ax)}]
64 set cax [expr {cos($ax)}]
65 set say [expr {sin($ay)}]
66 set cay [expr {cos($ay)}]
67 set saz [expr {sin($az)}]
68 set caz [expr {cos($az)}]
69 set Mx {{1 0 0 0} {0 0 0 0} {0 0 0 0} {0 0 0 1}}
70 set My {{0 0 0 0} {0 1 0 0} {0 0 0 0} {0 0 0 1}}
71 set Mz {{0 0 0 0} {0 0 0 0} {0 0 1 0} {0 0 0 1}}
72
73 # Rotation matrix around X axis with angle ax
74 lset Mx 1 1 $cax
75 lset Mx 1 2 $sax
76 lset Mx 2 1 [expr {-1*$sax}]
77 lset Mx 2 2 $cax
78 # Rotation matrix around Y axis with angle ay
79 lset My 0 0 $cay
80 lset My 0 2 [expr {-1*$say}]
81 lset My 2 0 $say
82 lset My 2 2 $cay
83 # Rotation matrix around Z axis with angle az
84 lset Mz 0 0 $caz
85 lset Mz 0 1 $saz
86 lset Mz 1 0 [expr {-1*$saz}]
87 lset Mz 1 1 $caz
88 return [MatrixProduct [MatrixProduct $Mx $My] $Mz]
89}
41proc MatrixRotation { ax ay az } {(
42 # Rotation matrix around X axis with angle ax
43 Mx = ((1, 0 , 0 , 0),
44 (0, cos($ax) , sin($ax), 0),
45 (0, -sin($ax), cos($ax), 0),
46 (0, 0 , 0 , 1));
47 # Rotation matrix around Y axis with angle ay
48 My = ((cos($ay), 0, -sin($ay), 0),
49 (0 , 1, 0 , 0),
50 (sin($ay), 0, cos($ay) , 0),
51 (0 , 0, 0 , 1));
52 # Rotation matrix around Z axis with angle az
53 Mz = ((cos($az) , sin($az), 0, 0),
54 (-sin($az), cos($az), 0, 0),
55 (0 , 0 , 1, 0),
56 (0 , 0 , 0, 1));
57
58 $Mx \matrixProd $My \matrixProd $Mz
59)}
62proc MatrixRotation { ax ay az } {
63 set sax [expr {sin($ax)}]
64 set cax [expr {cos($ax)}]
65 set say [expr {sin($ay)}]
66 set cay [expr {cos($ay)}]
67 set saz [expr {sin($az)}]
68 set caz [expr {cos($az)}]
69 set Mx {{1 0 0 0} {0 0 0 0} {0 0 0 0} {0 0 0 1}}
70 set My {{0 0 0 0} {0 1 0 0} {0 0 0 0} {0 0 0 1}}
71 set Mz {{0 0 0 0} {0 0 0 0} {0 0 1 0} {0 0 0 1}}
72
73 # Rotation matrix around X axis with angle ax
74 lset Mx 1 1 $cax
75 lset Mx 1 2 $sax
76 lset Mx 2 1 [expr {-1*$sax}]
77 lset Mx 2 2 $cax
78 # Rotation matrix around Y axis with angle ay
79 lset My 0 0 $cay
80 lset My 0 2 [expr {-1*$say}]
81 lset My 2 0 $say
82 lset My 2 2 $cay
83 # Rotation matrix around Z axis with angle az
84 lset Mz 0 0 $caz
85 lset Mz 0 1 $saz
86 lset Mz 1 0 [expr {-1*$saz}]
87 lset Mz 1 1 $caz
88 return [MatrixProduct [MatrixProduct $Mx $My] $Mz]
89}
63proc MatrixRotation { ax ay az } {
64 : {
65 # Rotation matrix around X axis with angle ax
66 Mx = ((1, 0 , 0 , 0),
67 (0, cos( ax) , sin( ax), 0),
68 (0, -sin( ax), cos( ax), 0),
69 (0, 0 , 0 , 1));
70 # Rotation matrix around Y axis with angle ay
71 My = ((cos( ay), 0, -sin( ay), 0),
72 (0 , 1, 0 , 0),
73 (sin( ay), 0, cos( ay) , 0),
74 (0 , 0, 0 , 1));
75 # Rotation matrix around Z axis with angle az
76 Mz = ((cos( az) , sin( az), 0, 0),
77 (-sin( az), cos( az), 0, 0),
78 (0 , 0 , 1, 0),
79 (0 , 0 , 0, 1));
80
81 
82 MatrixProduct( MatrixProduct( Mx, My), Mz)
83 }
84}

NormalVector −16 +11 −9 +9 11.3 µs → 59.3 µs, 5.2× slower

The three vertices of the face are fetched as vectors in one tuple assignment, (P0, P1, P2) = lmap i $face {lindex $lvtx $i}, and the normal is written as in a textbook: ($P1 \sub $P0) \crossProd ($P2 \sub $P1). The norm is [( $n \dot $n )]. This costs time: three operator calls per face, each a proc (see the speed table).
137# Compute normal vector and norm for each face
138# -------------------------------------------------------------------
139proc NormalVector {lvtx lcnx} {
140 set lnv {}
141 set lmv {}
142
143 foreach face $lcnx {
144 foreach {nx ny nz} [CrossProduct \
145 [expr {[lindex $lvtx [lindex $face 1] 0] - [lindex $lvtx [lindex $face 0] 0]}] \
146 [expr {[lindex $lvtx [lindex $face 1] 1] - [lindex $lvtx [lindex $face 0] 1]}] \
147 [expr {[lindex $lvtx [lindex $face 1] 2] - [lindex $lvtx [lindex $face 0] 2]}] \
148 [expr {[lindex $lvtx [lindex $face 2] 0] - [lindex $lvtx [lindex $face 1] 0]}] \
149 [expr {[lindex $lvtx [lindex $face 2] 1] - [lindex $lvtx [lindex $face 1] 1]}] \
150 [expr {[lindex $lvtx [lindex $face 2] 2] - [lindex $lvtx [lindex $face 1] 2]}]] {}
151 lappend lnv [list $nx $ny $nz]
152 lappend lmv [DotProduct $nx $ny $nz $nx $ny $nz]
153 }
154 return [list $lnv $lmv]
155}
107# Compute normal vector and norm for each face
108# -------------------------------------------------------------------
109proc NormalVector {lvtx lcnx} {(
110 lnv = {};
111 lmv = {};
112
113 foreach face $lcnx {(
114 (P0, P1, P2) = lmap i $face {lindex $lvtx $i};
115 n = ($P1 \sub $P0) \crossProd ($P2 \sub $P1);
116 lappend lnv $n;
117 lappend lmv [( $n \dot $n )]
118 )};
119 ($lnv, $lmv)
120)}
137# Compute normal vector and norm for each face
138# -------------------------------------------------------------------
139proc NormalVector {lvtx lcnx} {
140 set lnv {}
141 set lmv {}
142
143 foreach face $lcnx {
144 foreach {nx ny nz} [CrossProduct \
145 [expr {[lindex $lvtx [lindex $face 1] 0] - [lindex $lvtx [lindex $face 0] 0]}] \
146 [expr {[lindex $lvtx [lindex $face 1] 1] - [lindex $lvtx [lindex $face 0] 1]}] \
147 [expr {[lindex $lvtx [lindex $face 1] 2] - [lindex $lvtx [lindex $face 0] 2]}] \
148 [expr {[lindex $lvtx [lindex $face 2] 0] - [lindex $lvtx [lindex $face 1] 0]}] \
149 [expr {[lindex $lvtx [lindex $face 2] 1] - [lindex $lvtx [lindex $face 1] 1]}] \
150 [expr {[lindex $lvtx [lindex $face 2] 2] - [lindex $lvtx [lindex $face 1] 2]}]] {}
151 lappend lnv [list $nx $ny $nz]
152 lappend lmv [DotProduct $nx $ny $nz $nx $ny $nz]
153 }
154 return [list $lnv $lmv]
155}
86# Compute normal vector and norm for each face
87# -------------------------------------------------------------------
88proc NormalVector {lvtx lcnx} {
89 set lnv {}
90 set lmv {}
91
92 foreach face $lcnx {
93 : {
94 (i0, i1, i2) = face;
95 (x0, y0, z0) = lindex(lvtx, i0);
96 (x1, y1, z1) = lindex(lvtx, i1);
97 (x2, y2, z2) = lindex(lvtx, i2);
98 (nx, ny, nz) = CrossProduct(x1-x0, y1-y0, z1-z0, x2-x1, y2-y1, z2-z1)
99 }
100 lappend lnv [: (nx, ny, nz)]
101 lappend lmv [: DotProduct(nx, ny, nz, nx, ny, nz)]
102 }
103 return [list $lnv $lmv]
104}

Projection −7 +8 −4 +7 2.3 µs → 5.4 µs, 2.4× slower

The 2D projection, a common operation, becomes the operator \project: $P \project $M, a point and a rotation matrix. The matrix is transposed into column vectors, and each coordinate is the dot product of the point with a column: nx = $P \dot $m.
157# 2D projection
158# -------------------------------------------------------------------
159proc Projection {x y z M} {
160 global scx scy vdist
161
162 set nx [expr {[lindex $M 0 0]*$x+[lindex $M 1 0]*$y+[lindex $M 2 0]*$z}]
163 set ny [expr {[lindex $M 0 1]*$x+[lindex $M 1 1]*$y+[lindex $M 2 1]*$z}]
164 set nz [expr {([lindex $M 0 2]*$x+[lindex $M 1 2]*$y+[lindex $M 2 2]*$z+10)/$vdist}]
165 return [list [expr {$nx/$nz+$scx/2.0}] [expr {$ny/$nz+$scy/2.0}]]
166}
122# 2D projection
123# -------------------------------------------------------------------
124proc tcl::mathop::project {P M} {(
125 global scx scy vdist;
126
127 (m, n, o) = \transpose $M;
128 nx = $P \dot $m;
129 ny = $P \dot $n;
130 nz = ($P \dot $o + 10)/$vdist;
131 ($nx/$nz + $scx/2.0, $ny/$nz + $scy/2.0)
132)}
157# 2D projection
158# -------------------------------------------------------------------
159proc Projection {x y z M} {
160 global scx scy vdist
161
162 set nx [expr {[lindex $M 0 0]*$x+[lindex $M 1 0]*$y+[lindex $M 2 0]*$z}]
163 set ny [expr {[lindex $M 0 1]*$x+[lindex $M 1 1]*$y+[lindex $M 2 1]*$z}]
164 set nz [expr {([lindex $M 0 2]*$x+[lindex $M 1 2]*$y+[lindex $M 2 2]*$z+10)/$vdist}]
165 return [list [expr {$nx/$nz+$scx/2.0}] [expr {$ny/$nz+$scy/2.0}]]
166}
106# 2D projection
107# -------------------------------------------------------------------
108proc Projection {x y z M} {
109 global scx scy vdist
110 
111 : {
112 ((m00,m01,m02), (m10,m11,m12), (m20,m21,m22)) = M;
113 nx = m00*x + m10*y + m20*z;
114 ny = m01*x + m11*y + m21*z;
115 nz = (m02*x + m12*y + m22*z + 10)/vdist;
116 list(nx/nz + scx/2.0, ny/nz + scy/2.0)
117 }
118}

Transformations −13 +8 −6 +5 71.9 µs → 79.6 µs, about the same

The body becomes an expression script: global, foreach and lappend are raw commands, the two lists start empty in one chained assignment, lnew = lvn = {}, the vertices are projected with $vtx \project $M and the normals rotated with $M \matrixVectorProd $v, and the result is the native list ($M, $lnew, $lvn). The counter i, never used, is gone, as in the Calc version.
168# Apply transformations to vertex coordinates
169# -------------------------------------------------------------------
170proc Transformations {lvtx lnv} {
171 global ax ay az
172 set lnew {}
173 set lvn {}
174 # Compute matrix rotation
175 set M [MatrixRotation $ax $ay $az]
176 set i 0
177 # Apply projection
178 foreach vtx $lvtx {
179 lappend lnew [Projection [lindex $vtx 0] [lindex $vtx 1] [lindex $vtx 2] $M]
180 incr i
181 }
182 # Normal vector rotation
183 foreach v $lnv {lappend lvn [MatrixVectorProduct $M $v]}
184
185 return [list $M $lnew $lvn]
186}
134# Apply transformations to vertex coordinates
135# -------------------------------------------------------------------
136proc Transformations {lvtx lnv} {(
137 global ax ay az;
138 lnew = lvn = {};
139 # Compute matrix rotation
140 M = [MatrixRotation $ax $ay $az];
141 # Apply projection
142 foreach vtx $lvtx {lappend lnew [( $vtx \project $M )]};
143 # Normal vector rotation
144 foreach v $lnv {lappend lvn [( $M \matrixVectorProd $v )]};
145
146 ($M, $lnew, $lvn)
147)}
168# Apply transformations to vertex coordinates
169# -------------------------------------------------------------------
170proc Transformations {lvtx lnv} {
171 global ax ay az
172 set lnew {}
173 set lvn {}
174 # Compute matrix rotation
175 set M [MatrixRotation $ax $ay $az]
176 set i 0
177 # Apply projection
178 foreach vtx $lvtx {
179 lappend lnew [Projection [lindex $vtx 0] [lindex $vtx 1] [lindex $vtx 2] $M]
180 incr i
181 }
182 # Normal vector rotation
183 foreach v $lnv {lappend lvn [MatrixVectorProduct $M $v]}
184
185 return [list $M $lnew $lvn]
186}
120# Apply transformations to vertex coordinates
121# -------------------------------------------------------------------
122proc Transformations {lvtx lnv} {
123 global ax ay az
124 set lnew {}
125 set lvn {}
126 # Compute matrix rotation
127 : M = MatrixRotation(ax, ay, az)
128 # Apply projection
129 foreach vtx $lvtx {
130 : (x, y, z) = vtx
131 lappend lnew [: Projection(x, y, z, M)]
132 }
133 # Normal vector rotation
134 foreach v $lnv {lappend lvn [: MatrixVectorProduct(M, v)]}
135
136 return [: (M, lnew, lvn)]
137}

Intensity −15 +12 −8 +8 7.0 µs → 7.3 µs, about the same

The shading maths is one expression script per face; the dot products are written $nv \dot $lvv, lindex is a raw command inside sqrt(), and the colour is a conditional expression.
188# Compute color entensity for each face
189# -------------------------------------------------------------------
190proc Intensity {lnv lmv lvv} {
191 set lclr {}
192 set v [DotProduct [lindex $lvv 0] [lindex $lvv 1] [lindex $lvv 2] \
193 [lindex $lvv 0] [lindex $lvv 1] [lindex $lvv 2]]
194 set i 0
195 foreach nv $lnv {
196 set clr 31
197 set a [DotProduct [lindex $nv 0] [lindex $nv 1] [lindex $nv 2] \
198 [lindex $lvv 0] [lindex $lvv 1] [lindex $lvv 2]]
199 set b [expr {sqrt([lindex $lmv $i]*$v)}]
200 set clr [expr {round(31*($a/$b))}]
201 lappend lclr [expr {$clr < 0 ? 31 : [expr {32 - $clr}]}]
202 incr i
203 }
204 return $lclr
205}
149# Compute color entensity for each face
150# -------------------------------------------------------------------
151proc Intensity {lnv lmv lvv} {(
152 lclr = {};
153 v = $lvv \dot $lvv;
154 i = 0;
155 foreach nv $lnv {(
156 a = $nv \dot $lvv;
157 b = sqrt(lindex $lmv $i * $v);
158 clr = round(31*($a/$b));
159 lappend lclr [( $clr < 0 ? 31 : 32 - $clr )];
160 incr i
161 )};
162 $lclr
163)}
188# Compute color entensity for each face
189# -------------------------------------------------------------------
190proc Intensity {lnv lmv lvv} {
191 set lclr {}
192 set v [DotProduct [lindex $lvv 0] [lindex $lvv 1] [lindex $lvv 2] \
193 [lindex $lvv 0] [lindex $lvv 1] [lindex $lvv 2]]
194 set i 0
195 foreach nv $lnv {
196 set clr 31
197 set a [DotProduct [lindex $nv 0] [lindex $nv 1] [lindex $nv 2] \
198 [lindex $lvv 0] [lindex $lvv 1] [lindex $lvv 2]]
199 set b [expr {sqrt([lindex $lmv $i]*$v)}]
200 set clr [expr {round(31*($a/$b))}]
201 lappend lclr [expr {$clr < 0 ? 31 : [expr {32 - $clr}]}]
202 incr i
203 }
204 return $lclr
205}
139# Compute color entensity for each face
140# -------------------------------------------------------------------
141proc Intensity {lnv lmv lvv} {
142 set lclr {}
143 : { (lx, ly, lz) = lvv; v = DotProduct(lx, ly, lz, lx, ly, lz) }
144 set i 0
145 foreach nv $lnv {
146 : {
147 (nx, ny, nz) = nv;
148 a = DotProduct(nx, ny, nz, lx, ly, lz);
149 b = sqrt(lindex(lmv, i) * v);
150 clr = round(31*(a/b))
151 }
152 lappend lclr [: clr < 0 ? 31 : 32 - clr]
153 incr i
154 }
155 return $lclr
156}

DisplayModel −6 +1 −8 +4

The six set become one tuple assignment, written as a [( … )] command in this plain script. The other changes of the Calc page (the remembered model, the label colour) are not about the maths and are left out here.
207# Start the display and rotation loop
208# -------------------------------------------------------------------
209proc DisplayModel {w s} {
210 global stop
211 global display
212 global ax ay az tx ty tz
213 global form
214
215 $w.c delete all
216 set stop 0
217 global iterations
218 set ax 0.2
219 set ay 0.1
220 set az 0.3
221 set tx 0
222 set ty 0
223 set tz 0
224
225 set d $display
226 foreach {t lvtx lcnx lclr} [ReadData $s] {}
227 $w.c create text 10 10 -anchor w -fill white -text $t
228 foreach {lnv lmv} [NormalVector $lvtx $lcnx] {}
229
230 set lpoly [DisplayInit $w $d $lcnx $lclr]
231 
232 after cancel $::run
233 set ::run [after 0 [list Display$d $w $lpoly $lvtx $lcnx $lnv $lmv]]
234}
165# Start the display and rotation loop
166# -------------------------------------------------------------------
167proc DisplayModel {w s} {
168 global stop
169 global display
170 global ax ay az tx ty tz
171 global form
172
173 $w.c delete all
174 set stop 0
175 global iterations
176 [( (ax, ay, az, tx, ty, tz) = (0.2, 0.1, 0.3, 0, 0, 0) )]
177
178 set d $display
179 foreach {t lvtx lcnx lclr} [ReadData $s] {}
180 $w.c create text 10 10 -anchor w -fill white -text $t
181 foreach {lnv lmv} [NormalVector $lvtx $lcnx] {}
182
183 set lpoly [DisplayInit $w $d $lcnx $lclr]
184 
185 after cancel $::run
186 set ::run [after 0 [list Display$d $w $lpoly $lvtx $lcnx $lnv $lmv]]
187}
207# Start the display and rotation loop
208# -------------------------------------------------------------------
209proc DisplayModel {w s} {
210 global stop
211 global display
212 global ax ay az tx ty tz
213 global form
214
215 $w.c delete all
216 set stop 0
217 global iterations
218 set ax 0.2
219 set ay 0.1
220 set az 0.3
221 set tx 0
222 set ty 0
223 set tz 0
224
225 set d $display
226 foreach {t lvtx lcnx lclr} [ReadData $s] {}
227 $w.c create text 10 10 -anchor w -fill white -text $t
228 foreach {lnv lmv} [NormalVector $lvtx $lcnx] {}
229
230 set lpoly [DisplayInit $w $d $lcnx $lclr]
231 
232 after cancel $::run
233 set ::run [after 0 [list Display$d $w $lpoly $lvtx $lcnx $lnv $lmv]]
234}
158# Start the display and rotation loop
159# -------------------------------------------------------------------
160proc DisplayModel {w s} {
161 global stop
162 global display
163 global ax ay az tx ty tz
164 global form
165
166 $w.c delete all
167 set stop 0
168 global iterations
169 : (ax, ay, az, tx, ty, tz) = (0.2, 0.1, 0.3, 0, 0, 0)
170
171 : ::curmodel = s; d = display ;# curmodel is remembered so Shaded/Wireframe can restart it
172 foreach {t lvtx lcnx lclr} [ReadData $s] {}
173 $w.c create text 10 10 -anchor w -tags label -text $t \
174 -fill [expr {$::bggray < 128 ? "white" : "black"}]
175 foreach {lnv lmv} [NormalVector $lvtx $lcnx] {}
176
177 set lpoly [DisplayInit $w $d $lcnx $lclr]
178 
179 after cancel $::run
180 set ::run [after 0 [list Display$d $w $lpoly $lvtx $lcnx $lnv $lmv]]
181}

Vector operators −0 +12 −0 +0

The operators used above, as procs of tcl::mathop: \add and \sub, the sum and the difference of two vectors or matrices; \dot, the dot product (it replaces DotProduct, which the Calc page does not show); \transpose, unary; \tensorProd, the tensor product of two vectors, a matrix; and \axial, unary, the vector of an antisymmetric matrix. They have no counterpart in the original or in Calc, which write the arithmetic inline. Written in C, they would make the vector code as fast as the inline code (see the speed table). These definitions could come from math::linearalgebra, with one package require line (see below the speed table).
# Vector operators, for the expressions: $U \add $V, $U \sub $V, $U \dot $V,
# \transpose $M, $U \tensorProd $V, \axial $A
# -------------------------------------------------------------------
proc tcl::mathop::add {U V} {lmap a $U b $V {( [llength $a] > 1 ? $a \add $b : $a + $b )}}
proc tcl::mathop::sub {U V} {lmap a $U b $V {( [llength $a] > 1 ? $a \sub $b : $a - $b )}}
proc tcl::mathop::dot {U V} {(
(x1, y1, z1) = $U; (x2, y2, z2) = $V;
$x1*$x2 + $y1*$y2 + $z1*$z2
)}
proc tcl::mathop::transpose {M} {lmap i [lseq [llength [lindex $M 0]]] {lmap r $M {lindex $r $i}}}
proc tcl::mathop::tensorProd {U V} {lmap u $U {lmap v $V {( $u * $v )}}}
proc tcl::mathop::axial {A} {( (lindex $A 2 1, lindex $A 0 2, lindex $A 1 0) )}
Calc has no user-defined operators: this section is TIP 759 only.

Calc-specific code −0 +0 −0 +21

What Calc needs around the code: the package at the top of the file, and at the end one Calc::transformProcs call that compiles the procs listed, before Main, then : and = renamed away, so that a missed proc fails loudly instead of running the slow interpreted path.
Nothing here for TIP 759: [( … )] and {( … )} are part of the Tcl syntax, parsed with the proc and compiled to bytecode with it, like expr {…} today. No package, no list of procs to keep up to date, no command to remove.
12#tcl::tm::path add {path/to/colon-module/dir} ;# point this to the module directory
13::tcl::tm::path add [file dirname [info script]] ;# works if script and module in same directory
14package require colon
493# Compile the Calc code (the : commands) in these procs, once, now that they
494# are all defined and just before Main runs. This is the same result as
495# defining each of them with proc=
496# -------------------------------------------------------------------
497Calc::transformProcs \
498 Barycenter CrossProduct DotProduct \
499 MatrixVectorProduct MatrixProduct MatrixRotation \
500 NormalVector Projection Transformations Intensity \
501 DisplayModel ReadData BlueColor \
502 DisplayShaded DisplayWireframe
503
504# Everything that uses Calc is compiled now, so remove the interpreted : and =
505# commands. A : or = left in any code that was not compiled (a proc missing from
506# the list above, say) now fails with 'invalid command name' and a traceback
507# showing which proc and line, instead of quietly running the slow path and
508# filling Calc::cache.
509rename : {}
510rename = {}