# STM publishing: tools, technologies and changeA WordPress site for STM Publishing

14Dec/11Off

## LuaTeX: nodes, graphics and PDF coordinate transformation matrices

#### Posted by Graham Douglas

Note: if you want to zoom in on the matrices, right-click over an equation and set the MathJax parameters to your preferred values:

# Introduction

In this post I'll introduce a nice matrix-manipulation library called lua-matrix. It is written in pure Lua and so should be usable with any LuaTeX installation. You can download the code from GitHub. You can use lua-matrix as a convenient method to create PDF transformation matrices.

Note: where to install Lua code modules
The texmf.cnf variable you need to check is LUAINPUTS. See this newsgroup post for more details.

Tip: a Git tool for Windows users
Like many open source projects lua-matrix is hosted on GitHub. If you are a Windows user you may need to install some utilities that let you "check out" a copy of the code on repositories such as GitHub or others based on SVN. For SVN repositories there is the excellent TortoiseSVN but for Git repos I use a free tool called Git for Windows.

# Very brief summary of matrices

Quoting from the PDF standard:

"PDF represents coordinates in a two-dimensional space. The point (x, y) in such a space can be expressed in vector form as [x y 1]. The constant third element of this vector (1) is needed so that the vector can be used with 3-by-3 matrices. The transformation between two coordinate systems is represented by a 3-by-3 transformation matrix written as

$$\displaystyle \left( \matrix{ a & b & 0 \cr c & d & 0 \cr e & f & 1 \cr} \right)$$

Because a transformation matrix has only six elements that can be changed, it is usually specified in PDF as the six-element array [a b c d e f].

Note: This is method of representing coordinates is referred to as homogeneous coordinates.

## Rotation

The matrix for rotation by an angle $$\theta$$ counter clockwise about the origin:
$$\displaystyle \left( \matrix{ \cos (\theta) & \sin (\theta) & 0 \cr -\sin (\theta) & \cos (\theta) & 0 \cr 0 & 0 & 1 \cr} \right)$$

This is expressed in PDF code as $$\cos(\theta)\ \sin(\theta)\ -\hskip-2pt\sin(\theta)\ \cos(\theta)\ 0\ 0$$ cm

## Translation

The matrix for translation by $$(t_x, t_y)$$ relative to the origin:

$$\displaystyle \left( \matrix{ 1 & 0 & 0 \cr 0 & 1 & 0 \cr t_x & t_y & 1 \cr} \right)$$

This is expressed in PDF code as $$1\ 0\ 0\ 1\ t_x\ t_y$$ cm

## Scale

The matrix for scaling by $$s_x$$ in the horizonal direction and $$s_y$$ in the vertical direction is:

$$\displaystyle \left( \matrix{ s_x & 0 & 0 \cr 0 & s_y & 0 \cr 0 & 0 & 1 \cr} \right)$$

This is expressed in PDF code as $$s_x\ 0\ 0\ s_y\ 0\ 0$$ cm

## Demonstration graphic

The following simple graphic (shown as inline SVG) will be used to explore transformations. The equivalent PDF graphic (in hand-coded PDF data) is shown below.

### Equivalent PDF data

The following PDF code will draw a very similar graphic:

q % save graphics state
1 j % set the line join style
1 J % set the line cap style
10 M % set the miter limit
%Set the stroking color space to DeviceRGB
0 0 0 RG % black
% draw the axes
0 0 m
0.5 w
0 30 l
0 0 m
30 0 l
S % stroke
% draw the red arrow head on x axis
q % save graphics state
%Set the non-stroking color space to DeviceRGB
1 0 0 rg % red
% translate to end of line on x-axis
1 0 0 1 30 0 cm
0 0 m % move to the origin
0 1.5 l
2.5 0 l
0 -1.5 l
h % close the current subpath
B % fill and stroke
Q % restore graphics state
% draw the blue arrow head on y axis
q % save graphics state
%Set the non-stroking color space to DeviceRGB
0 0 1 rg % blue
% translate to end of line on y-axis
1 0 0 1 0 30 cm
0 0 m % move to the origin
-1.5 0 l
0 2.5 l
1.5 0 l
h % close the current subpath
B % fill and stroke
% restore graphics state
Q
Q


# Creating a graphic with LuaTeX nodes

As usual, a simple plain TeX setup.

\pdfoutput=1
\pdfcompresslevel=0
\hoffset-1in
\voffset-1in
\pdfpageheight=50mm
\pdfpagewidth=50mm
\vsize=50mm
\hsize=50mm
\topskip=0pt
\maxdepth=0pt
\nopagenumbers

\directlua{
grafik = node.new("whatsit","pdf_literal")
grafik.mode=0
grafik.data="  q % save graphics state
1 j % set the line join style
1 J % set the line cap style
10 M % set the miter limit
%Set the stroking color space to DeviceRGB
0 0 0 RG % black
% draw the axes
0 0 m
0.5 w
0 30 l
0 0 m
30 0 l
S % stroke
% draw the red arrow head on x axis
q % save graphics state
%Set the non-stroking color space to DeviceRGB
1 0 0 rg % red
% translate to end of line on x-axis
1 0 0 1 30 0 cm
0 0 m % move to the origin
0 1.5 l
2.5 0 l
0 -1.5 l
h % close the current subpath
B % fill and stroke
Q % restore graphics state
% draw the blue arrow head on y axis
q % save graphics state
%Set the non-stroking color space to DeviceRGB
0 0 1 rg % blue
% translate to end of line on y-axis
1 0 0 1 0 30 cm
0 0 m % move to the origin
-1.5 0 l
0 2.5 l
1.5 0 l
h % close the current subpath
B % fill and stroke
% restore graphics state
Q
Q "

tex.box[1000]=node.hpack(grafik)
}

Here is out new graphic \vskip 35mm
\noindent\hskip 15mm \copy1000
\bye


### Notes about the PDF graphic

In the code above we have not assigned any size to the box containing the graphic, hence I needed to add \vskip 35mm \noindent\hskip 15mm to push the graphic into a space where it will be seen. To give the graphic some dimensions, we'll need to add code such as

tex.box[1000].width = width value in sp
tex.box[1000].height = height value in sp
tex.box[1000].depth = depth value in sp

where the values assigned are in sp (special points). You may recall that 65536sp = 1 TeX point, where 72.27 TeX points = 1 inch = 72 PostScript points (same as default in PDF).

As far as the LuaTeX engine is concerned, the box containing the graphic has zero size, we have to tell LuaTeX how big we want it to be. In addition, the line widths, based on the above code, will be affected by any scaling but it is not too difficult to fix that.

# The Lua code

The idea is that we create a number of functions based on the lua-matrix library and save those functions into a Lua module called "mymatrix.lua". Within "mymatrix.lua" we import the lua-matrix code via its module called "matrix" which we load with:

local matrix=require("matrix")

## Our simple API

Here are the functions defined within our "mymatrix.lua" module:

• rotate(angle): returns a 3 x 3 rotation matrix (angle positive for counter clockwise)
• translate(tx,ty): returns a 3 x 3 translation matrix (tx, ty are translations in x, y directions)
• scale(sx,sy): returns a 3 x 3 scaling matrix (sx, sy are scaling in x,y directions)
• dump(mtx): simple debugging function (mtx = 3 x 3 matrix)
• toinlinetex(mtx): returns inline TeX code so we can typeset the matrix (mtx = 3 x 3 matrix)
• todisplaytex(mtx): returns display TeX code so we can typeset the matrix (mtx = 3 x 3 matrix)
• topdf(mtx): returns matrix in PDF code format (mtx = 3 x 3 matrix)

Here's the source code for mymodule.lua. One huge advantage of putting Lua code into Lua modules is that it greatly simplifies dealing with \catcode issues. Note that within code saved in Lua files you use the regular Lua comment "--" mechanism and not the TeX comment "%" mechanism. You can use "%" when the code is embedded in a \directlua{...} call.

module("mymatrix",package.seeall)
local matrix=require("matrix")
local sin=math.sin
local cos=math.cos

-- Function to generate PDF transformation (rotation) matrices.
function rotate(angle)
return rot
end

-- Function to generate PDF transformation (translation) matrices.
function translate(tx,ty)
local tran = matrix {{1,0,0},{0,1,0},{tx,ty,1}}
return tran
end

-- Function to generate PDF transformation (scale) matrices.
function scale(sx,sy)
local scale = matrix {{sx,0,0},{0,sy,0},{0,0,1}}
return scale
end

function dump(mtx)
for i=1,3 do
for j=1,3 do
print("(i,j)=("..i..","..j..")="..mtx[i][j])
end
end
end

function todisplaytex(mtx)
texcode=string.format([[$$\left(\matrix {%3.3f & %3.3f & %3.3f \cr %3.3f & %3.3f & %3.3f \cr %3.3f & %3.3f & %3.3f \cr } \right)$$]],
mtx[1][1], mtx[1][2], mtx[1][3],mtx[2][1], mtx[2][2], mtx[2][3],
mtx[3][1], mtx[3][2], mtx[3][3])
return texcode
end

function toinlinetex(mtx)
texcode=string.format([[$\left(\matrix {%3.3f & %3.3f & %3.3f \cr %3.3f & %3.3f & %3.3f \cr %3.3f & %3.3f & %3.3f \cr } \right)$]],
mtx[1][1], mtx[1][2], mtx[1][3],mtx[2][1], mtx[2][2], mtx[2][3],
mtx[3][1], mtx[3][2], mtx[3][3])
return texcode
end

function topdf(mtx)
pdftext = string.format("%3.3f %3.3f %3.3f %3.3f %3.3f %3.3f  cm",
mtx[1][1], mtx[1][2],mtx[2][1], mtx[2][2], mtx[3][1], mtx[3][2])
return pdftext
end


# Full example

\pdfoutput=1
\pdfcompresslevel=0
\hoffset-1in
\voffset-1in
\pdfpageheight=350mm
\pdfpagewidth=150mm
\vsize=350mm
\hsize=150mm
\topskip=0pt
\maxdepth=0pt
\nopagenumbers
\directlua{require("mymatrix")}

\directlua{
% We'll create an non-transformed graphic and store it in box 1000
grafik = node.new("whatsit","pdf_literal")
grafik.mode=0
grafik.data="
q % save graphics state
1 j % set the line join style
1 J % set the line cap style
10 M % set the miter limit
%Set the stroking color space to DeviceRGB
0 0 0 RG % black
% draw the axes
0 0 m
0.5 w
0 30 l
0 0 m
30 0 l
S % stroke
% draw the red arrow head on x axis
q % save graphics state
%Set the non-stroking color space to DeviceRGB
1 0 0 rg % red
% translate to end of line on x-axis
1 0 0 1 30 0 cm
0 0 m % move to the origin
0 1.5 l
2.5 0 l
0 -1.5 l
h % close the current subpath
B % fill and stroke
Q % restore graphics state
% draw the blue arrow head on y axis
q % save graphics state
%Set the non-stroking color space to DeviceRGB
0 0 1 rg % blue
% translate to end of line on y-axis
1 0 0 1 0 30 cm
0 0 m % move to the origin
-1.5 0 l
0 2.5 l
1.5 0 l
h % close the current subpath
B % fill and stroke
% restore graphics state
Q
Q "
% store graphic in box 1000
tex.box[1000]=node.hpack(grafik)

% create some transformation matrices
mtx1 = mymatrix.rotate(45)
mtx2 = mymatrix.scale(1.5,2)
mtx3 = mymatrix.translate(15,15)

% Now we copy our untransformed node
% and add the PDF transformation matrices to
% rotate, scale etc.

% We'll do a rotation and store in box 1001
grafik2 = node.copy(grafik)
grafik2.mode=0
cm = mymatrix.topdf(mtx1)
% copy the PDF data from the untransformed
% graphic and add the PDF rotation matrix
grafik2.data="q ".. cm ..grafik.data.." Q "
% store graphic in box 1001
tex.box[1001]=node.hpack(grafik2)

% We'll do a scale and store in box 1002
grafik3 = node.copy(grafik)
grafik3.mode=0
cm = mymatrix.topdf(mtx2)
% copy the PDF data from the untransformed
% graphic and add the PDF rotation matrix
grafik3.data="q ".. cm ..grafik.data.." Q "
% store graphic in box 1002
tex.box[1002]=node.hpack(grafik3)

% Now multiply the scale and rotation matrices
% --- experiment with different combinations
combo=mtx1*mtx2

grafik4 = node.copy(grafik)
grafik4.mode=0
cm = mymatrix.topdf(combo)
% copy the PDF data from the untransformed
% graphic and add the result of multiplication
grafik4.data="q ".. cm ..grafik.data.." Q "

% store graphic in box 1002
tex.box[1003]=node.hpack(grafik4)

% Now multiply the scale, rotation and translation
% matrices --- experiment with different combinations
combo2=mtx1*(mtx2*mtx3)

grafik5 = node.copy(grafik)
grafik5.mode=0
cm = mymatrix.topdf(combo2)
% copy the PDF data from the untransformed
% graphic and add the result of multiplication
grafik5.data="q ".. cm ..grafik.data.." Q "

% store graphic in box 1002
tex.box[1004]=node.hpack(grafik5)

}

Here are our graphics \vskip 35mm
\noindent\hskip 15mm \copy1000 Default graphic
\vskip 35mm
\noindent\hskip 15mm \copy1001 Rotated graphic =  \directlua{tex.sprint(mymatrix.toinlinetex(mtx1))}
\vskip 35mm
\noindent\hskip 15mm \copy1002 Non-uniformly scaled graphic = \directlua{tex.sprint(mymatrix.toinlinetex(mtx2))}
\vskip 35mm
\noindent\hskip 15mm \copy1003 Rotation $\times$ scale = \directlua{tex.sprint(mymatrix.toinlinetex(combo))}
\vskip 35mm
\noindent\hskip 15mm \copy1004 Rotation $\times$ scale $\times$ translate =\directlua{tex.sprint(mymatrix.toinlinetex(combo2))}
\bye


## Resulting PDF

1Jan/11Off

$$\vec{F}_g=-F\frac{m_1 m_2}{r^2} \vec{e}_r$$