prepare manual for rest conversion
[PyX/mjg.git] / manual / graphics.tex
blob05d374f7b56f8c1d7f2750a59eb8a1a069ccd0cb
1 \chapter{Basic graphics}
3 \sectionauthor{J\"org Lehmann}{joergl@users.sourceforge.net}
5 \label{graphics}
7 \section{Introduction}
9 The path module allows one to construct PostScript-like
10 \textit{paths}, which are one of the main building blocks for the
11 generation of drawings. A PostScript path is an arbitrary shape
12 consisting of straight lines, arc segments and cubic B\'ezier curves.
13 Such a path does not have to be connected but may also comprise
14 several disconnected segments, which will be called \textit{subpaths}
15 in the following.
17 XXX example for paths and subpaths (figure)
19 Usually, a path is constructed by passing a list of the path
20 primitives \class{moveto}, \class{lineto}, \class{curveto}, etc., to the
21 constructor of the \class{path} class. The following code snippet, for
22 instance, defines a path \var{p} that consists of a straight line
23 from the point $(0, 0)$ to the point $(1, 1)$
24 \begin{verbatim}
25 from pyx import *
26 p = path.path(path.moveto(0, 0), path.lineto(1, 1))
27 \end{verbatim}
28 Equivalently, one can also use the predefined \class{path} subclass
29 \class{line} and write
30 \begin{verbatim}
31 p = path.line(0, 0, 1, 1)
32 \end{verbatim}
34 While already some geometrical operations can be performed with this
35 path (see next section), another \PyX{} object is needed in order to
36 actually being able to draw the path, namely an instance of the
37 \class{canvas} class. By convention, we use the name \var{c} for this
38 instance:
39 \begin{verbatim}
40 c = canvas.canvas()
41 \end{verbatim}
42 In order to draw the path on the canvas, we use the \method{stroke()} method
43 of the \class{canvas} class, i.e.,
44 \begin{verbatim}
45 c.stroke(p)
46 c.writeEPSfile("line")
47 \end{verbatim}
48 To complete the example, we have added a \method{writeEPSfile()} call,
49 which writes the contents of the canvas to the file \file{line.eps}.
50 Note that an extension \file{.eps} is added automatically, if not
51 already present in the given filename. Similarly, if you want to
52 generate a PDF file instead, use
53 \begin{verbatim}
54 c.writePDFfile("line")
55 \end{verbatim}
57 As a second example, let us define a path which consists of more than
58 one subpath:
59 \begin{verbatim}
60 cross = path.path(path.moveto(0, 0), path.rlineto(1, 1),
61 path.moveto(1, 0), path.rlineto(-1, 1))
62 \end{verbatim}
63 The first subpath is again a straight line from $(0, 0)$ to $(1, 1)$,
64 with the only difference that we now have used the \class{rlineto}
65 class, whose arguments count relative from the last point in the path.
66 The second \class{moveto} instance opens a new subpath starting at the
67 point $(1, 0)$ and ending at $(0, 1)$. Note that although both lines
68 intersect at the point $(1/2, 1/2)$, they count as disconnected
69 subpaths. The general rule is that each occurrence of a \class{moveto}
70 instance opens a new subpath. This means that if one wants to draw a
71 rectangle, one should not use
72 \begin{verbatim}
73 rect1 = path.path(path.moveto(0, 0), path.lineto(0, 1),
74 path.moveto(0, 1), path.lineto(1, 1),
75 path.moveto(1, 1), path.lineto(1, 0),
76 path.moveto(1, 0), path.lineto(0, 0))
77 \end{verbatim}
78 which would construct a rectangle out of four disconnected
79 subpaths (see Fig.~\ref{fig:rects}a). In a better solution (see
80 Fig.~\ref{fig:rects}b), the pen is not lifted between the first and
81 the last point:
83 \includegraphics{rects}
84 \centerline{Rectangle consisting of (a) four separate lines, (b) one open
85 path, and (c) one closed path. (d) Filling a
86 path always closes it automatically.}
88 \begin{verbatim}
89 rect2 = path.path(path.moveto(0, 0), path.lineto(0, 1),
90 path.lineto(1, 1), path.lineto(1, 0),
91 path.lineto(0, 0))
92 \end{verbatim}
93 However, as one can see in the lower left corner of
94 Fig.~\ref{fig:rects}b, the rectangle is still incomplete. It needs to
95 be closed, which can be done explicitly by using for the last straight
96 line of the rectangle (from the point $(0, 1)$ back to the origin at $(0, 0)$)
97 the \class{closepath} directive:
98 \begin{verbatim}
99 rect3 = path.path(path.moveto(0, 0), path.lineto(0, 1),
100 path.lineto(1, 1), path.lineto(1, 0),
101 path.closepath())
102 \end{verbatim}
103 The \class{closepath} directive adds a straight line from the current
104 point to the first point of the current subpath and furthermore
105 \textit{closes} the sub path, i.e., it joins the beginning and the end
106 of the line segment. This results in the intended rectangle shown in
107 Fig.~\ref{fig:rects}c. Note that filling the path implicitly closes
108 every open subpath, as is shown for a single subpath in
109 Fig.~\ref{fig:rects}d), which results from
110 \begin{verbatim}
111 c.stroke(rect2, [deco.filled([color.grey(0.95)])])
112 \end{verbatim}
113 Here, we supply as second argument of the \method{stroke()} method a
114 list which in the present case only consists of a single element,
115 namely the so called decorator \class{deco.filled}. As it name says,
116 this decorator specifies that the path is not only being stroked but
117 also filled with the given color. More information about decorators,
118 styles and other attributes which can be passed as elements of the
119 list can be found in Sect.~\ref{graphics:attributes}. More details on
120 the available path elements can be found in Sect.~\ref{path:pathitem}.
122 To conclude this section, we should not forget to mention that
123 rectangles are, of course, predefined in \PyX{}, so above we could
124 have as well written
125 \begin{verbatim}
126 rect2 = path.rect(0, 0, 1, 1)
127 \end{verbatim}
128 Here, the first two arguments specify the origin of the rectangle
129 while the second two arguments define its width and height,
130 respectively. For more details on the predefined paths, we
131 refer the reader to Sect.~\ref{path:predefined}.
133 \section{Path operations}
135 Often, one wants to perform geometrical operations with a path before
136 placing it on a canvas by stroking or filling it. For instance, one
137 might want to intersect one path with another one, split the paths at
138 the intersection points, and then join the segments together in a new
139 way. \PyX{} supports such tasks by means of a number of path methods,
140 which we will introduce in the following.
142 Suppose you want to draw the radii to the intersection points of a
143 circle with a straight line. This task can be done using the following
144 code which results in Fig.~\ref{fig:radii}
145 \verbatiminput{radii.py}
146 \includegraphics{radii}
147 \centerline{Example: Intersection of circle with line yielding two radii.}
148 Here, the basic elements, a circle around the point $(0, 0)$ with
149 radius $2$ and a straight line, are defined. Then, passing the \var{line}, to
150 the \method{intersect()} method of \var{circle}, we obtain a tuple of
151 parameter values of the intersection points. The first element of the
152 tuple is a list of parameter values for the path whose
153 \method{intersect()} method has been called, the second element is the
154 corresponding list for the path passed as argument to this method. In
155 the present example, we only need one list of parameter values, namely
156 \var{isects_circle}. Using the \method{at()} path method to obtain
157 the point corresponding to the parameter value, we draw the radii for
158 the different intersection points.
160 Another powerful feature of \PyX{} is its ability to split paths at a
161 given set of parameters. For instance, in order to fill in the
162 previous example the segment of the circle delimited by the straight
163 line (cf.\ Fig.~\ref{fig:radii2}), one first has to construct a path
164 corresponding to the outline of this segment. The following code
165 snippet yields this \var{segment}
166 \begin{verbatim}
167 arc1, arc2 = circle.split(isects_circle)
168 if arc1.arclen() < arc2.arclen():
169 arc = arc1
170 else:
171 arc = arc2
173 isects_line.sort()
174 line1, line2, line3 = line.split(isects_line)
176 segment = line2 << arc
177 \end{verbatim}
178 \includegraphics{radii2}
179 \centerline{Example: Intersection of circle with line yielding radii and
180 circle segment.}
181 Here, we first split the circle using the \method{split()} method passing
182 the list of parameters obtained above. Since the circle is closed,
183 this yields two arc segments. We then use the \method{arclen()}, which
184 returns the arc length of the path, to find the shorter of the two
185 arcs. Before splitting the line, we have to take into account that
186 the \method{split()} method only accepts a sorted list of parameters.
187 Finally, we join the straight line and the arc segment. For
188 this, we make use of the \verb|<<| operator, which not only adds
189 the paths (which could be done using \samp{line2 + arc}), but also
190 joins the last subpath of \var{line2} and the first one of
191 \var{arc}. Thus, \var{segment} consists of only a single subpath
192 and filling works as expected.
194 An important issue when operating on paths is the parametrisation
195 used. Internally, \PyX{} uses a parametrisation which uses an interval
196 of length $1$ for each path element of a path. For instance, for a
197 simple straight line, the possible parameter values range from $0$ to
198 $1$, corresponding to the first and last point, respectively, of the
199 line. Appending another straight line, would extend this range to a
200 maximal value of $2$.
202 However, the situation becomes more complicated if more complex
203 objects like a circle are involved. Then, one could be tempted to
204 assume that again the parameter value ranges from $0$ to $1$, because
205 the predefined circle consists just of one \class{arc} together with a
206 \class{closepath} element. However, this is not the case: the actual
207 range is much larger. The reason for this behaviour lies in the
208 internal path handling of \PyX: Before performing any non-trivial
209 geometrical operation with a path, it will automatically be converted
210 into an instance of the \class{normpath} class (see also
211 Sect.~\ref{path:normpath}). These so generated paths are already
212 separated in their subpaths and only contain straight lines and
213 B\'ezier curve segments. Thus, as is easily imaginable, they are much
214 simpler to deal with.
216 XXX explain normpathparams and things like p.begin(), p.end()-1,
218 A more geometrical way of accessing a point on the path is to use the
219 arc length of the path segment from the first point of the path to the
220 given point. Thus, all \PyX{} path methods that accept a parameter
221 value also allow the user to pass an arc length. For instance,
222 \begin{verbatim}
223 from math import pi
225 r = 2
226 pt1 = path.circle(0, 0, r).at(r*pi)
227 pt2 = path.circle(0, 0, r).at(r*3*pi/2)
229 c.stroke(path.path(path.moveto(*pt1), path.lineto(*pt2)))
230 \end{verbatim}
231 will draw a straight line from a point at angle $180$ degrees (in
232 radians $\pi$) to another point at angle $270$ degrees (in radians
233 $3\pi/2$) on a circle with radius $r=2$. Note however, that the mapping arc
234 length $\to$ point is in general discontinuous at the begin and the
235 end of a subpath, and thus \PyX{} does not guarantee any particular
236 result for this boundary case.
238 More information on the available path methods can be found
239 in Sect.~\ref{path:path}.
241 \section{Attributes: Styles and Decorations}
243 \label{graphics:attributes}
245 Attributes define properties of a given object when it is being used.
246 Typically, there are different kind of attributes which are usually
247 orthogonal to each other, while for one type of attribute, several
248 choices are possible. An example is the stroking of a path. There,
249 linewidth and linestyle are different kind of attributes. The linewidth
250 might be normal, thin, thick, etc, and the linestyle might be solid,
251 dashed etc.
253 Attributes always occur in lists passed as an optional keyword argument
254 to a method or a function. Usually, attributes are the first keyword
255 argument, so one can just pass the list without specifying the keyword.
256 Again, for the path example, a typical call looks like
258 \begin{verbatim}
259 c.stroke(path, [style.linewidth.Thick, style.linestyle.dashed])
260 \end{verbatim}
262 Here, we also encounter another feature of \PyX's attribute system. For
263 many attributes useful default values are stored as member variables of
264 the actual attribute. For instance, \code{style.linewidth.Thick} is
265 equivalent to \code{style.linewidth(0.04, type="w", unit="cm")}, that is
266 $0.04$ width cm (see Sect.~\ref{unit} for more information about
267 \PyX's unit system).
269 Another important feature of \PyX{} attributes is what is call attributed
270 merging. A trivial example is the following:
271 \begin{verbatim}
272 # the following two lines are equivalent
273 c.stroke(path, [style.linewidth.Thick, style.linewidth.thin])
274 c.stroke(path, [style.linewidth.thin])
275 \end{verbatim}
276 Here, the \code{style.linewidth.thin} attribute overrides the preceding
277 \code{style.linewidth.Thick} declaration. This is especially important
278 in more complex cases where \PyX defines default attributes for a
279 certain operation. When calling the corresponding methods with an
280 attribute list, this list is appended to the list of defaults.
281 This way, the user can easily override certain defaults, while leaving
282 the other default values intact. In addition, every attribute kind
283 defines a special clear attribute, which allows to selectively delete
284 a default value. For path stroking this looks like
285 \begin{verbatim}
286 # the following two lines are equivalent
287 c.stroke(path, [style.linewidth.Thick, style.linewidth.clear])
288 c.stroke(path)
289 \end{verbatim}
290 The clear attribute is also provided by the base classes of
291 the various styles. For instance, \class{style.strokestyle.clear}
292 clears all strokestyle subclasses and thus \class{style.linewidth} and
293 \class{style.linestyle}. Since all attributes derive from
294 \class{attr.attr}, you can remove all defaults using
295 \code{attr.clear}. An overview over the most important attribute typesprovided
296 by PyX is given in the following table.
297 \medskip
298 \begin{tableiii}{l|l|l}{textrm}{Attribute category}{description}{examples}
299 \lineiii{\class{deco.deco}}{decorator specifying the way the path is drawn}{\class{deco.stroked}, \class{deco.filled}, \class{deco.arrow}}
300 \lineiii{\class{style.strokestyle}}{style used for path stroking}{\class{style.linecap}, \class{style.linejoin}, \class{style.miterlimit}, \class{style.dash}, \class{style.linestyle}, \class{style.linewidth}, \class{color.color}}
301 \lineiii{\class{style.fillstyle}}{style used for path filling}{\class{color.color}, \class{pattern.pattern}}
302 \lineiii{\class{style.filltype}}{type of path filling}{\code{style.filltype.nonzero_winding} (default), \code{style.filltype.even_odd}}
303 \lineiii{\class{deformer.deformer}}{operations changing the shape of the path}{\class{deformer.cycloid}, \class{deformer.smoothed}}
304 \lineiii{\class{text.textattr}}{attributes used for typesetting}{\class{text.halign}, \class{text.valign}, \class{text.mathmode}, \class{text.phantom}, \class{text.size}, \class{text.parbox}}
305 \lineiii{\class{trafo.trafo}}{ransformations applied when drawing object}{\class{trafo.mirror}, \class{trafo.rotate}, \class{trafo.scale}, \class{trafo.slant}, \class{trafo.translate}}
306 \end{tableiii}
307 \medskip
309 XXX specify which classes in the table are in fact instances
311 Note that operations usually allow for certain attribute categories
312 only. For example when stroking a path, text attributes are not
313 allowed, while stroke attributes and decorators are. Some attributes
314 might belong to several attribute categories like colours, which are
315 both, stroke and fill attributes.
317 Last, we discuss another important feature of \PyX's attribute system.
318 In order to allow the easy customisation of predefined attributes, it
319 is possible to create a modified attribute by calling of an attribute
320 instance, thereby specifying new parameters. A typical example is to
321 modify the way a path is stroked or filled by constructing appropriate
322 \class{deco.stroked} or \class{deco.filled} instances.
323 For instance, the code
324 \begin{verbatim}
325 c.stroke(path, [deco.filled([color.rgb.green])])
326 \end{verbatim}
327 draws a path filled in green with a black outline. Here,
328 \code{deco.filled} is already an instance which is modified to fill
329 with the given color. Note that an equivalent version would
331 \begin{verbatim}
332 c.draw(path, [deco.stroked, deco.filled([color.rgb.green])])
333 \end{verbatim}
334 In particular, you can see that \class{deco.stroked} is already an
335 attribute instance, since otherwise you were not allowed to pass
336 it as a parameter to the draw method. Another example where
337 the modification of a decorator is useful are arrows. For instance, the following
338 code draws an arrow head with a more acute angle (compared to the
339 default value of $45$ degrees):
340 \begin{verbatim}
341 c.stroke(path, [deco.earrow(angle=30)])
342 \end{verbatim}
345 XXX changeable attributes