1%% Version 1.2.17
2\documentclass[12pt,letterpaper]{book}
3\usepackage{amsmath,amssymb,epic,eepic,pstricks,tikz,xcolor,comment}
4\usepackage[body={6in,8.5in}]{geometry}
5%\usepackage{makeidx}
6\usepackage{index}
7%\newindex{xfcns}{fdx}{fnd}{Index of Functions}
8\makeindex
9
10\usepackage{ifpdf}
11
12\usepackage[
13  \ifpdf pdftex, \else dvips, \fi
14  hyperfootnotes=false,
15  pdftitle={ePiX Tutorial and Reference Manual},
16  pdfauthor={Andrew D. Hwang},
17  pdfkeywords={LaTeX, Mathematical Figures, Plotting},
18  pdfstartview=FitH,
19  bookmarks=true,
20  colorlinks=true,
21  linkcolor=black]{hyperref}
22
23\setlength{\emergencystretch}{1.25em}
24\renewcommand{\thefigure}{\arabic{chapter}.\arabic{figure}}
25
26\newcommand{\code}[1]{\texttt{#1}}
27\newcommand{\filename}[1]{\texttt{#1}}
28\newcommand{\Key}[1]{\texttt{#1}}
29\newcommand{\URL}[1]{\texttt{#1}}
30
31%% \setlength{\topmargin}{0.5in}
32\newcommand{\ePiX}{\code{ePiX}}
33\newcommand{\ext}{\code{ePiX\_ext}}
34\newcommand{\epix}{\code{epix}}
35\newcommand{\eepic}{\code{eepic}}
36\newcommand{\C}{\code{C}}
37\newcommand{\CXX}{\code{C++}}
38\newcommand{\pyepix}{\code{Pyepix}}
39
40\DeclareMathOperator{\clip}{clip}
41
42\newcommand{\Header}[1]{\smallskip\noindent\texttt{#1}\quad}%
43
44%% Substitution commands easily removable by sed for texinfo:
45%% Remove recalcitrant chunks,
46\newcommand{\texicomment}{}
47\newcommand{\texicommentend}{}
48
49%% mark simple math,
50\newcommand{\teximath}[1]{$#1$}
51%% make function index entries,
52%\newcommand{\findex}[1]{\index[xfcns]{#1}}
53\newcommand{\findex}[1]{\ignorespaces}
54
55%% top-level division (first argument for texinfo node name)
56\newcommand{\texinfochapter}[2]{\chapter{#2}}
57\newcommand{\texinfoappendix}[2]{\chapter{#2}}
58%%\renewcommand{\subsection*}[1]{\subsection{#1}}
59
60\title{ \ePiX\ Tutorial and  \\ Reference Manual}
61\author{Andrew D. Hwang \\
62  Department\ of Math and CS \\
63  College of the Holy Cross}
64\date{Version 1.2.17, July, 2017}
65
66\begin{document}
67
68\maketitle
69
70\tableofcontents
71
72\texinfochapter{1}{Introduction}
73
74\ePiX, a collection of batch utilities, creates mathematically
75accurate figures, plots, and animations containing \LaTeX\ typography.
76The input syntax is easy to learn, and the user interface resembles
77that of \LaTeX\ itself: You prepare a scene description in a text
78editor, then ``compile'' the input file into a picture. \LaTeX- and
79web-compatible output types include a \LaTeX\ picture-like environment
80written with \code{PSTricks}, \code{tikz}, or \code{eepic} macros;
81vector images (\code{eps}, \code{ps}, and~\code{pdf}); and bitmapped
82images and movies (\code{png}, \code{mng}, and~\code{gif}).
83
84\ePiX's strengths include:
85
86\begin{itemize}
87\item Quality of output: \ePiX\ creates accurate, publication-quality
88  figures whose appearance matches that of \LaTeX.  Typography may be
89  put in a figure as easily as in an ordinary \LaTeX\ document.
90
91\item Ease of use: Figure objects and their attributes are specified
92  by simple, descriptive commands.
93
94\item Flexibility: Objects are described by attributes and Cartesian
95  location; as in \LaTeX, printed appearance is determined when the
96  figure is compiled. A well-designed figure can be altered
97  dramatically, yet precisely, with command-line switches or minor
98  changes to the input file.
99
100\item Power and extendibility: \ePiX\ inherits the power of \CXX\ as a
101  programming language; variables, data structures, loops, and
102  recursion can be used to draw complicated plots and figures with
103  just a few lines of input. External code can be incorporated in a
104  figure with a command line option or by using a Makefile.
105
106\item Economy of storage and transmission: For a document containing
107  many figures, a compressed tar file of the \LaTeX\ sources and
108  \ePiX\ files is typically a few percent the size of the compressed
109  PostScript file.
110
111\item License: \ePiX\ is \emph{free software}.
112  \index{Free software}
113  You are granted the right to use the program for whatever purpose,
114  and to inspect, modify, and re-distribute the source code, so long
115  as you do not restrict the rights of others to do the same. In
116  short, the license is similar to the terms under which theorems are
117  published.
118
119\end{itemize}
120
121
122\ePiX\ facilitates logical structuring of mathematical figures, as
123opposed to visual structuring (or WYSIWYG), analogous to the
124relationship between \LaTeX\ and a word processor. Stylistic
125defaults streamline the creation of simple figures, but there are few
126internal restrictions on the contents or appearance of a figure;
127aesthetic and practical decisions are left to you.
128
129If you are a:
130
131\begin{itemize}
132
133\item Potential user, you may wish to skip immediately to ``Software
134  Dependencies'' before investing additional time.
135
136\item New user, proceed from here until you have enough understanding
137  to run the software, then experiment with the samples files while
138  reading Chapter~\ref{chapter-started}, or return to the manual as
139  needed.
140
141\item More advanced user, browse at will, probably starting with
142  Chapter~\ref{chapter-ref-man}.
143
144\end{itemize}
145
146This manual is relatively conversational, and occasionally redundant,
147especially between portions meant for readers at different levels of
148familiarity. Throughout, you are assumed to be familiar with \LaTeX\
149and basic linear algebra: the description of points, vectors, lines,
150and planes in three-dimensional space. Other material, such as \CXX\
151syntax, is introduced as needed.
152
153
154\section{Software Dependencies}
155\label{section-software_deps}
156
157\index{Installation|(}
158\index{Mac OS X}
159
160If you run GNU/Linux, a BSD, or Solaris, you probably have (and can
161surely install) all the external software needed to use \ePiX.  On Mac
162OS~X, you will need the Apple developer tools and an X~server (such as
163XQuartz), and the free~\code{fink} package manager to build a GNU
164environment.  For Windows, you'll need to install Cygwin and several
165packages. Detailed instructions are given below.
166
167``Under the hood'', an input file is successively converted to a
168\LaTeX\ picture; \code{dvi}; PostScript, \code{pdf}~or \code{eps}; and
169if desired, to a bitmapped image or movie.  Four shell
170scripts---\epix, \code{laps}, \code{elaps}, and~\code{flix}---automate
171the various file format conversions.
172
173\ePiX\ consists of a \CXX\ library, header, and shell scripts, and
174requires GNU \code{bash} and a compiler \emph{for normal use}.  For
175complete functionality, you need \code{g++} (Version~3.2 or later),
176\code{bash}, a text editor (\ePiX\ works particularly well with
177\code{emacs}), a \LaTeX\ distribution, \code{Ghostscript}, \code{gv}
178(or your favorite PS/PDF previewer), and \code{GraphicsMagick}. GNU
179\code{grep} and \code{sed} are good to have.  You may need additional
180``developer packages'' (\code{binutils}, \code{make}) in order to
181build \ePiX.  The more up to date your software is, the better your
182experience is likely to be, but bleeding edge versions are not
183necessary, or even always desirable.
184
185Aside from their reliance on specific programs, \ePiX's shell scripts
186are written using Unix-style pathnames. Thus, the most straightforward
187way to use \ePiX\ is to install a GNU environment.
188
189Jay Belanger's \code{emacs} mode allows you to write, compile, and
190view \ePiX\ figures without leaving \code{emacs}. If you use another
191editor, you'll want to create template source files so you don't have
192to type boilerplate code each time you write a new figure.
193\index{Emacs@\code{emacs}}
194
195
196\subsection{Setting up an Environment Under  Windows}
197
198\index{Windows operating system|(}
199\begin{comment}
200Version~1.0.4 of \ePiX\ has been implemented in Python~2.2 by Andrew
201Sterian, making \ePiX\ available on any platform that supports Python,
202and without requiring a \CXX~compiler or~\code{bash}.  Python is a
203GPL-ed scripting language, and is available with a Windows installer
204and detailed instructions.  The easiest alternative for Windows users
205is probably to install Python~2.2 or later (if necessary) and
206\code{Pyepix}. The \code{pyepix} project home page is:
207\URL{claymore.engineer.gvsu.edu/~steriana/Python/index.html}
208\end{comment}
209
210Cygwin can be used to run \ePiX\ under Windows. Download
211\filename{setup.exe} from \URL{www.cygwin.com}, then install the
212packages you need. The following are recommended, and sufficient for
213the actions described in this manual.
214\begin{verbatim}
215(Archive)    bzip2, tar
216(Devel)      binutils, coreutils, gcc, gcc-g++, make, sed
217(Editors)    emacs, emacs-X11, vim
218(Graphics)   GraphicsMagick, ghostscript-base, ghostscript-x11, gv
219(Publishing) tetex (all)
220(Shells)     bash, bash-completion
221(X11)        X-start-menu-icons, X-startup-scripts,
222             XFree86-lib-compat, xorg-x11-fscl, xorg-x11-fsrv
223\end{verbatim}
224\index{Windows operating system|)}
225
226
227\section{Installation}
228
229\ePiX\ is distributed over the World-Wide Web as source code. Packages
230may be found at \URL{mathcs.holycross.edu/\~{}ahwang/epix/ePiX.html}
231The latest stable release is also on the CTAN mirrors, in the
232\code{graphics} directory.  (Some users of Red Hat have reported file
233permission problems when unpacking the CTAN tarballs. If you encounter
234this difficulty, please try downloading the sources from the project
235main page.)  Unpack the compressed tar file with the appropriate
236command:
237\begin{verbatim}
238  tar -zxvf epix-x.y.z.tar.gz
239  tar -jxvf epix-x.y.z.tar.bz2
240\end{verbatim}
241(\code{x.y.z}~is the version number) or, if your \code{tar}
242doesn't do decompression,
243\begin{verbatim}
244  gunzip -c epix-x.y.z.tar.gz | tar -xvf -
245  bzcat epix-x.y.z.tar.bz2 | tar -xvf -
246\end{verbatim}
247\code{cd} to the source directory, \filename{epix-x.y.z}.  The
248\filename{INSTALL} file contains detailed installation instructions.
249If you're impatient, the short of it is \code{./configure [--options];
250  make; make install}.  Run \code{./configure --help} for a list of
251options.
252
253By default, \ePiX\ installs in subdirectories of
254\filename{/usr/local}; if you want to install elsewhere, supply
255\code{./configure} with the appropriate \code{--prefix}. You may also
256want to consult \filename{POST-INSTALL} for information on setting
257your \code{PATH} variable so your shell can find \ePiX.  The manual
258and sample files are in \filename{/usr/local/share/doc/epix}.
259\index{Installation|)}
260
261
262\subsection{Development}
263
264There are two mailing lists, one for user questions, one for
265development discussion. Please visit
266\URL{savannah.nongnu.org/mail/?group=epix} to subscribe.
267
268
269\texinfochapter{2}{Getting Started}
270\label{chapter-started}
271
272This chapter describes the basics of creating figures in \ePiX\ for
273readers familiar with \LaTeX\ but completely new to~\CXX. No detailed
274knowledge of~\CXX\ is needed to use \ePiX, only a bit of grammar that
275is easily absorbed by example.
276
277Section~\ref{section-running} describes the commands (shell scripts)
278comprising \ePiX, and explains how to set up a graphical environment
279using standard *nix programs. Section~\ref{section-overview} briefly
280describes figure creation. Section~\ref{section-tutorial} presents a
281few files side-by-side with their output, and should be read at a
282computer so you can run the exercises.
283
284
285\section{Running \ePiX}
286\label{section-running}
287
288An ``input file'' is a human-written figure specification containing
289\ePiX\ commands; an ``output file'' is either a \LaTeX\ picture-like
290environment or a stand-alone vector graphic.  Conversion
291(``compiling'' a figure) is accomplished with four shell scripts,
292\code{laps}, \code{epix}, \code{elaps}, and \code{flix}.  Each script
293has a preferred extension for its input files, and is invoked with a
294command of the form
295\begin{verbatim}
296  <script> [options] <input file(s)>
297\end{verbatim}
298Often, no options are necessary.  \code{<script> --help}
299describes \code{<script>}'s options.
300\texicomment
301Figure~\ref{fig-programs} (page~\pageref{fig-programs}) diagrams the
302shell scripts and the file types they process.
303\texicommentend
304
305By default, output file names are constructed by replacing the input
306extension with the (preferred) output extension. For brevity,
307extensions may be omitted. If the script has doubts about your intent,
308it proceeds with default behavior and prints a warning message.
309
310The author is a great fan of \Key{TAB} completion, under which a
311shell, based on what has been typed so far, automatically fills in a
312command when the \Key{TAB} key is pressed.  \ePiX\ comes with code
313snippets that complete intelligently when the first part of a command
314is one of the shell scripts. For example, if command completion is
315active, typing \code{epix} \Key{TAB} prints only names of \code{epix}
316input files. To use this feature, you must install Ian MacDonald's
317\code{bash completion} package. The \filename{INSTALL} and
318\filename{POST\_INSTALL} files contain details.
319
320
321\subsection*{Shell Scripts}
322
323\subsubsection*{\code{laps}}
324
325\code{laps} performs \LaTeX\ to PostScript/PDF conversion, and is
326independent of the rest of \ePiX. By default, \code{laps} invokes
327\LaTeX~and \code{dvips}. The option \code{--pdf} creates a PDF~file by
328post-processing the PostScript with~\code{ps2pdf}.  Other \TeX-family
329processors (\code{pslatex}, \code{pdftex}, etc.) may be used instead
330of~\LaTeX\ by invoking \code{laps} with an appropriate option.
331
332
333\subsubsection*{\code{epix}}
334
335\code{epix} compiles an input file into a \LaTeX\ picture.  The input
336file should have extension \filename{xp} (for eXtended Picture).  Jay
337Belanger's \code{emacs} mode is Highly Recommended; the installation
338procedure can be found in the \filename{POST\_INSTALL} file. When this
339mode is active, \code{emacs} automatically inserts a preamble template
340when a new \filename{xp} file is created. In addition, you can peruse
341\ePiX's info file, or format, compile, and preview files, all from
342within \code{emacs}.
343\index{Emacs@\code{emacs}}
344
345Output files from the script \code{epix} have extension
346\filename{eepic}, after Conrad Kwok's enhancements to the \LaTeX\
347picture environment. In Version~1.2, however, an output file may
348contain \code{PSTricks} or \code{tikz} macros instead of \code{eepic}
349macros.  A command such as \verb+\input{myfile.eepic}+ incorporates an
350output file into a \LaTeX\ document. The preamble must contain
351\code{usepackage} lines appropriate to the output format.
352\texicomment
353\begin{center}
354  \begin{tabular}{cc}
355    Format & Required Package(s) \\
356    \hline
357    \code{eepic} & \code{epic,eepic,xcolor,rotating} \\
358    \code{pst}   & \code{pstricks,rotating} \\
359    \code{tikz}  & \code{tikz,rotating}
360  \end{tabular}
361\end{center}
362\texicommentend
363
364
365\subsubsection*{\code{elaps}}
366
367\code{elaps} creates stand-alone vector images (\filename{eps}~or
368\filename{pdf}) from \code{epix} input files or \filename{eepic}
369figures, even those not produced with \code{epix}.  \code{elaps}
370automatically loads the \LaTeX\ packages needed for features described
371in this manual. Additional \LaTeX\ packages and \code{dvips} options
372may be specified on the command line.  An \code{elaps} output file is
373placed in a \LaTeX\ document with an \verb+\includegraphics+ command;
374the preamble must contain \verb+\usepackage{graphicx}+ [sic].
375
376
377\subsubsection*{\code{flix}}
378
379\code{flix} creates bitmapped images and movies,
380Section~\ref{section-animation}. Input files should have extension
381\filename{flx}, and must contain a valid \code{epix} header as well as
382additional code. Jay Belanger's \code{emacs} mode facilitates creation
383of \code{flix} files.
384
385
386\section{The Drawing Model}
387\label{section-overview}
388
389To draw a figure manually, you select a sheet of paper of appropriate
390size and add paths, markers, and labels. These scene elements have
391attributes (line color, line width, fill color, font size, etc.)\
392affecting their appearance.
393
394\index{canvas}%
395\ePiX's drawing model behaves similarly.  A \code{picture} command
396sets the \emph{canvas} (or logical drawing area, a Cartesian
397rectangle) and the true size of the final figure. A \code{begin}
398command initializes the ``virtual paper'' for drawing. Subsequent
399\emph{drawing commands} add objects to the scene: lines, curves,
400function plots, labels, and the like. The printed appearance of scene
401elements is determined by the current ``attribute state'' and
402controlled by \emph{style declaration} which remain in effect until
403superseded. Finally, an \code{end} command closes the figure and
404prints it to the output file.
405
406In this manual, command descriptions follow a few
407conventions. Optional arguments are enclosed in square brackets. A
408\code{len} argument is either a number (representing a length in
409\code{pt}) or a double-quoted string containing a number and a
410two-letter \LaTeX\ length unit, such as \code{"1.5pt"} or
411\code{"6cm"}.  A \code{color} argument is a named primary
412(\code{Red()}, \code{Cyan()}, \code{White()}, etc.), or a \code{Color}
413specified by densities (\code{RGB(r,g,b)}, \code{CMY(c,m,y)}, etc.)
414
415\begin{itemize}
416
417\item Fill color: \code{fill(color)}, \code{nofill()}.
418
419\item Line color and width: \code{plain([color])},
420  \code{bold([color])}.
421
422\item Text size: \code{font\_size([size])}, returns to
423  \code{normalsize} if no argument is given.
424
425\end{itemize}
426
427\noindent A complete list of style commands is found in
428Section~\ref{section-quickref}, starting on
429page~\pageref{section-quickref}.
430
431To handle three-dimensional scenes, a \code{camera} performs point
432projection from a selected spatial location to the canvas. As a user,
433you'll need to control relatively few of the \code{camera}'s
434parameters. Keep in mind, however, that elements are added to a scene
435in the same order their commands appear in the output file, and that
436later elements generally cover earlier ones. Some three-dimensional
437scenes require manual ordering of the input file; such ordering is
438dependent on the \code{camera}'s location.
439
440By default, \ePiX\ draws thin, solid, black lines, performs no filling
441of regions, prints text in a 12~pt Roman font, and looks down the
442\teximath{z}~axis from a large distance, giving orthogonal projection
443on the \teximath{(x,y)}~plane. When the \code{camera} is moved, the
444\teximath{z}~axis points vertically up on the page.
445
446
447\section{Tutorial}
448\label{section-tutorial}
449
450This section presents sample input files side-by-side with their
451output so you can compare what you write with what you'll see on the
452screen or page.  \ePiX\ provides standard drawing capabilities, but
453like all software has its own idioms and personality. The basic
454syntax, which comes from \code{C}/\CXX, should be mostly
455self-explanatory. One-line comments begin with the
456string~``\verb+//+''.
457
458
459%%\index{Emacs@\code{emacs}}
460\index{Graphical interface}
461To use the sample files interactively, you'll need working software:
462\filename{bash}, \filename{emacs}, \ePiX, \filename{g++},
463\filename{gv}, and a running X~server. To complete your ``GUI'',
464start~\filename{gv} and select ``Watch file'' from the ``State''
465menu. The loaded file will update automatically when it changes.
466
467Create a ``scratch'' directory, \code{cd} into it, and run the command
468\begin{verbatim}
469  tar -zxf /usr/local/share/doc/epix/sample_src.tar.gz
470\end{verbatim}
471(Change the path as appropriate for your installation.)  This unpacks
472copies of the sample files into your scratch directory, including all
473the files mentioned in this manual. The \filename{README} file serves
474as a table of contents.
475
476Open a sample file in \filename{emacs}, compile it from the drop-down
477menu (or with the keyboard command), then open the \filename{EPS} file
478in~\filename{gv}. Now you're ready to follow the tutorial
479interactively. A few suggested exercises are included with each
480file. Naturally, as you study more files, you'll be able to make more
481interesting changes on your own.
482
483
484\subsection*{Basic Drawing}
485
486The first sample, \filename{hello.xp}, contains code needed to specify
487the figure's size, followed by the classic greeting. The \code{border}
488command draws a box around the figure in the specified color and
489width, and serves here merely to delimit the output from the
490surrounding page.
491\begin{verbatim}
492/* -*-ePiX-*- */
493#include "epix.h"      // These lines are analogous
494using namespace ePiX;  // to a usepackage command.
495
496int main()
497{
498  picture(P(-1,-1), P(1,1), "2 x 1in"); // corners, true size
499
500  begin(); // ---- Figure body starts here ----
501
502  border(Black(), "1pt"); // color, line width
503
504  font_size("Huge");  // May be any font size, e.g. "scriptsize"
505  label(P(0,0), "Hello, world!");
506
507  end();   // ---- End figure; write output file ----
508}
509\end{verbatim}
510
511\begin{center}
512  \input{hello.eepic}
513\end{center}
514
515\begin{itemize}
516
517\item Change the color and width of the
518  border. (\code{RGB(r,g,b);} creates an RGB color, CMY colors are
519  analogous. Named primaries are available. The densities should be
520  between \teximath{0}~and \teximath{1} for ``expected'' behavior.)
521
522\item Add \code{backing(Cyan());} after the \code{border} command.
523
524\item Put the command \code{crop\_ellipse();} before the \code{border}
525  command. Permute the \code{crop\_ellipse} command with the
526  \code{border} and \code{backing} lines, and note how the attribute
527  (\code{crop}) affects objects (\code{border}, \code{backing}).
528
529\end{itemize}
530
531
532\subsubsection*{Geometric Objects}
533
534Our next file uses simple objects to draw a 2-D house-and-sun scene.
535
536\begin{verbatim}
537int main()
538{
539  picture(P(0,0), P(5,2), "3.75 x 1.5in");
540
541  begin();
542
543  triangle(P(0.9, 1), P(3.1, 1), P(2, 1.5)); // vertices
544  circle(P(4,1.5), 0.25); // center and radius
545
546  rect(P(1,0), P(3,1)); // opposite corners
547
548  fill(Black(0.1));     // light gray
549  rect(P(2.3,0), P(2.7,0.8)); // the door
550  nofill();
551
552  bold();               // draw thicker lines
553  grid(P(1.4, 0.2), P(2, 0.6), 2, 2); // corners, number of squares
554
555  line(P(xmin(), 0), P(xmax(), 0));   // endpoints
556
557  end();
558}
559\end{verbatim}
560
561\begin{center}
562  \input{objects.eepic}
563\end{center}
564
565\begin{itemize}
566
567\item Add declarations such as \code{bold(RGB(1,0.9,0.5))} or
568  \code{fill(Yellow())} to color the scene. (Color and filling are
569  orthogonal attributes.)
570\end{itemize}
571
572\noindent The sample file \filename{house.flx} uses loops to draw
573gradient fills of the lawn, sky, and sun, and animates a sunset.
574
575
576\subsubsection*{Function Plotting}
577
578Plotted functions must be defined in the ``preamble'', before
579\code{main}. ``High-level'' elements---coordinate axes and grids, axis
580labels, and graphs---are drawn with mnemonically-named commands.
581\begin{verbatim}
582// double = double-precision floating point
583double f(double x) { return 0.75*Sin(x) - 0.25*Sin(2*x); }
584
585int main()
586{
587  picture(P(-2,-1), P(2,1), "5 x 1in"); // [-2,2] x [-1,1]
588
589  begin();
590  revolutions(); // set angle units, [0,1] = one turn
591
592  h_axis(16); // axes w/default endpts
593  v_axis(4);
594  h_axis_labels(4, P(0,-4), b); // shift down 4pt, align below
595
596  plain(Red());
597  plot(f, xmin(), xmax(), 120); // use 120 intervals
598
599  end();
600}
601\end{verbatim}
602
603\begin{center}
604  \input{plotting.eepic}
605\end{center}
606
607\begin{itemize}
608
609\item Define and plot some different functions; adjust the bounding
610  box as necessary. (Use repeated multiplication for polynomials.
611  The \code{polarplot} command graphs \teximath{r=f(\theta)}.)
612
613\item Change the arguments to \code{h\_axis\_labels}. The first
614  specifies the number of intervals to label; the second gives the
615  label offset in~\code{pt}. The last puts each label below~(\code{b})
616  its Cartesian location.
617
618\end{itemize}
619
620
621\subsubsection*{Multivariable Plotting}
622
623Functions of two or three variables are defined just like functions of
624one variable, but for plotting the return type must be a
625point~(\code{P}), not a real number~(\code{double}). The \code{domain}
626class specifies the set of inputs to plot.
627
628\begin{verbatim}
629P f(double r, double th)
630{
631  return P(r*Cos(th), r*Sin(th), pow(r, 3)*Cos(3*th));
632}
633
634int main()
635{
636  picture(P(-1,-1), P(1, 1), "2 x 1in");
637  begin();
638  pst_format();     // use PSTricks macros for output
639
640  // corners ([0,1] x [0,2\pi]) and fineness
641  // (8x40 rectangles, plotted at 16x120 resolution)
642  domain R(P(0,0), P(1, 2*M_PI), mesh(8,40), mesh(16,120));
643
644  camera.at(P(3,1,2)); // set the viewpoint
645  arrow(P(0,0,0), P(1.25,0,0)); // coordinate axes
646  arrow(P(0,0,0), P(0,1.25,0));
647
648  plain(Blue(1.2)); // line color and width
649  fill(Yellow());   // shading color
650  surface(f, R);
651
652  end();
653}
654\end{verbatim}
655
656\begin{center}
657  \input{plotting2.eepic}
658\end{center}
659
660
661\subsubsection*{Loops and Control Structures}
662\label{taylor_poly}
663
664A function can be defined by an arbitrary algorithm, and a
665\code{domain} may be used to plot a family of functions for several
666values of one variable.
667
668\begin{footnotesize}
669\begin{verbatim}
670P sin_n(double x, double n)     // Taylor polynomial of sin x
671{
672  const int N((int) floor(n));  // convert n to an index bound
673  const double sqx(-pow(x, 2)); // -x^2
674  double val(x), summand(x);
675
676  for (int i=1; i <= 2*N+1; i += 2)
677    {
678      summand *= (sqx/((i+1)*(i+2)));   // (-1)^i x^{2i+1}/(2i+1)!
679      val += summand;
680    }
681
682  return P(x, val);    // return (x, y)
683}
684
685int main()
686{
687  picture(P(0, -1), P(6*M_PI, 1), "5 x 1in");
688
689  begin();
690
691  set_crop();
692  bold(Green());
693  plot(Sin, 0, xmax(), 120);
694
695  domain R(P(0,1), P(6*M_PI, 41), mesh(60, 40), mesh(120, 40));
696  for (int i=3; 0 <= i; --i)  // print in descending degree
697    {
698      bold(RGB(0.25*i, 0, 1-0.25*i)); // degree-dependent color
699      plot(sin_n, R.slice2(5*i+1));   // plot for n = 5i+1
700    }
701  end();
702}
703\end{verbatim}
704\end{footnotesize}
705
706\begin{center}
707  \input{plotting3.eepic}
708\end{center}
709
710
711\subsubsection*{Page Layout}
712
713Page layout can be composed from sub-pages with \code{screen} objects.
714In the loop body below, objects are added to the ``active''
715\code{screen}, then \code{inset} into the ``canvas'', the screen
716representing the entire figure.
717
718\begin{verbatim}
719P f(double u, double v)
720{
721  return P((u-v)*(u+v), 2*u*v, u);
722}
723
724int main()
725{
726  picture(P(0,0), P(2,3), "5x7.5in"); // overall size
727
728  begin();
729
730  domain R(P(-1,-1), P(1,1), mesh(12,12), mesh(24,24));
731
732  for (int i=0; i<2; ++i)
733    for (int j=0; j<3; ++j)
734      {
735        screen my(P(-3,-3), P(3,3));
736        activate(my);
737        border(Red(0.6), "1pt");
738        // frame-dependent viewpoint
739        camera.at(sph(10, (2*j+i+1)*M_PI/8, M_PI/6));
740
741        plot(f, R);
742        arrow(P(0,0,0), 2*E_1);
743        arrow(P(0,0,0), 2*E_2);
744        // SW corner at (i, 2-j), padded by 0.05 on all sides
745        inset(P(i+0.05,2.05-j), P(i+0.95,2.95-j));
746      }
747
748  end();
749}
750\end{verbatim}
751
752\begin{center}
753  \input{layout.eepic}
754\end{center}
755
756
757\section{\CXX\ Basics}
758
759\index{Cplusplus@\CXX|(}
760An \ePiX\ source file is a \CXX~program. If you've successfully
761modified and compiled the sample files, you know enough~\CXX\ to use
762\ePiX. In the author's experience, \code{C}~grammar suffices for most
763applications.  An excellent introduction to definitions of functions
764and variables, control statements, and overall program structure is
765Kernighan~and Ritchie's \emph{The \code{C} Programming Language},
766second edition~\cite{KnR}.
767
768
769\subsection{File Format}
770
771\index{Emacs@\code{emacs}}
772Jay Belanger's \code{emacs} mode for \code{ePiX} inserts a file
773template when an empty buffer is opened with the extension~\code{xp}.
774This section explains the purposes served by the template. A few
775additional remarks may help you avoid basic syntax pitfalls.
776
777A \CXX\ file consists of ``statements'', analogous to ordinary
778sentences. Common types include \emph{declarations} (which
779``register'' a function, variable, or type name with the compiler),
780\emph{definitions} (which assign meaning to declared names), and
781\emph{function calls} (which cause a named function to execute).  Most
782statements in an \ePiX\ input file are function calls (``commands'').
783Plain declarations are relatively rare in user files, since a
784definition serves to declare any new names that it contains.
785
786Every statement ends with a semicolon, and conventionally a file
787contains at most one statement per line.  The compiler ignores
788nearly all whitespace (spaces, tabs, and newlines), which should be
789used freely to make files easy to read.  Other punctuation
790(periods, commas, (semi)colons, parentheses, braces, and quotes)
791dictates file parsing, and must adhere stringently to grammar.
792
793An \ePiX\ file always begins with the lines
794\findex{include}
795\begin{verbatim}
796#include "epix.h" // N.B. pre-processor directive, no semicolon
797using namespace ePiX;
798\end{verbatim}
799The first line is analogous to a \LaTeX\ \code{usepackage} command: It
800loads the contents of the ``header'' file \filename{epix.h}, importing
801the names of commands provided by~\ePiX.  To avoid name conflicts,
802\ePiX's commands are enclosed in a ``namespace''. For example, the
803\code{label} command is actually known to the compiler as
804\code{ePiX::label}. The second line above tells the compiler to apply
805the prefix tacitly.
806
807
808\subsection{Variables and Functions}
809%% \index{Variable}\index{Variable!names}
810%% \index{Function}\index{Function!names}
811
812Definitions of variables and functions play the same role in a figure
813that macro definitions play in a \LaTeX\ document: gathering and
814organizing information on which the figure depends. A variable is
815defined by supplying its type, name, and initial value. By far the
816most common data types in~\ePiX\ are \code{double} (double-precision
817floating point number), \code{P}, and \code{int}. The name of a
818variable may only consist of letters (including the underscore
819character) and digits, and must begin with a letter:
820\begin{verbatim}
821my_var, var2,    MY_var, aLongVariableName;  // valid
822my-var, 2var, \v@riable, $x, ${MY_VARIABLE}; // not valid
823\end{verbatim}
824Variable names are case-sensitive, and numerous (non-universal)
825conventions govern the significance of capitalization. Generally, make
826names descriptive but not unwieldy, and avoid language keywords (such
827as \code{const}, \code{true}, \code{double}, \code{class}, or
828\code{public}) and names that begin with an underscore.
829
830A function accepts ``arguments'' and ``returns a value''. To define a
831function in~\CXX, specify the return type, the name of the function,
832the types of the arguments, and the algorithm by which the value is
833computed from the inputs.  The code block
834\begin{verbatim}
835double f(double x)
836{
837  return sqrt(1-x*x);
838}
839\end{verbatim}
840defines the \code{double}-valued function~\teximath{f} of one \code{double}
841variable defined by the formula \teximath{f(x)=\sqrt{1-x^2}}.
842
843
844\subsection{Comments}
845
846\CXX\ has two types of comments. \code{C}-style comments, which may
847span several lines, are delimited by the strings \code{/*}~and
848\code{*/}. One-line comments, analogous to the \LaTeX~\code{\%}, are
849begun with \code{//}. A one-line comment may appear within a multi-line
850comment, but a \code{C}-style comment may not; the compiler will
851mistake the first~\code{*/} it encounters as the end of the current
852multi-line comment.
853
854
855\subsection{Program Execution}
856
857All the ``action'' in a \CXX\ program occurs inside the special
858function~\code{main}. Running a compiled \CXX~program is viewed by the
859operating system as calling the program's \code{main} function. The
860return value (an \code{int}) is the program's exit status.  The
861contents of the output file start with \code{begin()} and terminate
862with \code{end()}.  Intervening statements constitute the \emph{body}
863of the file.
864
865In \CXX, a function may not be defined inside another function.
866Variables may be defined inside \code{main}, but functions cannot be.
867
868
869\subsection{Strings and Raw Output}
870
871\index{string}%
872\index{Backslash character}%
873In \CXX, a \code{string} is a sequence of characters. Most
874\code{string}s in \ePiX\ input files are \emph{literals},
875double-quoted \code{string}s whose value is read from the input. In a
876string literal, backslash is an escape character; a single backslash
877is produced by a double backslash in the input file.  Certain letters
878have special meanings when backslash-escaped, including ``\verb+\n+''
879(newline) and ``\verb+\t+'' (\Key{TAB}).  Unlike~\LaTeX, \CXX~does not
880require a space to separate an escape sequence from following text;
881the string ``\verb+\\textwidth+'' literally represents a \LaTeX\
882command, while ``\verb+\textwidth+'' is read ``\code{TABextwidth}'' by
883the compiler.
884
885\index{Self-contained figure}%
886\index{Writing directly to output file}%
887\index{Output file!writing directly to}%
888Though not commonly needed, raw text can be printed to the output
889file. The functions \code{write}, \code{pre\_write}, and
890\code{post\_write} accept \code{string} arguments. \code{write} prints
891its argument where the call appears in the input file. The other
892functions print their arguments before or after the completed picture,
893respectively. These commands must be in the file body.  As an
894application, a complete \LaTeX\ \code{figure} environment (with
895caption and label) can be produced by an \ePiX\ file,
896Figure~\ref{fig-captioned}.
897
898\findex{pre\_write}
899\findex{post\_write}
900\findex{write}
901\begin{figure}
902\begin{footnotesize}
903\begin{verbatim}
904#include "epix.h"
905using namespace ePiX;
906
907int main()
908{
909  picture(P(-1,-1), P(1,1), "10cm x 3in);
910  begin();
911  pre_write("\\begin{figure}[hbt]"); // comes before the picture
912
913  post_write("\\caption{A \\LaTeX\\ figure.}"); // and after
914  post_write("\\end{figure}");
915
916  < ... other ePiX commands ... >
917  write("%% A comment near the end, but inside the picture.");
918  end();
919} // End of main()
920\end{verbatim}
921\end{footnotesize}
922\caption{Generating a self-contained figure in \ePiX.}
923\label{fig-captioned}
924\end{figure}
925
926
927\subsection{Conditionals and Loops}
928
929An algorithm's behavior usually depends on internal state. A
930\emph{conditional statement} causes blocks of code to be executed
931according to criteria. A \emph{loop} repeatedly executes a code
932block, usually changing the values of variables in a predictable way,
933so that the loop exits after finitely many traversals.
934
935\texicomment
936Figure~\ref{fig-gcd} illustrates conditionals and loops with
937Euclid's algorithm for the greatest common divisor. Three pieces of
938notation require explanation: \code{j\%i} means~``\teximath{j\pmod i}'',
939\code{||} is logical~``or'', and \code{==} is ``test for equality''.
940(A single~``\code{=}'' is the assignment operator.)
941
942\index{Function!Euclidean algorithm}
943\begin{figure}[hbt]
944\begin{footnotesize}
945\begin{verbatim}
946int gcd (int i, int j)
947{
948  int temp(i);  // initialization syntax
949    if (i==0 || j==0)
950        return i+j;    // define gcd(k,0) = k
951
952    else {
953        if (j < i)     // swap them
954            {
955                temp = j;
956                j = i;
957                i = temp;
958            }
959        // the work is done here...
960        while (0 != (temp = j%i)) // assign temp, test for zero
961            {
962                j = i;
963                i = temp;
964            }
965        return i;
966    }
967}
968\end{verbatim}
969\end{footnotesize}
970\caption{Euclid's division algorithm in~\CXX.}
971\label{fig-gcd}
972\end{figure}
973\texicommentend
974
975%% \noindent For details on conditionals, or for more advanced techniques
976%% of \CXX\ programming, please consult a textbook or online tutorial.
977\index{Cplusplus@\CXX|)}
978
979%% Force previous two figures onto the same page
980%%\clearpage
981
982\section{Animation}
983\label{section-animation}
984
985\index{Animation|(}
986\ePiX\ is well-suited to the creation of mathematically accurate
987animations: If a figure depends suitably upon a ``time'' parameter,
988then a loop can be used to draw the entire figure for multiple time
989values, yielding successive ``snapshots'' of the figure as time
990progresses. The shell script~\code{flix} automates the process of
991compiling a suitable input file into a collection of \filename{png}s
992and assembling these frames into a \filename{mng}~or \filename{gif}
993animation. GraphicsMagick is the image-handling engine.
994
995A \code{flix} file is an \code{epix} file with two restrictions:
996\begin{itemize}
997  \item The \code{double} variable \code{tix()} is used as
998  ``clock''.
999
1000  \item \code{main} accepts two command line arguments and sets
1001  \code{tix()} accordingly.
1002\end{itemize}
1003\index{Emacs@\code{emacs}}
1004Jay Belanger's \code{emacs} mode recognizes the file
1005extension~\filename{.flx} and inserts template code if an empty buffer
1006is opened. Creation of \code{flix} files is as easy as creation of
1007\code{epix} files.  The \filename{samples} directory contains a
1008handful of \code{flix} files that may be consulted for ideas.
1009
1010By default, \code{flix} creates movies with 24~frames, in which
1011\code{tix()} runs from~0 to~1, and animates at
1012\teximath{0.08}~sec/frame.  These and other parameters can be changed
1013with command-line options.
1014
1015A ``typical'' \code{.flx} file may take 30~seconds to a few minutes to
1016compile, depending on the number of frames and the complexity of each
1017frame. To facilitate debugging, \code{elaps} can be run on a
1018\code{flix} file. \code{elaps} runs in a fraction of the time, and if
1019\code{elaps} can't produce a viewable image, \code{flix} will surely
1020fail.
1021\index{Animation|)}
1022
1023
1024\section{Layout Tricks}
1025\label{section-layout}
1026\index{Layout}
1027
1028\subsection{Stereograms}
1029\index{Stereograms}
1030Stereograms are created by drawing a single scene twice from slightly
1031different points of view. To create a stereogram with \ePiX, write a
1032``scene'' function containing the necessary drawing commands, then set
1033the camera appropriately and call the scene function twice, once for
1034each frame.
1035
1036\subsubsection*{Crossed-Eyes Stereograms}
1037
1038The sample files \filename{lorenz.xp}~and \filename{twisted\_cubic.xp}
1039use page layout to draw crossed-eyes stereograms. For each frame,
1040create and activate a \code{screen}, set the camera, and call the
1041scene function. The frames are inset side by side in the final
1042picture. For a crossed-eyes stereogram, the frame from the
1043``rightmost'' camera position is placed on the left.
1044
1045\subsubsection*{Bi-Color Stereograms}
1046
1047The sample files \filename{cube.flx}~and \filename{mirrorball.flx}
1048contain animated red-cyan stereograms, suitable for viewing with 3-D
1049glasses. The technique works best with black-and-white line drawings,
1050but the basic approach is the same as for crossed-eyes stereograms:
1051Create a scene function and call it twice, setting the camera
1052appropriately. Layout is unnecessary since the frames are superposed.
1053Pen colors should be close to red and cyan, but ``optimal'' choices
1054depend on one's eyes and 3-D glasses.
1055
1056\subsubsection*{Stereographic Movies}
1057
1058Either form of stereogram can be animated in a \code{.flx} file, but
1059keeping one's eyes properly crossed requires practice while most
1060people can instantly see depth with 3-D glasses. As always when using
1061\code{flix}, debug the scene with \code{elaps} before compiling a
1062movie. If a stereoscopic effect is difficult to see in a still image,
1063it will be even harder to perceive in a movie.
1064
1065
1066\subsection{Inset Images}
1067
1068\ePiX\ can place external images into a figure, similarly to
1069Rolf Niepraschk's \code{overpic} package. You provide the Cartesian
1070center point, the file name, and optionally the true height and/or
1071width of the image:
1072\findex{label}
1073\begin{verbatim}
1074  label(P(a,b), "\\includegraphics[width=w,height=h]{file}");
1075\end{verbatim}
1076This effect requires the \filename{graphicx} package. When compiling a
1077stand-alone graphic containing an external image, you must specify the
1078\filename{graphicx} package on the command line: \code{elaps -p
1079graphicx <file>}
1080
1081\texicomment
1082\begin{figure}[hbt]
1083  \begin{center}
1084    \input{ePiX.eepic}
1085  \end{center}
1086  \caption{Visual guide to \ePiX's shell scripts}
1087  \label{fig-programs}
1088\end{figure}
1089\texicommentend
1090
1091
1092\texinfochapter{3}{Reference Manual}
1093\label{chapter-ref-man}
1094
1095This chapter details \ePiX's capabilities, discussing attributes and
1096data types, and listing available commands in the form
1097\begin{verbatim}
1098  label(P posn, [P offset], string text, [align]);
1099  circle(P ctr, double rad=1, normal=P(0,0,1));
1100\end{verbatim}
1101As in Chapter~\ref{chapter-started}, function arguments are given by
1102type (\code{P}, \code{double}, \code{string}, etc.)\ and name, or by
1103name alone if the type is clear. Optional arguments are enclosed in
1104square brackets. A few argument types, such as \code{[align]} above,
1105admit only a small number of values; these cases are explained when
1106the corresponding command is first introduced.
1107
1108A name followed by an equals sign and a value indicates a default
1109argument; if omitted in an input file, the compiler substitutes the
1110default value. Only trailing arguments may be specified this way.  For
1111example, if the \code{rad} argument of the \code{circle} command is
1112omitted, the \code{normal} argument \emph{must} be omitted as well.
1113
1114In an input file, only an argument's value is given, not the type:
1115\begin{verbatim}
1116  label(P(0,0), P(0,-4), "Hello world", b);
1117  circle(P(0,-0.25), sqrt(2)); // use default normal
1118\end{verbatim}
1119
1120\index{Length}%
1121\index{Color}%
1122Generally, \code{len} signifies either a number (representing a length
1123in \code{pt}) or a double-quoted string containing a number and a
1124two-letter \LaTeX\ length unit, such as \code{"1.5pt"} or
1125\code{"6cm"}. \code{color} represents a \code{Color} object
1126constructed from a named primary (\code{Blue()}, \code{Magenta(0.7)},
1127etc.), a color specification (\code{RGB(r,g,b)}, \code{CMY(c,m,y)},
1128etc.), or an operator applied to an existing \code{Color}.
1129
1130
1131\section{File Structure}
1132
1133An \ePiX\ input file constitutes a short \CXX\ program. When this
1134program is compiled and run by one of the shell scripts, it creates a
1135figure file suitable for inclusion in \LaTeX.
1136
1137\index{Preamble}
1138Like a \LaTeX\ document, an \ePiX\ file contains a \emph{preamble},
1139which sets up a drawing environment, and a \emph{body}, which contains
1140actual figure-generating commands.  The minimal file has the form
1141\findex{picture}
1142\findex{begin}
1143\findex{end}
1144\begin{verbatim}
1145#include "epix.h"  // N.B. no semicolon
1146using namespace ePiX;
1147
1148int main() {
1149  picture(P(a1,b1), P(a2,b2), "n1 [unit1] x n2 unit2");
1150  begin(); // end of preamble, start of body
1151  end();   // end of body
1152}
1153\end{verbatim}
1154\ePiX\ commands are of four general types: drawing, attribute setting,
1155definitions (of data and functions), and operations on existing
1156objects. Except as noted below, drawing and attribute commands must
1157appear in the body, between \code{begin()}~and \code{end()}. Function
1158definitions must come in the preamble, before \code{main()}. Data
1159definitions may appear in the preamble or body.
1160
1161
1162\subsection*{Output Format}
1163\index{Output format}
1164
1165The \code{end()} command writes the output file to \code{stdout},
1166using \code{eepic} macros by default. The shell scripts redirect
1167\code{stdout} to an appropriate disk file.
1168
1169The attribute-setting command \code{pst\_format()} causes the output
1170file to be written using \code{PSTricks} macros when \code{end} is
1171called. Similarly, \code{tikz\_format()} causes the file to be written
1172using \code{tikz} macros, and \code{eepic\_format()} causes the file
1173to be written using \code{eepic} macros. These commands may appear
1174anywhere in the figure body. There is no reason for a file to contain
1175more than one such command.
1176
1177The output format may be selected on the command line, overriding any
1178explicit request in the input file. Supplying \code{epix},
1179\code{elaps}, or \code{flix} with one of the options \code{--pst},
1180\code{--tikz}, or \code{--eepic} is tantamount to issuing a
1181\code{pst\_format()} (etc.)\ command just before the end of the
1182file. These options are listed in decreasing precedence. If more than
1183one is given, the ``strongest'' applies, regardless of the command
1184line order.
1185
1186A figure may be written directly to a specified disk file, in a format
1187unaffected by the command line flags above. The command
1188\begin{verbatim}
1189  print_eepic("file.tex");
1190\end{verbatim}
1191writes the figure to the named file using \code{eepic}
1192macros. Analogous commands exist for the formats \code{pst}~and
1193\code{tikz}. These commands perform an immediate action. Consequently,
1194the command's location in the input file is significant, and multiple
1195commands may appear in a single file, so long as distinct file name
1196arguments are provided. Applications include writing the same figure
1197in multiple formats, or creating successive ``snapshots'' of a lengthy
1198computation.
1199
1200
1201\section{Picture Size and Aspect Ratio}
1202
1203\index{Picture!size}%
1204\index{Picture!offset}%
1205\index{Aspect ratio}%
1206The \code{picture} command specifies a figure's logical and true
1207sizes. In the ``minimal file'' snippet above, the \emph{canvas} is the
1208Cartesian rectangle \teximath{[a_1,a_2]\times[b_1,b_2]} whose corners
1209are given. Either pair of opposite corners is acceptable, but
1210confusion is less likely when the SW~and NE corners are given, in this
1211order.
1212
1213\index{Length}%
1214The true (printed) width and height are read from \code{picture}'s
1215third argument, a ``size \code{string}'' such as \verb+"4cm x 1in"+,
1216containing a number and optional \LaTeX\ length unit, an~\code{x},
1217another number, and a mandatory length unit. Spaces may be used for
1218legibility.  The mandatory length unit becomes the \LaTeX\
1219\code{unitlength}.  The argument \verb+"4cm x 1in"+ creates a picture
12204~cm wide and 1~in high, but internally converts 4~cm to inches.
1221Recognized length units are \code{pt} (points, the default), \code{cm}
1222(centimeters), \code{in} (inches), \code{mm} (millimeters), \code{pc}
1223(picas), and \code{bp} (big points).
1224(\code{1in = 2.54cm = 72bp = 72.27pt}, \code{1pc = 12pt}.)
1225
1226The logical and true sizes may be defined separately with the commands
1227\findex{bounding\_box}
1228\findex{picture}
1229\findex{unitlength}
1230\begin{verbatim}
1231  bounding_box(P(a1,b1), P(a2,b2));
1232  picture(n1, n2);
1233  unitlength(len); // len a length string, not a double
1234\end{verbatim}
1235One way or another, the logical and true dimensions \emph{must} have
1236positive values when the \code{begin()} command is issued.
1237
1238\LaTeX\ treats the contents of a picture environment as a single box,
1239aligned by default on its lower left corner. An \code{offset} command
1240accepts two \code{double} arguments or a size \code{string} and shifts
1241the page location accordingly. The command
1242\code{offset("0.25 x -0.5cm")} shifts the picture right
1243\teximath{0.25}~cm and down \teximath{0.5}~cm.  If the
1244\code{unitlength} is 1~cm, the command \code{offset(0.25, -0.5)} has
1245the same effect.
1246
1247A non-zero \code{offset} causes a picture's contents to appear in a
1248location where \LaTeX\ does not expect them. This can be useful in a
1249\LaTeX\ document, but should be avoided when compiling a stand-alone
1250image, since \code{dvips} may crop according to rules of its own.
1251
1252
1253\index{Picture!aspect ratio}
1254\index{Picture!bounding box}
1255The canvas's corners are \code{(xmin(),ymin())} and
1256\code{(xmax(),ymax())}, while its width and height are
1257\code{xsize()}~and \code{ysize()}. The canvas is a virtual, advisory
1258data structure; its dimensions are not directly related to the
1259figure's printed size, and picture elements may lie outside the
1260canvas. Affine scaling maps the canvas to the page when the output
1261file is written.
1262\begin{center}
1263\input{scaling.eepic}
1264\end{center}
1265\label{page-scaling}
1266The figure's aspect ratio is controlled by sizing the canvas.  The
1267aspect ratio is ``true'' if the canvas and page rectangles are
1268geometrically similar, e.g., if both boxes are 1.5~times as wide as
1269they are tall.
1270
1271
1272\section{Color}
1273\label{section-color}
1274
1275\index{Color|(}
1276\ePiX\ provides a \code{Color} data type. Four models are implemented:
1277\code{RGB}, \code{CMY}, \code{CMYK}, and \code{Gray}.  A \code{Color}
1278holds primary color ``channels'', each carrying an intensity between
12790~(no color) and~1 (full saturation).  ``No color'' means black in
1280\code{RGB} and \code{Gray}, white in \code{CMY(K)}.  \code{RGB},
1281\code{CMY}, and~\code{CMYK} colors are written to the output file as
1282commands in the corresponding model. \code{Gray} shades are written
1283in~\code{RGB}.
1284
1285Operations on red-green-blue colors are described below. Functionally,
1286colors are converted to~\code{RGB}, operated upon, then converted back
1287to the original model. Conversions are as described in Uwe Kern's
1288\filename{xcolor} manual~\cite{xcolor}.
1289
1290
1291\subsection{Constructors}
1292
1293Each color model has a ``constructor'' creating a color of specified
1294densities. The \code{RGB}~and \code{CMY} models have named ``primary''
1295constructors; the density argument is optional and defaults to~1.
1296\findex{RGB}
1297\findex{Red}
1298\findex{Green}
1299\findex{Blue}
1300\findex{White}
1301\findex{Black}
1302\index{Color!primitive}
1303\begin{verbatim}
1304  // red-green-blue colors
1305  RGB(double r=0, double g=0, double b=0);
1306  Red(d=1);   Green(d=1);   Blue(d=1);
1307  White(d=1);   Black(d=1);
1308\end{verbatim}
1309\findex{CMY}
1310\findex{Cyan}
1311\findex{Magenta}
1312\findex{Yellow}
1313\findex{CMY\_White}
1314\findex{CMY\_Black}
1315\findex{CMYK}
1316\findex{Gray}
1317\begin{verbatim}
1318  // cyan-magenta-yellow colors
1319  CMY(double c=0, double m=0, double y=0);
1320  Cyan(d=1);   Magenta(d=1);   Yellow(d=1);
1321  CMY_White(d=1);   CMY_Black(d=1);
1322
1323  // gray
1324  Gray(double d=0); // equivalent to RGB(d, d, d)
1325\end{verbatim}
1326Each \code{CMY} constructor has a corresponding \code{CMYK} function,
1327e.g.\ \code{CyanK()}~or \code{CMYK\_White()}.
1328
1329\index{Color!density|(}%
1330Though color densities lie between 0~and 1, \ePiX's primary color
1331constructors take arguments mod~4, viewed as elements
1332of~\teximath{[-2,2]}. Consider \code{Red(d)}, ``red with
1333density~\teximath{d}''. For integer values of~\teximath{d}, the
1334constructor has the following meanings: \code{Red(0)}~is black,
1335\code{Red(1)}~is red, \code{Red(2)}=\code{Red(-2)}~is white, and
1336\code{Red(-1)}~is anti-red, or cyan. For non-integer~\teximath{d}, the
1337constructor interpolates between the bracketing integer values,
1338Figure~\ref{fig-densities}. Other primary constructors work
1339analogously.
1340
1341\begin{figure}[hbt]
1342  \begin{center}
1343    \input{color_density.eepic}
1344  \end{center}
1345  \caption{The red primary constructor.}
1346\label{fig-densities}
1347\end{figure}
1348
1349Let \teximath{\delta:[-2,2]\to[0,1]} be the piecewise-linear function
1350that converts real numbers to primary color densities,
1351\teximath{\clip:\mathbf{R}\to[0,1]} the clipping function.  The
1352non-primary constructor \code{RGB(r, g, b)} computes the density of
1353the red channel as
1354\teximath{\clip\bigl(\delta(r)+\delta(-g)+\delta(-b)\bigr)}; the green
1355and blue channel densities are computed similarly. Every color can be
1356created with arguments between 0~and 1, but the constructor accepts
1357arbitrary real arguments and returns colors varying ``continuously and
1358periodically''.
1359\index{Color!density|)}%
1360
1361\index{Color!transparency}
1362Colors possess an ``alpha-channel'' for transparency. Except as
1363supported by the output format, this feature is a stub.
1364
1365
1366\subsection{Color Operations}
1367
1368\index{Color!blencing}%
1369Colors can be scaled, inverted, blended, superposed, and filtered. In
1370the code below, \code{tint}~is a \code{Color}. The effect of each
1371operation is described in the \code{rgb} model; the visual result is
1372the same in all models.
1373\findex{Color.invert}
1374\findex{Color.blend}
1375\findex{Color.superpose}
1376\findex{Color.alpha}
1377\findex{Color.filter}
1378\begin{verbatim}
1379  tint *= double c; // multiply channels by c, rebuild
1380  tint.invert();    // (r, g, b) -> (1-r, 1-g, 1-b)
1381  tint.blend(Color col, double t);  // (1-t)*tint + t*col
1382  tint.superpose(col); // add channels, then clip to [0,1]
1383  tint.alpha(double d); // set alpha channel to clip(d)
1384
1385  tint.filter(col); // return min density in each channel
1386\end{verbatim}
1387Except for \code{filter}, these operators modify their object.
1388\code{filter} simulates the effect of viewing \code{col}
1389through a transparent sheet of \code{tint}, and returns a new
1390\code{Color} object having the same model as \code{tint} without
1391modifying \code{tint} itself.
1392
1393
1394\section{Scene Attributes}
1395
1396Objects in a scene sit in 3-dimensional space. A \emph{camera}
1397maps objects to the \emph{active screen}. The active \code{screen}
1398may, in turn crop its contents. Each drawing command creates an
1399object, ``photographs'' it, and adds the image to the active
1400\code{screen}. This section describes the \code{Camera} and
1401\code{screen} classes and a few associated concepts.
1402
1403
1404\subsection{Angular Mode}
1405\index{Angle!units}
1406
1407By default, angles are measured in \code{radian}s. Two other angular
1408modes are available: \code{degrees}~and \code{revolutions}. The
1409angular mode is set with a named command, \code{radians()},
1410\code{degrees()}, or \code{revolutions()}. The current angular mode
1411affects all trigonometric functions and operations.
1412
1413
1414\subsection{The Camera}
1415\index{Camera|(emph}
1416\index{Screen|(}
1417
1418Three-dimensional scenes are drawn on flat paper by applying a
1419mathematical transformation. By default, \ePiX\ uses \emph{point
1420projection}, the technique used by art students when they trace on a
1421window with grease pencil, Figure~\ref{fig-camera}.
1422
1423\begin{figure}[hbt]
1424  \begin{center}
1425    \input{camera.eepic}
1426  \end{center}
1427  \vspace*{-0.25in}
1428  \caption{Point projection.}
1429  \label{fig-camera}
1430\end{figure}
1431
1432\index{Camera!viewpoint}
1433\index{Viewpoint}
1434\ePiX\ depicts a Cartesian world by projecting mathematically to a
1435screen plane, then affinely scaling to a printed page. The camera,
1436which maps the world to the screen, consists of a \emph{body} (data
1437that determines the position and orientation of the camera), a
1438\emph{lens} (the actual mapping to the screen plane), and a
1439\emph{filter} (a color through which the scene is viewed).
1440
1441
1442\subsubsection*{Body}
1443
1444The camera's spatial orientation is described by a triple of mutually
1445perpendicular unit vectors.  In memory of happy days at the beach,
1446these vectors are called \emph{sea}, \emph{sky}, and~\emph{eye}. The
1447screen plane is parallel to the sea-sky plane; the sea vector points
1448horizontally to the right, sky points vertically upward. The eye is
1449their cross product, which points directly at the viewer.
1450
1451The sea-sky-eye basis is located at the \emph{viewpoint}, the camera's
1452spatial location. The \emph{target}, the origin of the screen plane,
1453lies on the line through the viewpoint in the direction opposite the
1454eye vector.  The distance from the viewpoint to the target is the
1455\emph{range}.  The \emph{camera sphere} is centered at the viewpoint
1456and passes through the target.  The orientation, viewpoint, target,
1457and range completely (and redundantly) determine the camera's
1458geometric situation in the world.
1459
1460
1461\subsubsection*{The Lens}
1462\index{Camera!lens}
1463
1464A \emph{lens} maps the world to the screen.  \ePiX\ comes with four
1465lenses: \emph{shadow} (the default), \emph{orthogonal},
1466\emph{fisheye}, and \emph{bubble}. Each lens simulates the appearance
1467of world objects as seen by an observer at the viewpoint. The shadow
1468lens is point projection from the viewpoint to the screen plane. The
1469orthogonal lens projects from infinite distance.  Each of the other
1470lenses performs radial projection to the camera sphere, then maps the
1471sphere to the screen plane; the fisheye lens does orthogonal
1472projection (so the entire image lies inside the disk centered at the
1473target whose radius is the range) while the bubble lens does
1474stereographic projection from the target's antipode.
1475\index{Screen|)}
1476
1477
1478\index{Camera!manipulation|(}
1479An input file normally uses a single camera, so a global object named
1480\code{camera} is defined automatically. At the start of a figure, the
1481\code{camera} looks down on the \teximath{(x_1,x_2)}-plane from a
1482distant point on the \teximath{x_3}-axis. The resulting view,
1483essentially projection along the axis, is suitable for 2-dimensional
1484figures.
1485
1486The \code{camera} is manipulated similarly to a real camera:
1487\findex{Camera.at}
1488\findex{Camera.look\_at}
1489\findex{Camera.range}
1490\findex{Camera.focus}
1491\findex{Camera.tilt}
1492\findex{Camera.pan}
1493\findex{Camera.roll}
1494\findex{Camera.clip\_range}
1495\begin{verbatim}
1496  camera.at(P posn);          // set viewpoint to posn
1497  camera.look_at(P targ);     // set target to targ
1498  camera.range(double dist);  // fix target, move viewpoint
1499  camera.focus(double dist);  // fix viewpoint, move target
1500  camera.tilt(double angle);  // rotate about the sea axis
1501  camera.pan(double angle);   // rotate about the sky axis
1502  camera.roll(double angle);  // rotate about the eye axis
1503  camera.clip_range(dist);    // cull scenery closer than dist
1504\end{verbatim}
1505Explicitly setting the viewpoint or target makes the sky vector
1506parallel to the projection of the \teximath{x_3}~axis when possible;
1507otherwise the \teximath{x_2}-axis is used. Setting the range or focus
1508moves the \code{camera} parallel along the eye line. Each command
1509re-sizes the image; note that increasing the focus \emph{enlarges} the
1510image. The three rotation operations fix the viewpoint, but only roll
1511fixes the target.
1512
1513
1514\subsubsection*{Filtering and Color Separation}
1515\index{Color!separation}
1516\index{Camera!color separation}
1517
1518The \code{camera} has a \emph{filter} through which all scene
1519\code{Color}s pass. For uniformity, the filter should only be set at
1520the start of the file body, before any visible elements have been
1521placed in the scene.  The filter has two primary uses---model
1522conversion and color separation---but can also be used for special
1523effects.
1524
1525There is a \code{Neutral} color, for which filtering has no effect at
1526all. The \code{camera}'s default filter is \code{Neutral}. In
1527addition, each color model has a \emph{neutral} representative,
1528\code{RGB\_Neutral}, etc. Passing \code{Color}s through a neutral
1529filter preserves their appearance but converts them to the neutral
1530\code{Color}'s model.
1531
1532Filtering can be used to ``split'' a \code{Color} into primary
1533constituents. For \code{RGB} channels, the primaries themselves are
1534suitable filters. For \code{CMYK} channels, there are special
1535\emph{process} filters, named \verb+C_Process+, etc.
1536\begin{verbatim}
1537  camera.filter(CMY_Neutral());  // convert all colors to CMY
1538  camera.filter(Gray_Neutral()); // black and white photography
1539  camera.filter(Green());        // the green channel
1540  camera.filter(M_Process());    // the magenta channel
1541  camera.filter(Red(1.4));       // la vie en rose?
1542\end{verbatim}
1543\index{Camera!manipulation|)}
1544\index{Camera|)}
1545
1546
1547\subsection{Clipping}
1548
1549\index{Clipping|(}%
1550Two operations handle elements lying far from the target.
1551\emph{Cropping} culls elements based on their screen location, and is
1552described later. \emph{Clipping} removes objects whose spatial
1553location lies outside the ``clip region''.
1554
1555Initially, the clip region is a very large box centered at the
1556origin. Commands are provided to resize this box, keeping the faces
1557parallel to coordinate planes.
1558\findex{clip\_box}
1559\findex{clip\_to}
1560\begin{verbatim}
1561  clip_box(P pt1, P pt2); // opposite corners
1562  clip_box(P pt);         // opposite corners pt and -pt
1563  clip_to (P pt);         //                  pt and P(0,0,0)
1564  clip_box();             // very large box
1565\end{verbatim}
1566Additional ``clippers'' may be added manually. Individual clipping
1567planes are specified by a point and inward-pointing normal vector.
1568Parallel planes cutting a ``slice'' or ``slab'' are described by a
1569location, direction, and a distance. The location lies halfway between
1570the clipping planes, and the planes' normals point toward the location.
1571\findex{clip\_face}
1572\findex{clip\_slice}
1573\findex{clip\_restore}
1574\begin{verbatim}
1575  clip_face(P loc, P perp); // perp points inward
1576  clip_slice(loc, perp);    // very close parallel planes
1577  clip_slice(loc, perp, dist); // planes separated by dist
1578  clip_restore();  // remove manually-added clip planes
1579\end{verbatim}
1580Like \code{clip\_restore}, the \code{clip\_box} and \code{clip\_to}
1581commands remove all user-specified half spaces.
1582\index{Clipping|)}
1583
1584
1585\subsection{Screens and Page Layout}
1586\index{Screen|(}
1587\index{Screen!active}
1588\index{Layout}
1589
1590By default, drawing occurs in the Cartesian coordinate system of the
1591\code{canvas}. However, insets and subfigures are most naturally
1592composed in ``local'' coordinates, then placed into their final
1593location as a unit, a process called \emph{layout}. \ePiX\ implements
1594layout with the \code{screen} class.
1595
1596
1597\subsubsection*{Screens}
1598\index{Bounding box}
1599
1600A \code{screen} is a Cartesian plane containing a distinguished
1601coordinate rectangle, its \emph{bounding box}. The \code{canvas} of a
1602figure is a \code{screen}, as is the internal representation of the
1603printed page.  At any point of a file body, some \code{screen} is
1604\emph{active}, or ``open for drawing''. A new \code{screen} is created
1605from a pair of opposite corners, but is not used until explicitly
1606activated.
1607\findex{activate}
1608\findex{deactivate}
1609\begin{verbatim}
1610  screen subfig(P(a1,b1), P(a2,b2)); // [a1, a2] x [b1, b2]
1611  activate(subfig);   // open subfig for drawing
1612  // commands to draw in subfig
1613  deactivate(subfig); // re-activate the previous screen
1614\end{verbatim}
1615
1616The \code{canvas} is automatically drawn at the \code{end} of the
1617input file. The contents of other \code{screen}s must be incorporated
1618into the \code{canvas} explicitly with an \code{import}~or
1619\code{inset} command. \code{import} affinely scales the bounding box
1620of the ``child'' \code{screen} to the \code{canvas}. \code{inset}
1621specifies corners in the ``parent'' where the child is
1622placed.
1623\findex{import}
1624\findex{inset}
1625\begin{verbatim}
1626  import();           // active screen to canvas
1627  import(subfig);     // subfig to canvas
1628  inset(P sw, P ne);  // active screen to specified rectangle
1629  inset(subfig, sw, ne); // subfig to specified rectangle
1630  inset(subfig);      // inset to subfig's corners
1631\end{verbatim}
1632
1633
1634\subsubsection*{Extracting}
1635
1636The portion of a \code{screen} enclosed by a specified rectangle can
1637be \emph{extracted}. Each of the commands
1638\findex{extract}
1639\findex{canvas}
1640\begin{verbatim}
1641  subfig.extract(P sw, P ne);
1642  canvas().extract(P sw, P ne);
1643\end{verbatim}
1644returns the \code{screen} having stated corners and containing part of
1645\code{subfig} or the \code{canvas}, respectively. Elliptical and
1646diamond-shaped portions of a \code{screen} may be extracted.  The
1647contents occupy the ellipse or diamond inscribed in the given
1648rectangle.
1649\findex{extract\_diamond}
1650\findex{extract\_ellipse}
1651\begin{verbatim}
1652  subfig.extract_ellipse(sw, ne);
1653  canvas().extract_diamond(sw, ne);
1654\end{verbatim}
1655The \code{screen} returned by \code{extract} (or its variants) may be
1656used just like a manually-constructed \code{screen}, for example to
1657construct a magnified inset.
1658
1659
1660\subsubsection*{True-Size Drawing}
1661\label{truesize}
1662
1663On occasion, it is necessary to draw at known page size, independently
1664of the unit length. For 2-dimensional drawing in the
1665\teximath{(x_1,x_2)}-plane with the \code{camera} in its default
1666location, the coordinates (horizontal, vertical, or both) of a
1667\code{screen} may be interpreted as true~pt offsets relative to a
1668specified point rather than as Cartesian coordinates.
1669\findex{inlay}
1670\findex{inlay\_horizontal}
1671\findex{inlay\_vertical}
1672\begin{verbatim}
1673  inlay(subfig, P loc);
1674  inlay_horizontal(subfig, loc);
1675  inlay_vertical(subfig, loc);
1676\end{verbatim}
1677Each command maps the origin of \code{subfig} to the specified
1678location in the active \code{screen}. The first performs affine
1679scaling so that one Cartesian unit in \code{subfig} maps to one
1680true~pt on the page.  The second and third commands perform this
1681scaling only in the named direction.
1682
1683\findex{pt\_to\_screen}
1684The \code{inlay} functions are suitable only for 2-dimensional
1685effects. For 3-dimensional true-size drawing, the function
1686\code{pt\_to\_screen} converts a true length of 1~pt into Cartesian
1687coordinates in the active \code{screen}. For example, the command
1688\code{line(P(0,0), P(pt\_to\_screen(12),0))} draws a line segment
168912~pt long with its left endpoint at the Cartesian origin. True size
1690drawing is unusual in an input file, but has definite uses in library
1691code; \ePiX's right angle marker is a typical application.
1692
1693Either type of true-size drawing works as described when drawing in
1694the \code{canvas}, and \emph{only} when drawing in a \code{screen}
1695imported to the \code{canvas} at ``true Cartesian'' size (one
1696\code{screen} unit maps to one Cartesian unit in the \code{canvas}).
1697In other situations, the true size coordinate(s) will be scaled by
1698additional affine transformation(s).
1699
1700
1701\subsubsection*{Cropping and Decorations}
1702
1703\index{Cropping}
1704A \code{screen} has a \emph{crop mask}: rectangular (default),
1705elliptical, or diamond-shaped. If cropping is switched on in the
1706active \code{screen}, added elements are cropped to the crop mask.
1707For example, cropping by the default crop mask in the \code{canvas}
1708ensures the figure lies inside the printed region allocated by
1709\LaTeX.
1710
1711The \code{crop} commands below affect the active \code{screen}
1712only. Cropping is not a ``global'' attribute, but must be set or unset
1713explicitly for each \code{screen}. By default, cropping is switched
1714off.
1715\findex{crop}
1716\findex{crop\_ellipse}
1717\findex{crop\_diamond}
1718\findex{set\_crop}
1719\begin{verbatim}
1720  set_crop();      // activate cropping
1721  set_crop(false); // deactivate cropping
1722  crop_diamond();  // <>-shaped mask, set crop state
1723  crop_ellipse();  // etc...
1724  crop();          // crop active screen's contents
1725\end{verbatim}
1726Normally the crop mask is inscribed in the \code{screen}'s bounding
1727box. The commands \code{crop\_diamond} and \code{crop\_ellipse} also
1728accept a pair of \code{P}~arguments, which are treated as corners of
1729the crop box.
1730
1731The active \code{screen} may be decorated with a \code{border}
1732(outline of specified color and line width) and \code{backing} (solid
1733fill color). The crop mask determines the shape of the \code{border}
1734and \code{backing}.
1735\findex{border}
1736\findex{backing}
1737\begin{verbatim}
1738  border(color, len);
1739  backing(color);
1740\end{verbatim}
1741Identically-named member functions can be applied to an arbitrary
1742\code{screen} whether or not it is active:
1743\begin{verbatim}
1744  scr.crop_rectangle().backing(Blue(1.8));
1745  canvas().crop();
1746\end{verbatim}
1747
1748
1749\subsubsection*{Affine Maps}
1750\index{Affine map}
1751
1752A \emph{plane affine map} has the form \teximath{T(x) = Ax+b} for some
1753invertible \teximath{2\times2} matrix~\teximath{A} and a constant
1754vector~\teximath{b}. \ePiX's \code{affine} class allows affine maps to
1755be built and applied to \code{screen}s' contents.
1756
1757An affine map is uniquely determined by the images of three
1758non-collinear points.  The constructor returns the affine map sending
1759the points \teximath{(1,0)}, \teximath{(0,1)}, and~\teximath{(0,0)} to
1760\code{pt1}, \code{pt2}, and~\code{pt0}, respectively.
1761\findex{affine}
1762\begin{verbatim}
1763  affine af(P pt1, P pt2, P pt0=P(0,0));
1764\end{verbatim}
1765To emphasize, the arguments are locations, not displacements, and the
1766image of the origin comes last.  There is also a \code{void}
1767constructor (taking no arguments) which returns the identity map.
1768
1769To facilitate construction of affine maps, an existing \code{affine}
1770may be post-composed with a variety of ``elementary'' affine
1771transformations. In the commands below, \code{th} is an angle (in
1772current units), \code{sc} is a non-zero \code{double}, and \code{ctr}
1773is a point fixed by the composing transformation. In each command,
1774\code{ctr} defaults to \teximath{(0,0)}.
1775\findex{shift}
1776\findex{rotate}
1777\findex{reflect}
1778\findex{h\_scale}
1779\findex{v\_scale}
1780\findex{scale}
1781\findex{h\_shear}
1782\findex{v\_shear}
1783\findex{postcomp}
1784\begin{verbatim}
1785  affine af; // the identity map
1786  af.shift(P arg);    // translate by arg
1787  af.rotate(th, [ctr]);  // counterclockwise rotation about ctr
1788  af.reflect(th, [ctr]); // reflect across line through ctr
1789
1790  af.h_scale(sc, [ctr]); // horizontal scaling
1791  af.v_scale(sc, [ctr]); // vertical scaling
1792  af.scale(sc, [ctr]);   // dilatation
1793
1794  af.h_shear(sc, [ctr]); // shear preserving horizontals
1795  af.v_shear(sc, [ctr]); // shear preserving verticals
1796
1797  af.invert();           // the inverse
1798  af.postcomp(affine f); // post-compose with f
1799  af(f);                 // pre-compose, af not modified
1800\end{verbatim}
1801A non-invertible \code{affine} can be created \emph{only} by shearing
1802or scaling with an extremely large or extremely small argument, or by
1803supplying three collinear points to the constructor.  Calling
1804\code{invert} on a non-invertible map merely issues a warning and
1805performs no action.
1806
1807An \code{affine} may be applied to a \code{screen}'s current contents.
1808The \code{screen} class has eight member functions (\code{shift}
1809through \code{shear}) with syntax identical to the affine map
1810functions. In addition, an arbitrary \code{affine} may be applied to a
1811\code{screen}:
1812\findex{apply}
1813\begin{verbatim}
1814  scr.shift(arg); // shift scr's contents by arg; etc.
1815  scr.apply(f);   // apply f to scr's contents
1816\end{verbatim}
1817To apply a composition of several maps to a \code{screen}, it's best
1818to build an \code{affine} map by composition, then \code{apply} the
1819map. Composing \code{affine}s is cheap; \code{apply}ing an
1820\code{affine} is costly in proportion to the number of elements in the
1821\code{screen}.
1822
1823Applying an \code{affine} to a \code{screen} has no effect on the
1824bounding box, \code{border}, or \code{backing}, and may move elements
1825outside the bounding box even if cropping is active. To ensure a
1826\code{screen}'s contents lie inside the bounding box, \code{crop} the
1827\code{screen} \emph{after} \code{apply}ing the \code{affine}(s).
1828
1829The sample file \filename{inverse.xp} uses \code{affine} maps to
1830depict branches of inverse functions in one variable,
1831\filename{symmetry.xp} depicts the permutation group~\teximath{S_3}
1832by its action on a regular hexagon.
1833\index{Screen|)}
1834
1835
1836\section{Drawing Attributes}
1837
1838\ePiX\ maintains drawing states for filled regions, paths, and text
1839objects.
1840
1841
1842\subsection{Filled Regions}
1843
1844\index{Filling}
1845\index{Path|(}
1846\index{Path!filled}
1847Filling is either on or off. When filling is active, closed paths are
1848filled with the current \emph{fill color}.
1849\findex{fill}
1850\findex{nofill}
1851\begin{verbatim}
1852  fill();   // turn filling on
1853  fill(color); // turn filling on, specify color
1854  nofill(); // turn filling off, same as fill(false);
1855\end{verbatim}
1856
1857
1858\subsection{Paths}
1859
1860\index{Drawing style|(}
1861\index{Line style|(}
1862Paths and borders of filled regions are drawn with two \emph{pen}s,
1863each described by color and line width. The \emph{line pen} draws
1864all path-like objects. The \emph{base pen} does nothing unless it is
1865wider then the line pen, in which case it draws an ``underlayer'' or
1866``border'' on the line pen.
1867\findex{pen}
1868\begin{verbatim}
1869  pen(len);          // set line pen width
1870  pen(color);        // set line color, keep width
1871  pen(color, len);   // set color and width
1872\end{verbatim}
1873As usual, \code{len} may be either a length string or a \code{double},
1874interpreted as a width in~\code{pt}.  There are \code{base} functions
1875with the same signatures and analogous meanings for the base pen.
1876
1877The line width can be set with named declarations; the optional
1878argument sets the line color:
1879\findex{plain}
1880\findex{bold}
1881\findex{bbold}
1882\begin{verbatim}
1883  plain([color]); // 0.4pt
1884  bold([color]);  // 0.8pt
1885  bbold([color]); // 1.6pt
1886\end{verbatim}
1887
1888
1889\subsubsection*{Path Style}
1890
1891\index{Path!style}
1892By default, path-like objects are drawn with solid lines. Dashed,
1893dotted, and free-form path style patterns are also available. (The
1894\code{base} underlayer is always solid.) The page length of a pattern
1895defaults to 12~pt, but can be set.
1896\findex{line\_style}
1897\findex{dash\_size}
1898\begin{verbatim}
1899  line_style(string);
1900  dash_size(len=12);
1901\end{verbatim}
1902The path style is set with a WYSIWYG string of dashes, spaces, and
1903periods, representing a pattern of dashes, gaps, and dots. In the
1904sample styles below, the repeating units have the same page size,
190512~pt.
1906\begin{center}
1907  \input{pathstyle.eepic}
1908\end{center}
1909For brevity and uniformity, named commands are provided.
1910\findex{solid}
1911\findex{dashed}
1912\findex{dotted}
1913\begin{verbatim}
1914  solid(); "-"     dashed(); "-  -"    dotted(); " . "
1915\end{verbatim}
1916A sequence of \teximath{n}~dashes, spaces, and dots corresponds to a
1917dash/dot pattern in an interval divided into \teximath{n}~subintervals
1918of equal length. If the \teximath{i}th character is a dash or space,
1919the \teximath{i}th~subinterval is drawn solid or empty,
1920respectively. If the \teximath{i}th~character is a period, a dot is
1921placed at the midpoint of the \teximath{i}th~subinterval.
1922
1923This pattern is applied to a path-like object as follows. The page
1924length of each edge is divided by the current \code{dash\_size} and
1925the ceiling (next largest integer) taken. This many copies of the
1926current path style are scaled onto the edge. The first and last
1927characters are adjacent in repeated units.
1928
1929There are three inequivalent ways to adjust the dash length/dot
1930spacing in a non-line path: Change the \code{dash\_length}, create a
1931path with a different number of points, or use a longer, repetitive
1932pattern.  For best results, the style string should not be longer than
1933about a dozen characters.
1934
1935If you need several dashed/dotted line styles in multiple figures,
1936it's best to define a custom header instead of hard-coding line
1937styles. See Section~\ref{section-extensions} for guidance.
1938\index{Drawing style|)}
1939\index{Line style|)}
1940\index{Path|)}
1941
1942
1943\subsection{Text Objects}
1944
1945\index{Label|(emph}
1946\index{Label!alignment}
1947\index{Marker}
1948Two types of textual element may appear in a file: \emph{labels} (text
1949boxes) and \emph{markers} (\LaTeX\ symbols). A marker occupies a box
1950of zero size, and is placed at a specified Cartesian location. A label
1951has typographical size, and is usually offset from its Cartesian
1952location. For placement, an \emph{alignment point} is attached to each
1953label, and Cartesian coordinates position the alignment point.
1954
1955\subsubsection*{Labels}
1956
1957A label is printed as a \LaTeX\ box.  By default, the alignment point
1958is its reference point, the intersection of the left edge and the
1959baseline, which is used by \LaTeX\ to position the box on the
1960page:\input{basepoint.eepic}
1961
1962\index{Label!alignment|(}
1963The alignment point may be \emph{offset} manually by a specified
1964number of \code{pt}. Additionally, a label's location with respect to
1965the alignment point can be chosen with an optional \LaTeX-style
1966alignment option. This scheme allows labels to be placed easily where
1967they will not overlap other parts of the figure, and ensures labels
1968stay properly positioned when the size or aspect ratio of a figure
1969changes.
1970\findex{label}
1971\begin{verbatim}
1972  label(P posn, P offset, string msg, [align]);
1973  label(posn, msg);
1974\end{verbatim}
1975The first two components of the \code{offset} argument are numbers
1976of~\code{pt} to shift the alignment point right and up.  The optional
1977\code{align} argument may be one---or an appropriate pair---of
1978\code{t}, \code{b}, \code{r}, or~\code{l} (top, bottom, right, left),
1979or~\code{c} (center). These alignment options specify the position of
1980the label \emph{relative to the Cartesian location}~\code{posn},
1981namely they work \emph{opposite} to the way they work in \LaTeX.
1982\begin{center}
1983  \input{alignment_lr.eepic}\qquad
1984  \input{alignment.eepic}
1985\end{center}
1986\index{Label!alignment|)}
1987
1988The \code{msg} argument is usually a snippet of \LaTeX\ code enclosed
1989in double quotes. \CXX~treats ``\verb+\+'' as an escape character, so
1990a double backslash is needed in the source to get a single backslash
1991in the output. For example,
1992\begin{verbatim}
1993  label(P(0,0), P(2,-1), "$\\rho = \\sin\\theta$", br);
1994\end{verbatim}
1995positions an alignment point \code{2pt}~right and \code{1pt}~below the
1996(Cartesian) origin, and typesets the equation
1997\teximath{\rho=\sin\theta} below and to the right.
1998
1999\index{Label!rotated}
2000\index{Angle!units}
2001Labels can be rotated; the (counterclockwise) angle is set in current
2002angle units with the command \code{label\_angle(theta)}. For example,
2003a rotation angle of~90 degrees prints labels along a vertical
2004axis. Though label rotation has legitimate uses, it can make labels
2005more difficult to read, defeating their purpose. Do not use rotated
2006labels merely because they are available. As a practical matter, if an
2007output file contains rotated labels, the enclosing document must use
2008the \code{rotating} package. \code{elaps} automatically loads this
2009package.
2010
2011\index{Affine map!action on labels}
2012An \code{affine} behaves moderately intelligently when acting on a
2013marker or label. The mapping is applied to the label's location, and
2014the ``linear part'' is used to adjust the offset and label angle. No
2015attempt is made to treat alignment. For best results, if a
2016\code{screen} will have an \code{affine} applied to it, label
2017positions should be fine-tuned only with offsets, not alignment
2018arguments.  In all situations, the font itself is unchanged; no
2019attempt is made to print sheared, scaled, or reflected text. The
2020sample file \filename{inverse.xp} illustrates the effect of affine
2021maps on labels.
2022
2023
2024\subsubsection*{Fonts and Type Size}
2025
2026\index{Fonts}
2027\index{Label!fonts in}
2028By default, the font in an \ePiX\ figure is that of the enclosing
2029document. The font size and face are changed with
2030``declaration-style'' commands such as
2031\findex{font\_size}
2032\findex{font\_face}
2033\begin{verbatim}
2034font_size("Large");
2035font_face("sc");
2036\end{verbatim}
2037The argument of \verb+font_size+ is a valid \LaTeX\ size. If no
2038argument is given, \code{normalsize} is understood. \verb+font_face+
2039accepts a two-letter string, appended to the string ``\code{text}'' to
2040give a \LaTeX\ font declaration command (``\code{textsc}'' above).
2041Finer-grained control is accomplished by placing \LaTeX\ commands
2042into the label text.
2043
2044
2045\subsubsection*{Label Attributes and Masked Labels}
2046
2047\index{Label!masked}%
2048Each label command has a corresponding ``mask'' version
2049(\code{masklabel}) that draws an opaque rectangle under the label
2050text. The mask size exceeds the label's size by an amount of
2051\emph{padding}, and the mask is itself surrounded by a rectangular
2052\emph{border}, of specified color and width.
2053\findex{label\_color}
2054\findex{label\_mask}
2055\findex{label\_pad}
2056\findex{label\_border}
2057\findex{no\_label\_border}
2058\begin{verbatim}
2059  label_color(color);         // set label text color
2060  label_mask(color=White());  // set mask color
2061  label_pad(string len);
2062
2063  label_border(color, [len]); // set color (and line width)
2064  label_border(len);          // set line width only
2065  no_label_border();          // turn off label borders
2066\end{verbatim}
2067
2068
2069\subsubsection*{Markers}
2070
2071\index{Marker!types of|(}
2072\ePiX\ markers are obtained with \verb+marker(P pt, <MARKER TYPE>);+
2073(Table~\ref{table-marker}.)
2074Several ``dot-like'' marker types are available by name: \input{dots.eepic}
2075\findex{spot}
2076\findex{dot}
2077\findex{ddot}
2078\findex{box}
2079\findex{bbox}
2080\findex{ring}
2081\findex{circ}
2082\begin{verbatim}
2083  spot(P pt);  dot(P pt);   ddot(P pt);
2084     ---       box(P pt);   bbox(P pt);
2085  ring(P pt);  circ(P pt);     ---
2086\end{verbatim}
2087A \code{circ} is filled with the current \code{mask\_color}, and a
2088\code{ring} is ``hollow''.  Each dot-like marker can also be called
2089with label syntax, generating a labeled marker with one command.
2090\begin{verbatim}
2091  dot(P posn, offset=P(0,0), msg="", align=none); // etc.
2092\end{verbatim}
2093
2094\findex{dot\_size}
2095By default, \code{spot}~and \code{ring} are 4~pt in diameter;
2096\code{dot}, \code{box}, and~\code{circ} are 3~pt in diameter;
2097\code{ddot}~and \code{bbox} are 2~pt in diameter. At arbitrary
2098diameter, a \code{spot} is \teximath{4/3}~the diameter of a~\code{dot}
2099and a~\code{ddot} is \teximath{2/3}~the diameter.  The command
2100\code{dot\_size(diam=3)} sets the diameter of a \code{dot}, and hence
2101the size of all dot-like markers.
2102
2103\begin{table}[tb]
2104  \begin{center}
2105    \input{marker.eepic}
2106  \end{center}
2107  \caption{\ePiX's \code{marker} types.}
2108  \label{table-marker}
2109\end{table}
2110\index{Marker!types of|)}
2111
2112
2113\subsubsection*{Reminders}
2114
2115\index{Label!offset}%
2116When constructing and placing a label,
2117\begin{itemize}
2118\item Offsets are specified in \code{pt} (true length), not Cartesian
2119  units: A label's location relative to its alignment point should not
2120  depend on the logical or printed size of the figure.
2121
2122\item The label text is enclosed in double quotes (the single
2123  character~\code{"}), and contains the \LaTeX\ code to generate the
2124  label. Backslashes are doubled.
2125  \index{Label!backslash in}
2126  \index{Label!double quotes}
2127\end{itemize}
2128\index{Label|)}
2129
2130
2131\subsection{Color Declarations}
2132
2133\index{Color!declaration}
2134Old-style color declarations set the fill color, line color, and
2135text color.
2136\findex{rgb}
2137\findex{cmyk}
2138\begin{verbatim}
2139  rgb(r, g, b);      cmyk(c, m, y, k);
2140  rgb(P);            cmyk(P);  // for function-controlled colors
2141  red(d);  // similarly for other primaries
2142\end{verbatim}
2143\index{Color|)}
2144
2145
2146\section{Creating and Drawing Objects}
2147
2148Scene elements include geometric objects, coordinate grids, axis
2149labels, and function plots. A few commands create an object (a point,
2150line segment, circle, sphere, or plane) that can be used in subsequent
2151computations, but most drawing commands automatically create, draw,
2152and discard objects.
2153
2154
2155\subsection{Geometric Data Structures}
2156
2157\subsubsection*{Points}
2158\index{Point|(}
2159The simplest object in the world, and by far the most common named
2160data structure, is~\code{P}, an ordered triple of real numbers
2161(double-precision floats). The function~\code{P(x1,x2,x3)} creates the
2162point~\teximath{(x_1,x_2,x_3)}. If only two arguments are provided,
2163\teximath{x_3=0} by default. This convention allows \ePiX\ to treat
21642-~and 3-dimensional figures uniformly. The standard basis is
2165available: \code{E\_1=P(1,0,0)}, etc.
2166
2167Depending on context, a \code{P} may represent either a
2168\emph{location} (point) or a \emph{displacement} (vector). Almost all
2169\ePiX\ functions treat a~\code{P} as a point. However, algebraic
2170operators and commands that plot vector fields treat \code{P}
2171arguments as displacements.
2172
2173Polar, cylindrical, and spherical coordinate \code{P}~constructors are
2174sensitive to the current angular mode.
2175\index{Angle!mode}
2176\findex{P}
2177\findex{polar}
2178\findex{cis}
2179\findex{cyl}
2180\findex{sph}
2181\begin{verbatim}
2182  P pt=polar(r,t);   // (r*Cos(t), r*Sin(t), 0)
2183  P pt=cis(t);       // (Cos(t), Sin(t), 0) = polar(1, t)
2184  P pt=cyl(r,t,z);   // (r*Cos(t), r*Sin(t), z)
2185  P pt=sph(r,t,phi); // polar(r,t)*Cos(phi) + (0,0,r*Sin(phi))
2186\end{verbatim}
2187
2188Algebraic operations---addition/subtraction, scalar multiplication;
2189scalar, cross, and componentwise products; orthogonalization---can
2190be performed on~\code{P}s.  In compound expressions, the binary
2191operators below should be enclosed in parentheses, and scalars must be
2192collected at left, \code{P}s at right.
2193\findex{P.x1}
2194\findex{P.x2}
2195\findex{P.x3}
2196\findex{J}
2197\begin{verbatim}
2198  double u=pt.x1();   // first coordinate of pt, etc.
2199  P(a,b,c)|P(x,y,z);  // scalar product, ax+by+cz
2200  P(a,b,c)&P(x,y,z);  // componentwise product (ax, by, cz)
2201  P(a,b,c)*P(x,y,z);  // cross product (bz-cy, cx-az, ay-bx)
2202  J(p);               // quarter turn about the x3-axis
2203  p%q;                // orthogonalization, p (mod q)
2204\end{verbatim}
2205Explicitly, \code{p\%q}~is the unique vector \code{p+k*q}
2206perpendicular to~\code{q}.
2207
2208\code{P}~operations express mathematical relationships, and therefore
2209imbue a figure with logical structure, making the input file easier to
2210read, modify, and maintain. Commonly, a file preamble will define a
2211few named points with hard-coded coordinates, then define additional
2212points of interest using \code{P}~operators.
2213\index{Point|)}
2214
2215\subsubsection*{Complex Numbers}
2216
2217\index{Complex number|(}
2218\index{Function!complex}
2219The \code{Complex} class represents a complex number, specified by its
2220real and imaginary parts. Arithmetic operators (addition, subtraction,
2221multiplication, division) are provided, as well as exponential,
2222logarithmic, circular, and hyperbolic functions (sensitive to angle
2223units), the latter with \code{C} appended to their names. A complex
2224number implicitly converts to a point with third coordinate zero. The
2225sample file \filename{cubic\_cutaway.xp} illustrates usage, including
2226how to define and plot functions and color-shade Riemann surfaces.
2227\findex{Complex.re}
2228\findex{Complex.im}
2229\findex{Complex.conj}
2230\findex{Arg}
2231\findex{norm}
2232\findex{expC}
2233\findex{logC}
2234\findex{sqrtC}
2235\findex{rootC}
2236\findex{powC}
2237\findex{SinC}
2238\findex{CosC}
2239\findex{TanC}
2240\findex{CotC}
2241\findex{SecC}
2242\findex{CscC}
2243\findex{SinhC}
2244\findex{CoshC}
2245\findex{TanhC}
2246\findex{CothC}
2247\findex{SechC}
2248\findex{CschC}
2249\begin{verbatim}
2250  Complex u, z(4,3);  // u = 0, z = 4 + 3i
2251  double len(norm(z));// len = 5
2252  double th(Arg(z));  // th = atan2(3, 4);
2253  P pt(z);            // pt = (4, 3, 0)
2254  Complex w(expC(z)); // w = e^{4 + 3i}
2255  u = LogC(z,k=0);    // u = Log(z) + 2*pi*ki
2256  u = sqrtC(z,k=0);   // sqrt(z)*expC(pi*ki)
2257  u = rootC(z,n,k=0); // (z^{1/n})*expC(2*pi*ki/n)
2258  u = powC(z,n);      // z^n
2259\end{verbatim}
2260\index{Complex number|)}
2261
2262
2263\subsubsection*{Other Geometric Classes}
2264
2265In addition to~\code{P}, objects of type \code{Circle}, \code{Plane},
2266\code{Segment}, and \code{Sphere} can be used for Euclidean geometry
2267constructions. Simple affine operations are supplied for each type, as
2268is a \code{draw()} function, which represents the object as a path in
2269the screen.
2270\findex{shift}
2271\findex{move\_to}
2272\findex{scale}
2273\findex{draw}
2274\begin{verbatim}
2275  obj.shift(P arg);    // translate by arg
2276  obj.move_to(P arg);  // move center to arg
2277  obj.scale(double c); // scale about center by c
2278  obj.draw();
2279\end{verbatim}
2280A \code{Segment}'s ``center'' is its midpoint. A \code{Plane} has no
2281center; \code{move\_to} translates the \code{Plane} to pass through
2282\code{arg}, and \code{scale} has no effect.
2283
2284\index{Circle}
2285A \code{Circle} data structure consists of a center, radius, and a
2286perpendicular unit vector. Three constructors are provided:
2287\findex{Circle}
2288\begin{verbatim}
2289  Circle(center=P(0,0,0), double rad=1, normal=E_3);
2290  Circle(P center, P point);
2291  Circle(P p1, P p2, P p3);
2292\end{verbatim}
2293The second constructor creates the \code{Circle} parallel to the
2294\teximath{(x_1,x_2)}~plane, with given center, and radius equal to the distance
2295between the arguments. (A warning is printed if the second argument
2296does not lie on the circle, namely, if the arguments do not lie in a
2297plane parallel to the \teximath{(x_1,x_2)}~plane.) The third returns the
2298\code{Circle} passing through the given points; the points must not be
2299collinear.
2300
2301The data defining a \code{Circle} are recovered with member functions
2302named \code{center()}, \code{radius()}, and \code{perp()}.
2303
2304\index{Plane}
2305\findex{Plane}
2306A \code{Plane} is specified by a point and normal vector, or by three
2307non-collinear points. The \code{draw()} function clips the plane and
2308draws the resulting polygon. Unless the clip box has been set
2309manually, the clipped polygon's vertices will have large coordinates.
2310
2311\index{Segment}
2312\findex{Segment}
2313A \code{Segment} is constructed from its endpoints. The member
2314function \code{midpoint()} returns the center.
2315
2316\index{Sphere}
2317\findex{Sphere}
2318A \code{Sphere} is specified by a point and a radius---by default the
2319origin and unity, or by the center and a point on the sphere. Member
2320functions \code{center()}~and \code{radius()} return the defining
2321data.  Capabilities specific to geography and spherical geometry are
2322described below, pp.~\pageref{non-eucl}ff.
2323
2324The \code{draw()} function of a \code{Sphere} draws the horizon
2325visible from the current viewpoint. While this horizon is a circle in
2326object space, its image in the screen is generally an ellipse.
2327Antipodal points are not generally mapped to points symmetrically
2328placed with respect to the center of this ellipse. These effects are
2329most pronounced when the viewpoint is close to the \code{Sphere} and
2330the center is not close to the \code{target}.
2331
2332
2333\subsubsection*{Intersection}
2334
2335\index{Intersection}
2336
2337To facilitate geometric computation, \ePiX's \code{Circle},
2338\code{Plane}, \code{Segment}, and \code{Sphere} classes can be
2339intersected with the \code{*}~operator.
2340\texicomment
2341Table~\ref{table-intersect}
2342lists the return types for each pair of arguments.  Intersection is
2343commutative, so only the top half of the table is shown. For purposes
2344of intersection, a \code{Segment} is extended into a line.
2345The sample file \filename{pascal.xp} gives typical applications of
2346objects and intersection.
2347\findex{intersection}
2348\begin{table}[hbt]
2349\begin{center}
2350  \begin{tabular}{c|cccc}
2351    \code{*} &
2352    \code{Segment} & \code{Circle} & \code{Plane} & \code{Sphere} \\
2353    \hline
2354    \code{Segment} & \code{P} & \code{Segment} & \code{P} & \code{Segment} \\
2355    \code{Circle}  &    & \code{Segment} & \code{Segment} & \code{Segment} \\
2356    \code{Plane}   &    &    &   \code{Segment} & \code{Circle} \\
2357    \code{Sphere}  &    &    &    & \code{Circle}
2358  \end{tabular}
2359  \caption{Object intersection types.}
2360  \label{table-intersect}
2361\end{center}
2362\end{table}
2363\texicommentend
2364
2365A \code{Circle} has a center, radius, and unit normal; a \code{Plane}
2366has a distinguished point and unit normal; a \code{Segment} has two
2367endpoints; a \code{Sphere} has a center and radius. An object is
2368\emph{malformed} if these conditions are not met.  The constructors
2369return well-formed objects with two exceptions: \code{Circle} and
2370\code{Plane} create malformed objects if called with three collinear
2371points.  The operator~\code{*} returns a malformed object if either
2372argument is malformed, or if the operands are disjoint, tangent, or
2373coincident.  Malformedness is benign: Calling \code{draw()} on a
2374malformed object does nothing.
2375
2376
2377\subsubsection*{Orthonormal Frames}
2378
2379A \code{frame} comprises three mutually perpendicular unit
2380vectors. The constructor takes three vectors. The \code{frame}'s third
2381vector~\teximath{e_3} is positively proportional to~\code{v3}, the
2382second vector~\teximath{e_2} is positively proportional to
2383\code{v2\%v3}, and the first is the cross product,
2384\teximath{e_1=e_2\times e_3}. Thus, a \code{frame} is right-handed,
2385and does not depend on~\code{v1}.
2386
2387The elements of a \code{frame} are named \code{sea}, \code{sky}, and
2388\code{eye}, just as for the \code{camera}. A \code{frame} can be
2389rotated through an arbitrary angle about any of its elements.
2390\findex{frame}
2391\begin{verbatim}
2392  frame();        // the standard basis {E_1, E_2, E_3}
2393  frame fr(v1, v2, v3); // orthonormalize {v1, v2, v3}
2394  fr.sea();       // the first element of fr, etc.
2395  fr.rot1(theta); // rotate fr through theta about sea, etc.
2396\end{verbatim}
2397
2398
2399\subsection{Path-Like Elements}
2400
2401Basic path-like objects are drawn with named commands. Arguments of
2402polygon commands are endpoints/vertices. Except for \code{line}~and
2403\code{Line}, the following are subject to filling.
2404\findex{line}
2405\findex{Line}
2406\findex{triangle}
2407\findex{rect}
2408\findex{quad}
2409\findex{circle}
2410\begin{verbatim}
2411  line(P p1, P p2, [double expand]);
2412  Line(p1, p2);  // draw line through p1, p2 (crop required)
2413  triangle(P p1, P p2, P p3);
2414  rect(P p1, P p2);
2415  quad(P p1, P p2, P p3, P p4); // quadrilateral
2416  circle(ctr=P(0,0,0), rad=1, normal=E_3);
2417  circle(ctr, pt);
2418  circle(pt1, pt2, pt3);
2419\end{verbatim}
2420The optional \code{line} argument is an expansion parameter:
2421\code{line(p1,p2,t);} draws a segment centered at the midpoint of
2422\code{p1}~and \code{p2}, with length scaled
2423by~\teximath{2^{t/100}}. (Setting \teximath{t=100} doubles the length,
2424while \teximath{t=-100} halves the length.) The arguments of
2425\code{rect()} must lie in a plane parallel to a coordinate plane. The
2426arguments to \code{circle} commands are the same as for \code{Circle}
2427constructors.
2428
2429Quadratic and cubic splines are described by their control points.  A
2430list of~\code{P} is drawn as a ``natural'' spline (the \teximath{C^2}
2431piecewise cubic curve with vanishing second derivatives at the
2432endpoints); the number of points per cubic segment must be specified.
2433Circular and elliptical arcs are given by center, a basis, angular
2434range, and an optional number of intervals.
2435\findex{spline}
2436\findex{arc}
2437\findex{ellipse}
2438\begin{verbatim}
2439  spline(P p1, P p2, P p3, [int n]);       // quadratic
2440  spline(P p1, P p2, P p3, P p4, [int n]); // cubic
2441  spline(vector<P>, int n);                // natural spline
2442
2443  arc(P ctr, rad, t_min, t_max);  // parallel to (x1,x2)-plane
2444  ellipse(P ctr, P v1, P v2);     // in plane spanned by v1, v2
2445  ellipse(P ctr, P v1, P v2, t_min, t_max, [int n]);
2446\end{verbatim}
2447\texicomment
2448Mathematically, these commands draw parametric paths
2449\begin{align*}
2450  \text{Spline:}\quad&(1-t)^2 p_1 + 2(1-t)t p_2 + t^2 p_3,
2451    && t\in[0,1] \\
2452  \text{Spline:}\quad&(1-t)^3 p_1 + 3(1-t)^2t p_2 + 3(1-t)t^2 p_3 + t^3p_4,
2453    && t\in[0,1] \\
2454  \text{Arc:}\quad&\mathrm{ctr} + (\cos t)(\mathrm{rad},0,0)
2455                + (\sin t)(0,\mathrm{rad},0),
2456    && t\in[t_\mathrm{min}, t_\mathrm{max}] \\
2457  \text{Ellipse:}\quad&\mathrm{ctr} + (\cos t)v_1 + (\sin t)v_2,
2458    && t\in[t_\mathrm{min}, t_\mathrm{max}].
2459\end{align*}
2460\texicommentend
2461If parameter bounds are omitted in an \code{ellipse} command, the
2462entire ellipse is drawn.  When the angular range subtends one or more
2463full turns in an \code{arc}~or \code{ellipse} the curve is subject to
2464filling.
2465
2466Commands for planar (half-)ellipses remain from \ePiX's early days:
2467\findex{ellipse}
2468\findex{ellipse\_left}
2469\findex{ellipse\_right}
2470\findex{ellipse\_top}
2471\findex{ellipse\_bottom}
2472\begin{verbatim}
2473  ellipse(P ctr, P radius);
2474  ellipse_left(P ctr, P radius);
2475  ellipse_right(P ctr, P radius);
2476  ellipse_top(P ctr, P radius);
2477  ellipse_bottom(P ctr, P radius);
2478\end{verbatim}
2479If \code{radius} is \code{P(a,b)}, these commands draw all or half of
2480the ellipse with given center in the \teximath{(x_1,x_2)} plane, axes
2481parallel to the coordinate axes, and axis lengths \teximath{2a}~and
2482\teximath{2b}.
2483
2484Two commands are available to mark off right angles or a subtended
2485angle. Each accepts a spatial location and two non-zero directions,
2486and draws a scene element in the plane spanned by the vectors.
2487\findex{right\_angle}
2488\findex{arc\_measure}
2489\begin{verbatim}
2490  right_angle(P loc, P v1, P v2, scale=8);
2491  arc_measure(P loc, P v1, P v2, scale=8);
2492  arc_measure(P loc, P v1, P v2, offset, text, align, scale=8);
2493\end{verbatim}
2494The \code{right\_angle} command does not check its arguments for
2495perpendicularity. The \code{arc\_measure} commands mark the
2496\emph{small} angle subtended by the directions; the label form places
2497a label at the midpoint of the arc. The (optional) \code{scale}
2498argument is the true size in~\code{pt} of the marker.
2499
2500
2501\begin{comment}
2502\subsubsection*{Recursive Fractal Curves}
2503
2504\index{Path!fractal}
2505Consider a path made up of equal-length segments that can point at any
2506angle of the form~\teximath{2\pi k/n} radians, for \teximath{0\leq
2507k<n}, like spokes on a wheel. A path is specified by a finite sequence
2508of integers, taken modulo~\teximath{n}. For example, if
2509\teximath{n=6}, then the sequence \teximath{0, 1, -1, 0} corresponds
2510to the ASCII path \verb+_/\_+.  \ePiX's fractal approximation starts
2511with such a ``seed'' then recursively (up to a specified depth)
2512replaces each segment with a scaled and rotated copy of the seed,
2513Figure~\ref{fig-fractal}. The seed above generates the standard
2514von~Koch snowflake fractal. In code:
2515\findex{fractal}
2516\begin{verbatim}
2517  const int seed[] = {6, 4, 0, 1, -1, 0};
2518  fractal(P(a,b), P(c,d), depth, seed);
2519\end{verbatim}
2520The first entry of \code{seed[]} (here~6) is the number of
2521``spokes''~\teximath{n}, the second~(4) is the number of terms in the
2522seed, and the remaining entries are the seed proper. The final path
2523joins \teximath{(a,b)}~to \teximath{(c,d)}. The number of segments in
2524the final path grows exponentially in the depth, so depths larger than
25255~or 6 are likely to exceed the capabilities of \LaTeX\ and/or
2526PostScript.
2527\begin{figure}[hbt]
2528  \begin{center}
2529  \input{koch.eepic}
2530  \end{center}
2531  \caption{Successive iterations of \{\code{4,8,0,1,0,3,3,0,1,0}\}}
2532  \label{fig-fractal}
2533\end{figure}
2534\end{comment}
2535
2536
2537\subsubsection*{Arrows}
2538
2539\index{Arrow}
2540Line segments, splines, and arcs can be drawn with arrowheads at one
2541end.  In profile, an arrowhead's width is \code{3pt}, and its height
2542is 5.5~times the width.  The actual printed height depends on the
2543head's orientation with respect to the camera.  By default, an
2544arrowhead is a filled triangle. The shape and size are adjusted with
2545declarations:
2546\findex{arrow\_width}
2547\findex{arrow\_ratio}
2548\findex{arrow\_inset}
2549\begin{verbatim}
2550  arrow_width(w=3);   // width in pt
2551  arrow_ratio(r=5.5); // height-to-width
2552  arrow_inset(c=0);   // base indent as frac of ht
2553\end{verbatim}
2554\input{arrow.eepic} Inset\teximath{=0}\qquad
2555\input{arrow25.eepic} Inset\teximath{=0.25}\qquad
2556\input{arrow50.eepic} Inset\teximath{=0.5} \\
2557The \code{inset} must be between \teximath{-1}~and \teximath{1}. Each
2558\code{arrow} command accepts an optional \code{scale} argument, which
2559scales the arrowhead.
2560\findex{arrow}
2561\begin{verbatim}
2562  arrow(P tail, P tip, [scale]);
2563  arrow(P p1, P p2, P p3, [scale]);   // spline arrows
2564  arrow(P p1, P p2, P p3, P p4, [scale]);
2565  arrow(P ctr, P v1, P v2, t_min, t_max, [scale]); // ellipse
2566\end{verbatim}
2567A few ``special-purpose'' commands are supplied:
2568\findex{dart}
2569\findex{aarrow}
2570\findex{arc\_arrow}
2571\begin{verbatim}
2572  dart (P p1, P p2);  // same as arrow(p1, p2, 0.5);
2573  aarrow(P p1, P p2); // double-headed arrow <--->
2574  arc_arrow(ctr, rad, t_min, t_max, [scale]);
2575\end{verbatim}
2576If an \code{arc\_arrow} is too short, nothing is drawn.
2577
2578
2579\subsection{Coordinate Axes and Labels}
2580
2581\index{Label!axis|(}
2582\index{Axes!labeling}
2583\index{Axes|(}
2584\ePiX\ provides an \code{axis} class for coordinate axes. Labels are
2585generated automatically in a variety of styles: decimal, scientific
2586notation, fraction, and trigonometric fraction. Logarithmic axes and
2587labels are available. Axis and labeling commands from Version~1.0 have
2588been retained.
2589
2590
2591\subsubsection*{The \code{axis} Class}
2592
2593An \code{axis} consists of a line segment divided into a specified
2594number of equal-length subintervals by ``major'' (long) tick marks.
2595Each subinterval may be divided further by ``minor'' (short) tick
2596marks.  Minor ticks may be equally-spaced (``Cartesian'') or
2597logarithmically placed. Finally, a label is written at each major tick
2598mark with specified offset and alignment. Labels are generated
2599automatically from the endpoints, so the line should be parallel to a
2600coordinate axis. Label attributes (masking, borders, font size and
2601face, rotation angle) are determined by the current label style, not
2602by the \code{axis}.
2603
2604The command
2605\findex{axis}
2606\begin{verbatim}
2607  axis(P tail, P head, int n, P offset=P(0,0), [align = none]);
2608\end{verbatim}
2609creates an axis joining \code{tail} to \code{head}, divided into
2610\code{n}~segments of equal length, with a major tick mark and label at
2611each division point and endpoint. The \code{offset} and \code{align}
2612arguments have the same meaning as for ordinary labels.
2613
2614The number and length of minor ticks, and the alignment of ticks, are
2615controlled with member functions:
2616\findex{axis.subdivide}
2617\findex{axis.tick\_ratio}
2618\findex{axis.align}
2619\begin{verbatim}
2620  axis Ax(P(a,c), P(b,c), n);
2621  Ax.subdivide(n);  // put n-1 minor ticks in each axis segment
2622  Ax.tick_ratio(r); // minor length = r*major length
2623  Ax.align(AL=c);   // align all ticks; AL = t, b, l, r, or c
2624\end{verbatim}
2625By default, major ticks are \code{6pt}~long and twice the length of
2626minor ticks. The global declaration \code{tick\_size(len)} sets the
2627major length, subject to ``reasonable stylistic limits''. For visual
2628consistency, tick lengths should not be changed casually.
2629
2630\index{Axes!labeling}
2631Labels on an \code{axis} may be drawn in several styles, selected with
2632member functions:
2633\findex{axis.dec}
2634\findex{axis.frac}
2635\findex{axis.trig}
2636\findex{axis.sci}
2637\findex{axis.unmark}
2638\findex{axis.precision}
2639\findex{axis.align\_labels}
2640\begin{verbatim}
2641  Ax.dec();  // decimals (default)
2642  Ax.frac(); // fractions, e.g. 0.5 -> \frac{1}{2}
2643  Ax.trig(); // fractional multiples of \pi
2644  Ax.sci();  // scientific notation, k\times base^N
2645
2646  Ax.unmark(double); // remove label at selected location
2647  Ax.precision(p);   // set number of digits for decimal labels
2648  Ax.align_labels(AL); // re-align labels
2649\end{verbatim}
2650Arbitrary textual labels depending on one coordinate are obtained by
2651writing a \code{string}-valued function of~\code{double} and
2652``registering'' it:
2653\findex{axis.label\_rep}
2654\begin{verbatim}
2655  // f represents x as a string in given precision and base
2656  std::string f(double x, unsigned int prec, unsigned int base);
2657  Ax.label_rep(f);
2658\end{verbatim}
2659For example, textual tags can be printed instead of numeric labels.
2660
2661By default, an \code{axis} is Cartesian. The member function
2662\code{log(int b=10)} converts an \code{axis} to ``log mode'' with
2663specified base; this affects both tick marks and labeling. If \code{b}
2664is at least~3, minor tick marks appropriate for a logarithmic axis
2665base~\code{b} are drawn. Second, labels are written in decimal or
2666scientific notation appropriately for a logarithmic axis; that is,
2667``\teximath{k\times b^N}'' (or its decimal value) is written at
2668location \teximath{N+\log_b k}.
2669
2670Minor ticks of a log \code{axis} may be labeled individually; again,
2671this is controlled with member functions:
2672\findex{axis.tag}
2673\findex{axis.tag235}
2674\findex{axis.tags}
2675\findex{axis.untag}
2676\begin{verbatim}
2677  Ax.tag(d);   // labels at N+log_b(d)
2678  Ax.tag235(); // tag 2, 3, and 5 if b=10
2679  Ax.tags();   // tag 1, ..., b-1
2680  Ax.untag();  // remove all tags, including 1
2681  Ax.untag(double);  // remove one tag, e.g. Ax.untag(9);
2682\end{verbatim}
2683
2684For convenience, an \code{axis} object along an edge of the active
2685\code{screen} can be created with a named command:
2686\findex{top\_axis}
2687\findex{bottom\_axis}
2688\findex{left\_axis}
2689\findex{right\_axis}
2690\begin{verbatim}
2691  top_axis(n, offset, align);
2692  bottom_axis(n, offset, align);
2693  left_axis(n, offset, align);
2694  right_axis(n, offset, align);
2695\end{verbatim}
2696The ticks automatically point into the bounding box.
2697
2698The functions above create objects or set \code{axis} attributes, but
2699write no output. Tick marks and labels can be printed separately, or
2700at once:
2701\findex{axis.draw}
2702\findex{axis.draw\_ticks}
2703\findex{axis.draw\_labels}
2704\begin{verbatim}
2705  Ax.draw();        // axis, tick marks, and labels
2706  Ax.draw_ticks();  // axis and ticks only
2707  Ax.draw_labels();
2708\end{verbatim}
2709
2710
2711\subsubsection*{Other Axis-Drawing Commands}
2712
2713\index{Axes!logarithmic}
2714\ePiX\ formerly supplied commands for drawing simple axes and their
2715labels. These commands have been kept for compatibility.  Horizontal
2716axes are generated with
2717\findex{h\_axis}
2718\findex{h\_log\_axis}
2719\findex{v\_axis}
2720\findex{v\_log\_axis}
2721\begin{verbatim}
2722  h_axis(p1, p2, n, align=c);    // n subintervals (n+1 ticks)
2723  h_log_axis(p1, p2, n, align=c, base=10);
2724\end{verbatim}
2725For vertical axes, use \code{v\_axis}.  The style of tick mark is
2726appropriate for an axis of the given type.  Horizontal axis tick marks
2727may be aligned \code{t}~(above the axis) or~\code{b}
2728(below). Similarly, vertical axis ticks may be aligned \code{r}~or
2729\code{l}.
2730
2731The endpoint arguments of a coordinate axis may be omitted, in which
2732case they default to \teximath{p_1=(x_\mathrm{min},0)} and
2733\teximath{p_2=(x_\mathrm{max},0)} for a horizontal axis, or to
2734\teximath{p_1=(0,y_\mathrm{min})} and
2735\teximath{p_2=(0,y_\mathrm{max})} for a vertical axis. If the bounding
2736box has integer width and/or height, omitting the number of points
2737draws tick marks one unit apart.
2738
2739Labels for a horizontal Cartesian or logarithmic axis are generated
2740with the commands
2741\findex{h\_axis\_labels}
2742\findex{h\_axis\_masklabels}
2743\findex{h\_axis\_log\_labels}
2744\findex{h\_axis\_log\_masklabels}
2745\findex{v\_axis\_labels}
2746\findex{v\_axis\_masklabels}
2747\findex{v\_axis\_log\_labels}
2748\findex{v\_axis\_log\_masklabels}
2749\begin{verbatim}
2750  h_axis_labels(P p1, P p2, int n, P offset, [align]);
2751  h_axis_masklabels(p1, p2, n, offset, [align]);
2752  h_axis_log_labels(p1, p2, [n], offset, [align], base=10);
2753  h_axis_log_masklabels(p1, p2, [n], offset, [align], base=10);
2754\end{verbatim}
2755Labels for a vertical axis are generated with \code{v\_axis\_labels},
2756etc. The labels are automatically generated to match their horizontal
2757location.  The first puts \teximath{(n+1)}~evenly-spaced labels on the segment
2758joining \code{p1}~and \code{p2}. As with ordinary labels, the
2759\code{offset} is in~\code{pt}, and the optional \LaTeX-style alignment
2760option positions the labels using their corners.  The second command
2761draws masked labels according to the current label masking
2762attributes. The third writes labels in exponential notation, using the
2763Cartesian coordinate as exponent.
2764
2765As for coordinate axes, the initial and final points may be omitted in
2766an \code{axis\_[mask]labels} command, with the same defaults.  The
2767\code{offset} and number of labels must always be specified.
2768\index{Label!axis|)}
2769
2770
2771\subsubsection*{Broken Axes}
2772\index{Axes!broken}
2773
2774Broken axes are best drawn using page layout, especially if axis
2775labels are to be drawn. To accomplish the task, create a screen for
2776each piece of axis, using appropriate Cartesian coordinates for the
2777corners, then \code{inset} the screens so the axis pieces are nearly
2778end to end. A zig-zag glyph signifies the break:
2779\findex{axis\_break}
2780\begin{verbatim}
2781  axis_break(P, P, scale=12);
2782\end{verbatim}
2783The \code{P} arguments are the screen coordinates of the ends to be
2784joined; the optional third argument is the true height and width
2785in~\code{pt} of the glyph. The sample file \filename{coord\_tricks.xp}
2786uses layout and axis breaks.
2787
2788
2789\subsubsection*{Coordinate Grids}
2790
2791Cartesian grids fill a coordinate rectangle, and have a specified
2792number of lines in each direction. A polar grid has specified radius,
2793and numbers of rings and sectors.
2794\findex{grid}
2795\findex{polar\_grid}
2796\begin{verbatim}
2797  grid(n1, n2);         // fills the bounding box
2798  grid(p1, p2, n1, n2); // fills the box with corners p1, p2
2799  polar_grid(r, n1, n2);
2800\end{verbatim}
2801
2802Log and semi-log grids are drawn with analogous syntax:
2803\findex{log\_grid}
2804\findex{log1\_grid}
2805\findex{log2\_grid}
2806\begin{verbatim}
2807  log_grid (p1, p2, n1, n2, [base1], [base2]); // log-log
2808  log1_grid(p1, p2, n1, n2, [base]);           // log-lin
2809  log2_grid(p1, p2, n1, n2, [base]);           // lin-log
2810\end{verbatim}
2811The~\teximath{n_i} arguments dictate the number of squares, namely the number
2812of orders of magnitude spanned in the logarithmic direction(s).  The
2813(optional) base arguments default to~10, and control the number of
2814lines drawn per order of magnitude. As with Cartesian grids, the
2815corners are optional; if omitted, the grid fills the bounding box.
2816
2817\index{Graph paper}
2818Graph paper may be created by superimposing grids:
2819\texicomment
2820\begin{center}
2821  \begin{minipage}[b]{2.5in}
2822    \begin{footnotesize}
2823\texicommentend
2824\findex{pen}
2825\findex{grid}
2826\begin{verbatim}
2827  pen(0.25);
2828  grid(10*xsize(), 10*ysize());
2829  pen(0.5);
2830  grid(2*xsize(), 2*ysize());
2831  pen(1);
2832  grid(xsize(), ysize());
2833\end{verbatim}
2834\texicomment
2835    \end{footnotesize}
2836  \end{minipage}
2837  \qquad
2838  \input{graphpaper.eepic}
2839\end{center}
2840\index{Axes|)}
2841\texicommentend
2842
2843\subsection{The Path Class}
2844
2845\index{Path!class}
2846A \code{path} data structure is an ordered list of points that can be
2847cropped, clipped, mapped, concatenated, and drawn.  The first four
2848constructors mirror polygon-drawing commands above.  Function graphs
2849and parametric paths are built from a real- or \code{P}-valued
2850function~\code{f} of one variable.
2851\findex{path}
2852\begin{verbatim}
2853  path(p1, p2, expand=0);     // line (endpoints)
2854  path(p1, p2, p3, [n]);      // quadratic spline
2855  path(p1, p2, p3, p4, [n]);  // cubic spline
2856  path(p1, v1, v2, t_min, t_max, [n]); // ellipse
2857  path(f, t_min, t_max, [n]);
2858\end{verbatim}
2859
2860The member function \code{pt()} accepts a~\code{P} or three (or two)
2861doubles and appends the specified point to a \code{path}.  This
2862snippet creates a regular \teximath{n}-gon:
2863\begin{verbatim}
2864  path ngon; // declare new path
2865  for (int i=0; i<=n; ++i)
2866    ngon.pt(cis(i*full_turn()/n)); // works in all angle modes
2867\end{verbatim}
2868Compound paths may be built by concatenation.  If \code{path1}~and
2869\code{path2} share an endpoint, the commands
2870\begin{verbatim}
2871  path1 += path2;
2872  path1 -= path2;
2873\end{verbatim}
2874replace \code{path1} with the result of traversing \code{path1}
2875``forward'', then following \code{path2} in the forward or reverse
2876direction (respectively). For expected results, the first
2877(or last) point on~\code{path2} should be the last point
2878of~\code{path1}. The notation suggests 1-dimensional homology
2879chains. The sample file \filename{contour.xp} illustrates path
2880creation and manipulation.
2881
2882A \code{path} is a data structure, and must be drawn explicitly to
2883create visible output. By default a \code{path} is not a closed loop
2884(even if the first and last points are the same), and is not filled
2885when drawn. Member functions perform these tasks. Continuing the
2886\teximath{n}-gon snippet above,
2887\findex{path.close}
2888\findex{path.fill}
2889\findex{path.draw}
2890\begin{verbatim}
2891  ngon.close(); // mark path as closed
2892  ngon.fill();  // draw filled region if filling is active
2893  ngon.draw();  // print to the screen
2894\end{verbatim}
2895\code{path::close()} adds a closing edge if necessary. Once a
2896\code{path} is closed, no more points can be added. A closed path
2897clips and crops differently than an open \code{path} with the same
2898data. \code{path::fill()} has no effect on an unclosed \code{path}.
2899
2900
2901\subsection{Function Plotting}
2902
2903\index{Plotting|(}
2904The noun ``map'' refers to a \CXX\ function that accepts one or
2905more \code{double} arguments and returns a \code{double}~or
2906a~\code{P}. Mathematically, a map can be depicted in two ways: as a
2907graph (which retains information about the domain), or as a
2908parametrized curve or surface (which discards domain
2909information). \ePiX\ assumes that \code{double}-valued maps are
2910graphed and \code{P}-valued maps are drawn parametrically. Either sort
2911of depiction is called a ``plot''.  \ePiX\ plots are either ``wire
2912mesh'', produced by a \code{plot} command, or ``shaded'', produced by
2913a \code{surface} command.
2914
2915
2916\subsubsection*{Basic Plotting}
2917
2918For the moment, ``function'' means ``function of one variable''
2919(precisely, a \code{double}-valued function of a \code{double}
2920variable). A function graph depends on the domain and the number of
2921points to use. Each of the commands
2922\findex{plot}
2923\findex{polarplot}
2924\findex{shadeplot}
2925\begin{verbatim}
2926  plot(f, t_min, t_max, n);
2927  polarplot(f, t_min, t_max, n);
2928  shadeplot(f, t_min, t_max, n);
2929\end{verbatim}
2930graphs the function~\code{f} on the interval \code{[t\_min, t\_max]}
2931by dividing the interval into \code{n}~subintervals of equal length.
2932The first gives a Cartesian plot, the second a polar plot with bounds
2933in current angular units, the third shades the region between the
2934graph and the horizontal axis. If two functions are given to
2935\code{shadeplot}, the region between their graphs is shaded.
2936
2937
2938\subsubsection*{Domains and Wiremesh Plots}
2939
2940\index{Domain|(}
2941An \ePiX\ \code{domain} is a coordinate box of dimension one, two, or
2942three, specified by a pair of opposite corners and two \emph{meshes}
2943(``coarse'' and ``fine'', respectively) which specify the amount of
2944data to be plotted. Plotting is explained in detail below.
2945\findex{domain}
2946\begin{verbatim}
2947  // [a1,a2] x [b1,b2]: n1 x n2 rectangles, m1 x m2 intervals
2948  domain R2(P(a1,b1), P(a2,b2), mesh(n1,n2), [mesh(m1,m2)]);
2949
2950  // [a1,a2] x [b1,b2] x [c1,c2] divided analogously
2951  domain R3(P(a1,b1,c1), P(a2,b2,c2),
2952            mesh(n1,n2,n3), [mesh(m1,m2,m3)]);
2953\end{verbatim}
2954If unspecified, the fine mesh is the same as the coarse mesh. For
2955expected behavior, the coarse mesh should ``divide'' the fine mesh, in
2956that \teximath{m_i}~should be a (usually small) integer multiple
2957of~\teximath{n_i} for each~\teximath{i}.
2958
2959A \code{domain} may be \emph{resized} in any coordinate for which the
2960thickness is positive, and can be \emph{sliced} by setting one
2961variable to a constant. The result of slicing is a \code{domain} whose
2962dimension is one smaller than the original.  Finally,
2963``\code{slices}'' operators return the list of \code{domain}s obtained
2964by setting one variable to evenly-spaced constants.  By default, the
2965number of slices is specified by the coarse mesh. An optional argument
2966specifies the number of slices. This argument need not be related to
2967the coarse mesh.
2968\findex{domain.resize}
2969\findex{domain.slice}
2970\findex{domain.slices}
2971\begin{verbatim}
2972  R2.resize2(a,b); // [a1,b1] x [a,b]
2973  R2.slice1(t);    // set x1 = t
2974  R3.slices3([n]); // (n+1) domains with x3 = const
2975\end{verbatim}
2976\begin{center}
2977  \input{slices.eepic}
2978\end{center}
2979\smallskip
2980When possible, resizing preserves grid square sizes. Generally,
2981though, integer truncation occurs: If \code{R=domain(P(0,0), P(1,1),
2982mesh(10,6))}, then \code{R.resize1(0,0.25)} is the rectangle
2983\teximath{[0,0.25]\times[0,1]} subdivided into \teximath{2\times6}
2984subrectangles, since \teximath{10\div4=2} in integer arithmetic. For
2985expected behavior, choose mesh sizes to avoid integer truncation.
2986
2987
2988The arguments of a \code{plot} command are a map, followed by either a
2989domain or its logical equivalent.
2990\findex{plot}
2991\begin{verbatim}
2992  double f(double t) { return t*t; }
2993  P F(double u, double v) { return P(u, v, exp(u)*Sin(v)); }
2994  P G(double u, double v, double w) { return P(v*w, u*w, u*v); }
2995
2996  plot(f, a, b, n);       // f:[a,b] -> R, using n intervals
2997  plot(F, R2);            // graph of exp(u)*Sin(v)
2998  plot(G, R3.slice2(0.5); // G: R^3 -> R^3 restricted to y=0.5
2999\end{verbatim}
3000By (compiler-enforced) convention, \code{plot} commands involving a
3001\code{P}-valued map accept a \code{domain} argument, as in the second
3002and third commands above. To plot a \code{double}-valued function, by
3003contrast, supply the logical equivalent of a \code{domain}, usually
3004the endpoints and the number of intervals, as in the first \code{plot}
3005command above.
3006
3007Resizing and slicing allow a map~\code{F} to be plotted selectively
3008over parts of its domain. This can be used to emphasize parts of the
3009image, layer scene elements, patch surfaces together, and so forth.
3010Resize and slice(s) commands may be used directly in a \code{plot}
3011command:
3012\findex{plot}
3013\begin{verbatim}
3014  plot(F, R2.resize1(0,0.5));
3015  plot(F, R2.slices1());
3016\end{verbatim}
3017
3018
3019\subsubsection*{Meshes and Plotting}
3020
3021The \code{P}~arguments of a \code{domain} are a pair of opposite
3022corners. The first \code{mesh} argument, the \emph{coarse} mesh,
3023specifies the number of subdivisions in each coordinate direction.
3024The second \code{mesh}, the \emph{fine} mesh, determines the number of
3025points used in each direction when plotting.
3026
3027\begin{comment}
3028Suppose the \code{domain}~\code{R2} is, as above, the rectangle
3029\teximath{[0,3]\times[-1,2]}. The argument \code{mesh(12,6)} divides the
3030rectangle a \teximath{12\times6}~array of subrectangles known as the
3031\emph{coarse mesh}. A \code{P}-valued map~\code{F} of two variables is
3032plotted over the edges of the coarse mesh. Rather than drawing
3033quadrilaterals, however, \ePiX\ draws the image curves at the
3034resolution specified by the argument \code{mesh(60,60)}, the
3035\emph{fine mesh}. In this example, the curves in each direction are
3036drawn using 60~line segments.
3037\end{comment}
3038
3039Separating the roles of coarse and fine meshes allows a plot to
3040conform closely to a surface without using a fine grid of curves.
3041Both parts of Figure~\ref{fig-plot} are drawn with a
3042\teximath{6\times20} coarse mesh. In the first picture, the fine mesh
3043is also \teximath{6\times20}, while in the second, the fine mesh is
3044\teximath{12\times60}.
3045
3046\begin{figure}[hbt]
3047  \begin{center}
3048    \input{plot_a.eepic}\hspace*{0.5in}
3049    \input{plot_b.eepic}
3050    \caption{Coarse and fine meshes.}
3051    \label{fig-plot}
3052  \end{center}
3053\end{figure}
3054
3055The coarse mesh is significant only for domains of dimension at
3056least~2. The coarse mesh's size determines the number of curves or
3057surfaces plotted \emph{perpendicularly} to a coordinate direction,
3058while the fine mesh's size determines the number of segments used
3059\emph{along} that direction.  For predictable results, the fine mesh
3060should be a small multiple of the coarse mesh.
3061
3062Plotting works analogously for 3-dimensional \code{domain}s and maps
3063depending on three variables: The ``one-dimensional skeleton'' of the
3064\code{domain}'s image is drawn.  A \code{P}-valued map of
3065three variables can be plotted over a 1-~or 2-dimensional
3066\code{domain}. (The effect may be unexpected unless the domain arises
3067by slicing, however.) A map depending on one or two variables cannot
3068be plotted over a 3-dimensional \code{domain}.
3069\index{Domain|)}
3070
3071
3072\subsubsection*{Shaded Surfaces}
3073
3074\index{Plotting!surface|(}
3075
3076\ePiX's shaded surface plotting implements a degree of hidden surface
3077removal. The algorithm breaks a surface into mesh fragments, sorts
3078them in decreasing (approximate) distance to the camera, and prints
3079them.  If filling is active, a mesh fragment is shaded according to
3080the angle between the normal vector and the direction to the camera,
3081simulating constant ambient lighting; otherwise, the current fill
3082color is used.  This technique works fairly well for surfaces without
3083intersection, and even acceptably handles intersecting surfaces for
3084which mesh elements intersect only along boundaries.
3085
3086The syntax of a \code{surface} command is identical to a \code{plot}
3087command when only a single surface is drawn. For example,
3088\findex{surface}
3089\begin{verbatim}
3090  surface(F, R, cull=0);
3091\end{verbatim}
3092plots the \code{P}-valued function~\code{F} over the domain~\code{R},
3093the shaded equivalent of the corresponding \code{plot} command. The
3094optional \code{cull} argument removes elements that point toward
3095(\code{cull=-1}) or away from (\code{cull=1}) the camera. Naturally,
3096orientation of mesh elements depends on the parametrization~\code{F},
3097not merely on the surface. Culling reduces the output file size, but
3098is useful mostly for closed, convex surfaces.
3099
3100There are special commands for surfaces of rotation; each accepts a
3101final \code{cull} argument.
3102\findex{surface\_rev}
3103\begin{verbatim}
3104  surface_rev(f, t_min, t_max, n_lats, n_longs);
3105  surface_rev(f, g, t_min, t_max, n_lats, n_longs=24);
3106  surface_rev(f, g, R, frame coords);
3107\end{verbatim}
3108The first revolves the graph of~\teximath{f} about the
3109\teximath{x}-axis, the second uses the parametric curve
3110\teximath{t\mapsto\bigl(f(t),g(t)\bigr)} as profile. In each case, the
3111parameter interval \verb+[t_min,t_max]+ is divided into \verb+n_lats+
3112equal-length subintervals, \verb+n_longs+ copies of the profile curve
3113are drawn, and the complete surface (one full turn) is drawn.
3114
3115The third form uses a \code{domain} to control the range of
3116longitudes, and draws a surface of rotation in the Cartesian
3117coordinate system defined by the orthonormal basis \code{coords}, by
3118default the standard basis. The arguments \code{f}~and \code{g} define
3119a parametric curve in the plane spanned by the first two elements
3120of~\code{coords}, and the first element is the axis of rotation.
3121
3122As in wire mesh plotting, the fine mesh is used to draw the boundaries
3123of surface patches; this tends to make surfaces look smoother for
3124modest-sized coarse meshes. If the coarse mesh is too coarse, however,
3125two visually undesirable effects can occur. First, adjacent regions of
3126the surface may be shaded very differently, since shading is constant
3127over patches defined by the coarse mesh. Second, a patch nearly
3128tangent to a line of sight may be drawn badly if the patch bends back
3129on itself, since the boundary of the \emph{patch} is drawn, not the
3130visible edge of the mathematical surface. See
3131\filename{samples/artifacts.xp}.
3132
3133
3134\subsubsection*{Multiple Domains and/or Maps}
3135
3136A scene containing two or more shaded surfaces cannot generally be
3137built up one surface at a time. Instead, multiple surfaces must be
3138assembled into a single data structure before they can be drawn.
3139Multiple surfaces are built from one or more maps and one or more
31402-dimensional \code{domain}s. In the code snippets below, \code{F}~and
3141\code{G} are \code{P}-valued functions of 3~variables, and~\code{R} is
3142a 3-dimensional \code{domain}.
3143
3144To plot the images of several \code{domain}s under a \emph{single
3145map}, assemble the \code{domain}s into a list if necessary, then issue
3146a \code{surface} command:
3147\findex{surface}
3148\findex{domain\_list}
3149\findex{domain\_list.add}
3150\begin{verbatim}
3151  surface(F, R.slices3(), cull=0);
3152
3153  domain_list DL(R.slice1(0));  // build domain list
3154  DL.add(R.slice2(0.5));        // add a domain, etc.
3155  surface(G, DL, cull=0);       // draw
3156\end{verbatim}
3157For multiple maps, \ePiX\ provides the \code{scenery}
3158class. Conceptually, \code{scenery} is an agglomeration of shaded
3159surfaces, built one surface at a time from maps and 2-dimensional
3160\code{domain}s. The \code{add} function accepts two arguments---a map,
3161and either a \code{domain} or a list of \code{domain}s---and
3162contributes its data to the \code{scenery} rather than plotting
3163immediately. Completed \code{scenery} is drawn manually.
3164\findex{scenery}
3165\findex{scenery.add}
3166\findex{scenery.draw}
3167\begin{verbatim}
3168  scenery S(F, R.slice3(0.25)); // S contains one surface
3169  S.add(F, R.slice2(0));        // S contains two surfaces
3170  S.add(G, R.slices1(3));       // S contains six surfaces
3171  S.draw(cull=0);
3172\end{verbatim}
3173Complete examples are included in the \filename{samples} directory:
3174\filename{spherical.xp}~and \filename{minkowski.xp}.
3175
3176In principle, a scene may contain arbitrarily many surfaces. However,
3177figures that contain many objects tend to tax \LaTeX's internal
3178stacks. Frequent color changes exacerbate the problem.  Even if you
3179use \filename{hugelatex} (or increase \LaTeX's memory), a figure
3180containing more than a few thousand mesh elements is unlikely to
3181compile. At moderate resolution, a surface can easily contain
31821000~patches. Each shell script has a command-line option to invoke
3183\filename{hugelatex}; your mileage may vary.
3184
3185
3186\subsubsection*{User-Specified Color Shading}
3187
3188\index{Color!surface plotting}
3189By default, a \code{surface} or \code{scenery} is colored according to
3190the current fill color. For finer control, each \code{surface},
3191\code{surface\_rev}, and \code{scenery} command accepts an optional
3192position-dependent \code{color} specification.
3193\findex{surface}
3194\findex{surface\_rev}
3195\findex{scenery}
3196\findex{scenery.add}
3197\begin{verbatim}
3198  surface(F, R, color, cull=0);
3199  surface_rev(f, [g], t_min, t_max, n_lats, n_longs, color);
3200  surface_rev(f, g, R, color, [coords]);
3201
3202  scenery S(F, R, color);
3203  S.add(F, R, color);
3204\end{verbatim}
3205The \code{color} argument is a \code{P}-valued function of two or
3206three \code{double}s whose output is interpreted as a set of
3207\code{RGB}~densities. If \code{color} takes two arguments, they are
3208\code{domain} coordinates, and the surface is colored according to
3209parameter values. If \code{color} takes three arguments, they are
3210Cartesian coordinates, and the surface is colored according to spatial
3211location.  Please see the sample files
3212\filename{surface\_shade.xp}~and \filename{S2\_harmonics.xp}.
3213\index{Plotting!surface|)}
3214
3215
3216\subsection{Calculus Plotting}
3217\index{Plotting!calculus|(}
3218
3219\ePiX\ provides high-level commands for plotting derivatives and
3220definite integrals, Riemann sums, tangent lines, slope- and vector
3221fields, and solutions of planar and spatial systems of differential
3222equations.
3223
3224In this section, \code{f}~and \code{g} are \code{double}-valued
3225functions of one variable.
3226
3227\subsubsection*{Utility Functions}
3228
3229\findex{sup}
3230\findex{inf}
3231\findex{newton}
3232\begin{verbatim}
3233  sup(f, a, b);     // max/min of f on [a,b]
3234  inf(f, a, b);
3235  newton(f, g, x0); // find approximate crossing point
3236\end{verbatim}
3237Newton's method returns the crossing point of the given functions,
3238starting from the specified seed, which should be reasonably close to
3239the expected solution. If a critical point is hit or 5~iterations
3240pass, a warning is issued and the current result (probably incorrect)
3241is returned. The second function~\teximath{g} defaults to the zero function if
3242omitted.
3243
3244\subsubsection*{Derivatives and Integrals}
3245
3246The classes \code{Deriv}~and \code{Integral} are used to calculate
3247values of derivatives and integrals, and to plot these functions.
3248\findex{Deriv}
3249\findex{Deriv.eval}
3250\findex{Deriv.left}
3251\findex{Deriv.right}
3252\findex{Integral}
3253\findex{Integral.eval}
3254\begin{verbatim}
3255  Deriv df(f); // function object: df(x) = f'(x)
3256  df.eval(t);  // return f'(t)
3257  df.left(t);  // deriv from left at t:  (f(t)-f(t-dt))/dt
3258  df.right(t); // deriv from right at t: (f(t+dt)-f(t))/dt
3259
3260  Integral prim(f,a); // function object: prim(x) = int_a^x f
3261  prim.eval(b);  // numerical integral of f over [a,b]
3262  double val(Integral(f).eval(1));   // val = \int_0^1 f
3263\end{verbatim}
3264The lower limit on an integral is~0 by default. \code{Deriv}s and
3265\code{Integral}s can be used directly in a \code{plot} command:
3266\findex{plot}
3267\findex{riemann\_sum}
3268\begin{verbatim}
3269  plot(Deriv(f), a, b, n);  // plot f' over [a,b]
3270  plot(Integral(f, x0), a, b, n);
3271  riemann_sum(f, a, b, n, TYPE);
3272\end{verbatim}
3273The second graphs the definite integral \teximath{x\mapsto\int_{x_0}^x
3274f(t)\,dt} over~\teximath{[a,b]}. As above, \teximath{x_0}~defaults
3275to~0. The third draws rectangles or trapezoids whose area approximates
3276the definite integral of~\teximath{f} over~\teximath{[a,b]}. The
3277\code{TYPE} may be \code{UPPER}, \code{LOWER}, \code{LEFT},
3278\code{RIGHT}, \code{MIDPT}, or~\code{TRAP}.
3279
3280Tangent lines and envelopes (families of tangent lines) are drawn with
3281\findex{tan\_line}
3282\findex{envelope}
3283\findex{tan\_field}
3284\begin{verbatim}
3285  tan_line(f, t);                // f real- or vector-valued
3286  envelope(f, t_min, t_max, n);  // family of tangent lines
3287  tan_field(f, g, t_min, t_max, n); // field of tangents
3288\end{verbatim}
3289The sample files \filename{conic.xp}~and \filename{lissajous.xp}
3290illustrate these features.
3291
3292
3293\subsubsection*{Systems of Differential Equations}
3294
3295Let \code{F}~be a \code{P}-valued function of two or three variables.
3296\findex{ode\_plot}
3297\findex{flow}
3298\begin{verbatim}
3299  ode_plot(F, p_0, t_min, t_max, n);
3300  flow(F, p_0, t_max, n);
3301\end{verbatim}
3302The first plots the solution curve of the initial-value problem
3303\teximath{\dot{x}=F(x)}, \teximath{x(0)=p_0}, over the specified time
3304interval.  If \teximath{t_\mathrm{min}} is omitted, its value is~0, so
3305the curve starts at~\teximath{p_0}. With manual calculation to rotate
3306a planar field a quarter turn, \code{ode\_plot} can be used to draw
3307level curves (isobars) of a function of two variables; see the sample
3308file \filename{dipole.xp}.  The \code{flow} function returns the
3309result of starting at~\teximath{p_0} and flowing by~\teximath{F} for
3310time~\teximath{t_\mathrm{max}}, using Euler's method with~\teximath{n}
3311time steps.  This is useful for placing markers or arrowheads precisely
3312along a flow line.
3313
3314A planar or spatial vector field itself may be plotted over a
3315domain~\code{R} in three styles:
3316\findex{vector\_field}
3317\findex{dart\_field}
3318\findex{slope\_field}
3319\begin{verbatim}
3320  vector_field(F, R, [scale]); //  true length
3321  dart_field  (F, R, [scale]); // const length
3322  slope_field (F, R, [scale]); // const length
3323\end{verbatim}
3324The field is sampled at the grid points of the coarse mesh. If the
3325domain is 2-dimensional, the plot is a planar slice of the field, even
3326if the field depends on three variables. If the domain is
33273-dimensional, the field is drawn in successive slices
3328\teximath{x_3=\mathrm{const}}, starting at the height of the first
3329corner of~\code{R} and ending at the height of the second corner.
3330
3331The optional final argument, which defaults to~\teximath{1}, scales the
3332arrowheads in a vector field, and scales the (constant) length of
3333field elements for slope and dart fields. The sample files
3334\filename{layout2.xp}, \filename{lorenz.xp}, \filename{slopefield.xp},
3335and \filename{vfield.xp} illustrate usage.
3336
3337In each field-plotting command, the domain argument may be replaced by
3338two points, representing corners of a coordinate rectangle, and two
3339integers, the number of grid intervals in the selected coordinate
3340directions. Only planar slices of a vector field can be plotted using
3341the alternative syntax.
3342\index{Plotting|)}
3343\index{Plotting!calculus|)}
3344
3345
3346\subsection{Non-Euclidean Geometry}
3347\label{non-eucl}
3348
3349\ePiX\ provides limited features for spherical and hyperbolic
3350geometry: the ability to draw lines in the half-plane and Poincar\'e
3351disk models of the hyperbolic plane, and to draw latitudes,
3352longitudes, great circle arcs, spherical triangles, regular polyhedra,
3353and parametrized curves on a sphere.
3354
3355Hyperbolic line segments are specified by their endpoints in the upper
3356half space or ball (Poincar\'e) models.  In each case there is no
3357output if either endpoint lies outside the model.
3358\findex{hyperbolic\_line}
3359\findex{disk\_line}
3360\begin{verbatim}
3361  hyperbolic_line(p, q);
3362  disk_line(p, q);
3363\end{verbatim}
3364For compatibility with 2-dimensional hyperbolic space, the half-space
3365model is the set \teximath{\{(x_1,x_2,x_3)\mid x_2>0\}}.
3366
3367\index{Plotting!spherical|(}
3368A \code{frame} determines geographical coordinates on a \code{Sphere}:
3369the first element points toward longitude~0 on the equator, the third
3370element points to the north pole.  A latitude line depends on a
3371\code{Sphere}, a \code{frame}, the numerical latitude, and a range of
3372longitudes. A longitude line is described similarly.
3373\findex{latitude}
3374\findex{longitude}
3375\findex{back\_latitude}
3376\findex{back\_longitude}
3377\begin{verbatim}
3378  latitude(lat, long_min, long_max, Sphere S, frame coords);
3379  longitude(lngtd, lat_min, lat_max, Sphere S, frame coords);
3380\end{verbatim}
3381By default, \code{coords} is the standard \code{frame} and \code{S} is
3382the unit sphere. These commands draw only the portion of the curve
3383that is visible from the current viewpoint. The function
3384\code{back\_latitude} draws the invisible portion of a latitude line.
3385
3386Spherical arcs and triangles are described by their endpoints. Only
3387the direction vector from the center of the sphere to an endpoint is
3388significant; if a sphere is scaled or moved, the same function call
3389will draw the corresponding object on the new sphere.
3390
3391The following draw the visible (front) portions of great circle arcs:
3392\findex{front\_arc}
3393\findex{front\_arc2}
3394\findex{front\_line}
3395\findex{back\_arc}
3396\findex{back\_arc2}
3397\findex{back\_line}
3398\begin{verbatim}
3399  front_arc(p1, p2, S);  // short arc on S from p1 to p2
3400  front_arc2(p1, p2, S); // arc from p1 to -p1 through p2
3401  front_line(p1, p2, S); // great circle through p1 and p2
3402\end{verbatim}
3403Triangles and regular (Platonic) polyhedra are provided. The sample
3404file \filename{sample/polyhedra.xp} illustrates usage.
3405\findex{front\_triangle}
3406\findex{front\_tetra}
3407\findex{front\_cube}
3408\findex{front\_octa}
3409\findex{front\_dodeca}
3410\findex{front\_icosa}
3411\findex{back\_triangle}
3412\findex{back\_tetra}
3413\findex{back\_cube}
3414\findex{back\_octa}
3415\findex{back\_dodeca}
3416\findex{back\_icosa}
3417\begin{verbatim}
3418  front_triangle(p1, p2, p3, S); // spherical triangle
3419  front_tetra(S, coords);  // regular tetrahedron
3420  front_cube(S, coords);   //    hexahedron
3421  front_octa(S, coords);   //    octahedron
3422  front_dodeca(S, coords); //    dodecahedron
3423  front_icosa(S, coords);  //    icosahedron
3424\end{verbatim}
3425Each function has a \code{back} version, which draws the hidden
3426portion. The tetrahedron, cube, and octahedron are (up to scale)
3427inscribed in the cube of side length~\teximath{2} centered at the origin whose
3428sides are parallel to~\code{frame}. The point \teximath{(1,1,1)} is a vertex of
3429the tetrahedron.
3430
3431Up to scale, the icosahedron's vertices lie on the golden rectangle
3432with vertices \teximath{(\pm\gamma,0,\pm1)} and its images under cyclic
3433permutation of coordinates. The dodecahedron is dual to the
3434icosahedron.
3435
3436\subsubsection*{Spherical Geometry}
3437
3438\index{Sline}
3439
3440The \code{Sline} class represents geodesic arcs on the unit sphere,
3441and provides intersection and reflection operators.
3442\findex{Sline}
3443\findex{pole}
3444\findex{cosine}
3445\findex{reflect}
3446\findex{collinear}
3447\findex{cuts}
3448\findex{draw}
3449\findex{draw\_front}
3450\findex{draw\_back}
3451\findex{draw\_line}
3452\findex{line\_front}
3453\findex{line\_back}
3454\begin{verbatim}
3455  Sline L1(tail, head); // non-proportional vectors
3456  L1.pole();            // pole of equator
3457  L1.cosine();          // subtended arc
3458  L1.reflect(arg);      // reflect arg across L1
3459  L1.reflect(L2);       // reflect L2 across L1
3460  L1.collinear(L2);     // test for collinearity
3461  L1.cuts(L2);          //   or crossing
3462  L1.draw();            // arc
3463  L1.draw_front();      // front arc (same for back)
3464  L1.draw_line();       // draw entire line
3465  L1.line_front();      // front line (same for back)
3466\end{verbatim}
3467
3468
3469\subsubsection*{Spherical Plotting}
3470
3471Parametrized paths on a \code{Sphere~S} (by default the unit sphere)
3472can be specified either by radial projection of a \code{P}-valued
3473curve, or by stereographic projection of a plane curve given as a pair
3474of \code{double}-valued functions:
3475\findex{frontplot\_R}
3476\findex{frontplot\_N}
3477\findex{frontplot\_S}
3478\findex{backplot\_R}
3479\findex{backplot\_N}
3480\findex{backplot\_S}
3481\begin{verbatim}
3482  frontplot_R(phi, t_min, t_max, n, [S]);    // radial
3483  frontplot_N(f1, f2, t_min, t_max, n, [S]); // from north pole
3484  frontplot_S(f1, f2, t_min, t_max, n, [S]); // from south pole
3485\end{verbatim}
3486Attempts to perform radial projection on a path through the origin
3487will generate division-by-zero errors. Stereographic projection maps
3488the equatorial plane \teximath{\{x_3=0\}} to the unit sphere by
3489projection from the corresponding pole: \teximath{N=(0,0,1)},
3490\teximath{S=(0,0,-1)}.
3491
3492Each spherical plot command has a \code{back} version that prints only
3493the portion of the path invisible from the current viewpoint.
3494Because of the way \ePiX\ layers output, it is generally best to put
3495hidden portions of the input before visible portions, with line width
3496and/or style that suggests hidden lines.
3497\index{Plotting!spherical|)}
3498
3499
3500\subsection{Data Plotting}
3501\index{Plotting!data|(}
3502\index{Data plotting|(}
3503
3504Thanks in large part to code and ideas from Marcus Hanwell, files of
3505numerical data can be created, manipulated, analyzed, plotted (paths,
3506scatter plots, and histograms), read, and written.  The format for a
3507data file is one or more floating-point numbers per line, with the
3508same number of entries per line. Anything that appears on a line after
3509the \LaTeX\ comment character~\code{\%} is a comment.
3510
3511\ePiX\ provides two \code{plot} commands for file data. The first
3512facilitates plotting selected columns; the second simplifies plotting
3513the first two columns with one or both scales logarithmic. Either form
3514can be used to plot selected columns logarithmically.
3515
3516The general commands read numbers from two or three columns of a
3517specified file, pass them as arguments to a \code{P}-valued
3518function~\code{F}, and plot the resulting points:
3519\findex{plot}
3520\begin{verbatim}
3521  plot("filename", STYLE, [i_1], [i_2], [i_3], [F]);
3522  plot("filename", STYLE, F, [i_1], [i_2], [i_3]);
3523\end{verbatim}
3524The first argument is the name of the data file. The \code{STYLE} may
3525be \code{PATH}, which joins the points in the order they appear, or
3526any of the marker types in Table~\ref{table-marker}.  The
3527integers~\teximath{i_k} specify columns from which to extract data; these
3528default, respectively, to the first column, second column, and null (a
3529column of zeroes). If the ``coordinate system''~\code{F} is omitted in
3530the first command, it defaults to the Cartesian point constructor. The
3531function~\code{F} is mandatory in the second form; useful choices
3532include \code{log\_log}, \code{log\_lin}, and~\code{lin\_log}, which
3533plot the corresponding coordinate logarithmically.
3534
3535
3536\subsubsection*{Data Files}
3537
3538For more elaborate analysis, the \code{data\_file} class presents an
3539interface to a file as an ordered list of columns. There are two
3540general ways to create a \code{data\_file}: read in an external file,
3541or generate data (up to three columns) using specified
3542\code{double}-valued functions. In the constructors below, each
3543function~\code{fi} is a \code{double}-valued function of one variable.
3544\findex{data\_file}
3545\findex{data\_file.read}
3546\begin{verbatim}
3547  data_file DF("my_data"); // read data from disk file
3548  data_file DF(f1, t_min, t_max, num_pts); // values of f1
3549  data_file DF(f1, f2, t_min, t_max, num_pts);
3550  data_file DF(f1, f2, f3, t_min, t_max, num_pts);
3551  data_file DF(3);  // create empty data_file with 3 columns
3552  DF.read("file1"); // read a disk file
3553\end{verbatim}
3554
3555Columns of a \code{data\_file} can be transformed by a user-specified
3556function, averaged, correlated, extracted (for use by other code),
3557scatter plotted, and written to a disk file at specified
3558precision. Below, the function~\code{f} is a \code{double}-valued
3559function of one variable and~\code{F} is a \code{P}-valued function of
3560two or three variables, whose components are written back to the
3561selected columns.
3562\findex{data\_file.transform}
3563\begin{verbatim}
3564  DF.transform(f, i);    // apply f to selected column(s)
3565  DF.transform(F, i=1, j=2);
3566  DF.transform(F, i, j, k);
3567\end{verbatim}
3568Basic statistical operations on columns are provided.
3569\findex{data\_file.dot}
3570\findex{data\_file.avg}
3571\findex{data\_file.var}
3572\findex{data\_file.covar}
3573\findex{data\_file.regression}
3574\begin{verbatim}
3575  DF.dot(i,j);        // dot product of columns i, j
3576  DF.avg(i);          // mean of column i
3577  DF.var(i);          // population variance
3578  DF.covar(i,j);      // covariance
3579  DF.regression(i,j); // plot regression line
3580\end{verbatim}
3581A \code{data\_file} is scatter plotted using syntax as described above.
3582% The output is cropped automatically to the bounding box.
3583\findex{data\_file.plot}
3584\begin{verbatim}
3585  DF.plot(STYLE, [i1], [i2], [i3], [F]);
3586  DF.plot(STYLE, F, [i1], [i2], [i3]);
3587\end{verbatim}
3588Histograms and bar charts are described below.
3589
3590A \code{data\_file} can be written to a disk file as raw data, or in
3591specified format. Below, \code{fmt} denotes a \code{string}-valued
3592formatting function of two variables and \filename{myfile} is the
3593name of the disk file to be written.
3594\findex{data\_file.precision}
3595\findex{data\_file.write}
3596\begin{verbatim}
3597  DF.precision(4);    // set to 4 significant figures
3598  DF.write("myfile"); // write as tab-separated columns
3599  DF.write("myfile", fmt, [i1], [i2]); // apply fmt to cols
3600\end{verbatim}
3601A column can be extracted as a \code{C++}~\code{vector} for use by
3602another function.
3603\findex{data\_file.column}
3604\begin{verbatim}
3605  DF.column(i);    // i-th column
3606  DF.column(f, i); // i-th column, transformed by f
3607\end{verbatim}
3608
3609
3610\subsubsection*{Data Containers}
3611
3612\ePiX\ provides a \code{data\_mask} class for culling data from a file
3613according to the values in a specified column, and a \code{data\_bins}
3614class for sorting data by value.
3615
3616A \code{data\_mask} consists of an interval of numbers and a
3617``filter'' function. The (closed, open, or half-open) interval is
3618given as a string in standard mathematical notation, or by its
3619endpoints (for a closed interval).  The filter is a
3620\code{double}-valued function of \code{double}, by default the
3621identity, \teximath{f(x)=x}.
3622\findex{data\_mask}
3623\begin{verbatim}
3624  data_mask dm("[a, b]", [f]);
3625  data_mask dm(a, b, [f]);
3626\end{verbatim}
3627A \code{data\_mask} ``passes'' inputs~\teximath{x} if~\teximath{f(x)}
3628lies in the interval. The member function \code{reverse()} inverts
3629this logical test.
3630
3631The \code{data\_file} class has \code{prune} functions to cull
3632rows for which a specified column's entry satisfies a
3633\code{data\_mask}'s criterion.
3634\findex{data\_mask.prune}
3635\begin{verbatim}
3636  DF.prune(dm, i);   // remove row if i-th column entry fails
3637  DF.prune(a, b, i); // remove row if i-th column outside [a,b]
3638\end{verbatim}
3639
3640A \code{data\_bins} object models an interval divided at specified
3641locations into ``bins'', not necessarily of equal length. Numerical
3642data is read in and the number of points in each bin counted. The
3643lifetime of a \code{data\_bins} object has two stages. First, ``cuts''
3644(endpoints of subintervals) are added. Then, once data is read, the
3645cuts are ``locked'' and cannot subsequently be changed.
3646\findex{data\_bins}
3647\findex{data\_bins.cut}
3648\findex{data\_bins.read}
3649\begin{verbatim}
3650  // [xmin, xmax] divided into n equal intervals, 1 by default
3651  data_bins db(xmin, xmax, [n]);
3652  db.cut(x);  // add a cut at x (if x is in bounds)
3653  db.read(vector<double>); // read data, lock bins
3654\end{verbatim}
3655
3656\index{Histograms}
3657\index{Bar Charts}
3658A \code{data\_bins} object can be plotted as a histogram (rectangles'
3659\emph{area} is proportional to the bin population), bar chart
3660(rectangles' \emph{height} is proportional to the bin population), or
3661spline interpolation of a bar chart.
3662\findex{data\_bins.histogram}
3663\findex{data\_bins.bar\_chart}
3664\findex{data\_bins.plot}
3665\begin{verbatim}
3666  db.histogram(c=1);  // c = vertical scale factor
3667  db.bar_chart(c=1);
3668  db.plot(c=1);
3669\end{verbatim}
3670By default (\code{c=1}), the height of a bar chart rectangle is the
3671fraction of the total population contained in the bin; thus, the
3672height is always between 0~and 1. For a histogram, the height of a
3673rectangle is the fraction of the population per horizontal unit in the
3674bin; thus, the total area over an interval~\teximath{[a,b]} does not
3675depend on how~\teximath{[a,b]} has been subdivided. The sample files
3676\filename{dataplot.xp}~and \filename{histogram.xp} illustrate use.
3677
3678Statistical convention dictates cuts be chosen distinctly from data
3679values; that is, values should all fall strictly within a bin, not at
3680a boundary point. With large, unknown data sets, this convention may
3681be difficult to uphold. \ePiX\ attempts to handle anomalous data
3682intelligently, by keeping counts of values ``out-of-range'' or
3683``on-cut''.
3684
3685In detail, if \teximath{x<a} or \teximath{x>b} is a data value, it is
3686counted as out-of-range and does not contribute to the histogram
3687population. If \teximath{x=a} or \teximath{x=b}, the value counts as
3688both out-of-range and on-cut but is added to the population of the
3689lowest or highest bin, respectively. Any other cut appearing as a data
3690input is flagged as on-cut, and increments the population of each
3691adjacent bin by one-half. When a histogram or bar chart is written,
3692\ePiX\ prints a warning message summarizing the number of anomalous
3693data seen.
3694
3695
3696\subsubsection*{Error Bars}
3697\index{Error bars}
3698
3699Simple horizontal and vertical error bars are provided.  The final
3700(optional) argument is the true height or width (respectively) in pt.
3701\findex{h\_error\_bar}
3702\findex{v\_error\_bar}
3703\begin{verbatim}
3704  h_error_bar(P location, double error, <mark type>, ht=6);
3705  v_error_bar(P location, double error, <mark type>, wd=6);
3706\end{verbatim}
3707
3708To create more complex elements, such as asymmetric bars, whisker
3709plots, labeled error bars, and the like, write a custom function using
3710true-size drawing, see page~\pageref{truesize}. For example, a
3711fillable, labeled, asymmetric, vertical rectangular error bar can be
3712implemented (entirely in \ePiX) like this:
3713\begin{verbatim}
3714  void error_bar(P loc, double lo, double hi, P offset,
3715                 std::string text, align, double wd=6)
3716  {
3717    const double width(pt_to_screen(0.5*wd)); // converts to 3pt
3718    rect(loc - P(width, lo), loc + P(width, hi));
3719    line(loc - P(width,  0), loc + P(width,  0));
3720    label(loc + P(width, 0), offset, text, align);
3721  }
3722\end{verbatim}
3723For stylistic uniformity, functions such as this should be put into a
3724library and used systematically. Section~\ref{section-extensions}
3725outlines the process of writing, compiling, and using a custom
3726library.
3727\index{Plotting!data|)}
3728\index{Data plotting|)}
3729
3730
3731\subsection{Legends}
3732\index{Legends}
3733
3734A \code{legend} systematically labels different parts of a plot by
3735associating visual ``keys'' with explanatory text. This tends to be
3736most useful for plots containing several distinct but conceptually
3737related graphs requiring contrast.
3738
3739Visually, a \code{legend} is represented as an aligned list of rows,
3740each containing a box (the key), a gap (the label skip), and some
3741text.  These rows are printed in a (usually large) masked label. By
3742default, keys are \code{12pt}~squares bordered in black, the label
3743skip is~\code{6pt}, the background is white, and the border is plain
3744black. These attributes are controlled (simultaneously for all items)
3745with member functions.  Parameters of type \code{double} represent
3746lengths in~\code{pt}.
3747\findex{legend}
3748\findex{legend.backing}
3749\findex{legend.border}
3750\findex{legend.item\_border}
3751\findex{legend.label\_skip}
3752\findex{legend.key\_size}
3753\begin{verbatim}
3754  legend L;
3755  L.backing(color);          // set background
3756  L.border(color, [double]); // set border color [and width]
3757  L.border(double);          // border width
3758
3759  L.item_border(color, [double]);
3760  L.item_border(double);     // same, for item borders
3761
3762  L.label_skip(double);
3763  L.key_size(double);
3764\end{verbatim}
3765
3766
3767\subsubsection*{Legend Keys}
3768
3769There are three types of legend key, representing filled regions,
3770paths, and markers. Fill and path keys get their visual attributes
3771from the current drawing state. A mark key must be told the marker
3772type. Each is created by specifying the item text.
3773\findex{legend.fill\_item}
3774\findex{legend.path\_item}
3775\findex{legend.mark\_item}
3776\begin{verbatim}
3777  L.fill_item(text);
3778  L.path_item(text);
3779  L.mark_item(<mark type>, text);
3780\end{verbatim}
3781Keys in the printed legend appear in the same order they are created
3782in the input file.
3783
3784
3785\subsubsection*{Creating a Legend}
3786
3787Normally, a \code{legend} is defined near the start of a file, and an
3788item is added at the point in the file where the corresponding object
3789or plot is drawn, so that the item receives the correct attributes. A
3790\code{legend} is placed into the figure with the \code{draw}
3791function. The arguments have the same meaning as for ordinary
3792\code{label}s.
3793\findex{legend.draw}
3794\begin{verbatim}
3795  L.draw(P location, P offset, align);
3796\end{verbatim}
3797All three arguments are mandatory.  ``Global'' \code{legend} settings
3798(border, backing, etc.) may be changed anywhere between the
3799\code{legend}'s creation and \code{draw} function. The sample file
3800\filename{legend.xp} revisits the example on
3801page~\pageref{taylor_poly}, including a trig-labeled axis and a
3802legend. The file \filename{shadeplot.xp} contains filled keys, and
3803\filename{dataplot.xp} contains a \code{legend} with items of mixed
3804type.
3805
3806
3807\section{More About \CXX}
3808\index{Cplusplus@\CXX|(emph}
3809
3810A textbook or similarly detailed reference is essential for serious
3811study of~\code{C} or~\CXX. \emph{The \code{C} Programming Language},
3812second edition, by Kernighan~and Ritchie~\cite{KnR}, is an excellent,
3813manageable resource for the basics of procedural
3814programming. \emph{C++ Primer Plus}, by Stephen Prata~\cite{Prata},
3815clearly lays out the extensive details of~\CXX.  Marshall Cline's
3816\emph{\CXX\ FAQ Lite}~\cite{Cline} engagingly discusses common points
3817of confusion and furnishes tips on good design and programming.
3818
3819\CXX\ is a powerful, complex language whose syntax is similar to that
3820of~\C, or to the scripting languages of Maple~and Mathematica. An
3821\ePiX\ input file is source code for a \CXX~program that writes a
3822\LaTeX\ picture as output.  \ePiX\ may be viewed as an extension
3823to~\CXX; in the same way that \LaTeX\ furnishes a high-level interface
3824to~\TeX, \ePiX\ provides a high-level bridge between the computational
3825power of~\CXX\ and the \LaTeX\ \code{picture} environment.
3826
3827\index{Function}
3828\index{Conditional statement}
3829Like all high-level programming languages, \CXX\ provides variables,
3830functions, and control structures. Variables hold pieces of data such
3831as numerical values and geometric locations, while functions operate
3832on data. A control structure, such as a loop or conditional statement,
3833affects the program's course according to the program's current state.
3834A source file is composed primarily of ``statements'', which perform
3835actions ranging from defining variables and functions to setting
3836figure attributes, performing calculations, and writing objects to the
3837output file.
3838
3839\subsection{Names and Types}
3840
3841\index{Variable!names|(}
3842Names of variables and functions may consist (only) of letters,
3843digits, and the underscore character. The first character of a name
3844must not be a digit, and the language standard reserves names starting
3845with underscore for library authors. Names are case-sensitive, but
3846it's usually a bad idea to use a single name capitalized and
3847uncapitalized in a single file. Numerous capitalization conventions
3848are used informally; this document uses uncapitalized words separated
3849by underscores for variables and functions, and occasionally uses all
3850capitals for constants. As with names of \LaTeX\ macros, primary
3851considerations are clarity (of meaning), readability, and consistency.
3852\index{Variable!names|)}
3853
3854\index{Variable!type of}
3855Every variable in \CXX\ has a ``type'',
3856such as integer (\code{int}), double-precision floating point
3857(\code{double}), or Boolean (\code{bool}, true~or false).  \ePiX\
3858provides additional types, the most common of which is~\code{P}, for
3859point. The construct \code{P(x,y,z)} creates~\teximath{(x,y,z)}, while
3860\code{P(x,y)} gives~\teximath{(x,y,0)}, which is effectively the
3861pair~\teximath{(x,y)}. A variable is defined by giving its type, its
3862name, and an initializing expression.
3863
3864\index{Variable!pointer}
3865\index{Pointer}
3866In~\code{C} and~\CXX, a \emph{pointer} variable holds the memory
3867address of another variable. Pointers are useful for manipulating
3868(possibly large) data structures through ``handles'' of fixed small
3869size. \CXX\ also provides \emph{references}, which bind an additional
3870name to an existing object and allow the object to be manipulated
3871through this alias. The statements
3872\begin{verbatim}
3873  double  x=1;   // ordinary variable definition
3874  double& rx=x;  // bind a reference, signified by &
3875\end{verbatim}
3876define a variable~\code{x} having the value~1, and bind a reference
3877variable~\code{rx} to it. As long as~\code{rx} exists, it refers
3878to~\code{x}. If the value of~\code{x} changes, the value of~\code{rx}
3879does as well. Conversely, the value of~\code{x} can be altered by
3880assigning to~\code{rx}. However,~\code{rx} is the size of a pointer,
3881regardless of the size of~\code{x}, so~\code{rx} can be passed
3882efficiently in a function call.
3883\texicomment
3884Some applications are discussed on page~\pageref{references}.
3885\texicommentend
3886
3887
3888\subsection{Functions}
3889
3890\index{Function|(}
3891In a programming language, the term ``function'' refers to a block of
3892code that is executable by name.  A \CXX\ function takes a list of
3893``arguments'', and has a ``return value''.  This information, together
3894with the function's name, must be provided when a function is defined.
3895A function may not be defined inside another function. However, a
3896function may call other functions (including itself) as part of its
3897execution:
3898\begin{verbatim}
3899  int factorial(unsigned int n)
3900  {
3901    if (n == 0) return 1;
3902    else return n*factorial(n-1);
3903  }
3904\end{verbatim}
3905
3906\index{Function!returning \code{void}}
3907The special type~\code{void} represents a ``null type''. A function
3908that performs an action but does not return a value has return type
3909\code{void}. A function that takes no arguments may be viewed as
3910taking a single \code{void} argument.
3911
3912Every \CXX\ program has a special function~\code{main()}, which is
3913called by the operating system when the program is run. The arguments
3914of~\code{main()} are command-line arguments, and the return type is an
3915integer that signals success or failure. User-specified functions must
3916be defined before the call to \code{main()} or in a
3917separately-compiled file.
3918
3919Functions in~\CXX\ may be as simple as an algebraic formula or as
3920complex as an arbitrary algorithm. Greatest common divisors, finite
3921sums, numerical derivatives and integrals, solutions of differential
3922equations, recursively generated fractal curves, and curves of best
3923fit are a few applications in \ePiX. Several sample files contain
3924user-level algorithms, which do not require knowledge of \ePiX's
3925internal data structures. The source file \filename{functions.cc}
3926contains simple functions defined by algorithms, and
3927\filename{functions.h} illustrates the use of \CXX\ templates. Other
3928source files, such as \filename{plots.cc}, may be consulted for
3929Simpson's rule, Euler's method, and the like.
3930
3931
3932\subsection{Mathematical Functions}
3933
3934\index{Function!mathematical|(}
3935\CXX~knows several familiar mathematical functions by name:
3936\begin{verbatim}
3937  sqrt   exp   log   log10   ceil   floor   fabs
3938\end{verbatim}
3939(\code{fabs} is the absolute value for a floating-point argument.)
3940\ePiX\ provides trig and inverse trig functions sensitive to angular
3941mode:
3942\index{Angle!mode}
3943\findex{Cos}
3944\findex{Sin}
3945\findex{Tan}
3946\findex{Sec}
3947\findex{Csc}
3948\findex{Cot}
3949\findex{Acos}
3950\findex{Asin}
3951\findex{Atan}
3952\begin{verbatim}
3953  Cos       Sin       Tan
3954  Sec       Csc       Cot
3955  Acos      Asin      Atan
3956\end{verbatim}
3957The inverse functions are principle branches.
3958
3959The function \code{pow(x,y)} returns~\teximath{x^y} when
3960\teximath{x>0}, and \code{atan2(y,x)} (N.B. argument order) returns
3961\teximath{\mathrm{Arg}(x+iy)\in(-\pi,\pi]}, the principle branch of
3962arg.  \CXX~knows many constants to 20~decimal places, such as
3963\code{M\_PI}, \code{M\_PI\_2}, and \code{M\_E} for~\teximath{\pi},
3964\teximath{\pi/2}, and~\teximath{e} respectively.  \ePiX\ defines a few
3965additional functions:
3966\findex{sgn}
3967\findex{zero}
3968\findex{sinx}
3969\findex{cb}
3970\begin{verbatim}
3971  sgn   zero   sinx   cb
3972\end{verbatim}
3973\texicomment
3974\begin{center}
3975  \input{sgn.eepic}\qquad
3976  \input{sinx.eepic}\qquad
3977  \input{cb.eepic}
3978\end{center}
3979\medskip
3980\texicommentend
3981\code{sgn} is the signum function; \code{zero} is the constant
3982function; \code{sinx} is the function \teximath{x\mapsto \sin(x)/x}
3983with the discontinuity removed; \code{cb} (for ``Charlie Brown'') is
3984the period-2 extension of the absolute value function
3985on~\teximath{[-1,1]}.
3986
3987The GNU \CXX\ library defines other functions, including inverse
3988hyperbolic functions (\code{acosh}, etc.), \code{log}~and \code{exp}
3989with base~2, 10, or arbitrary~\teximath{b} (\code{log2}, etc.), the
3990error and gamma functions (\code{erf}~and \code{tgamma} [sic],
3991respectively), and Bessel functions of first and second kind:
3992\code{j0}, \code{j1}, \code{y0}, etc. Use, e.g., \code{jn(5,~)} to get
3993higher indices.  The GNU \C~library reference manual~\cite{GNUC}
3994describes these and other functions in detail.
3995
3996Functions may be used in subsequent definitions, and functions of two
3997(or more) variables are defined in direct analogy to functions of one
3998variable:
3999\begin{verbatim}
4000double f(double t) { return t*t*log(t*t); } // t^2 \ln(t^2)
4001double g(double s, double t) { return exp(2*s)*Sin(t); }
4002\end{verbatim}
4003\index{Function!mathematical|)}
4004
4005
4006\subsection{Basics of Classes}
4007
4008\index{Classes|(}
4009Unlike~\code{C}, \CXX\ supports ``object-oriented programming''. In a
4010nutshell, a \emph{class} is an abstraction in computer code of some
4011concept, such as a point, a sphere, a mapping that can be plotted, or
4012a camera. Classes allow a programmer to separate an object's
4013\emph{interface} (the set of meaningful operations) from its
4014\emph{implementation} (the data structures and algorithms that realize
4015the interface).
4016
4017\index{Function!class member}
4018A class implementation consists of \emph{members} (named data
4019elements) and \emph{member functions} (functions that belong to the
4020class and have free access to members).  \CXX\ classes enforce access
4021permissions on their members, protecting data from being manipulated
4022except as promised by the interface.
4023
4024An ideal interface looks like a black box: It hides the implementation
4025completely.  In order to cooperate, two classes need only know each
4026other's interfaces. This separation of form and function modularizes a
4027program, and facilitates debugging, code reuse, and overall
4028maintainability, particularly in large programs.
4029
4030In simple programming, classes may be treated like built-in types.
4031Each class object has its own member functions, whose call syntax
4032differs from standard function calls:
4033\begin{verbatim}
4034  Circle C1(P(1,0), 1.5); // circle of given center and radius
4035  C1.draw();              // member function Circle::draw();
4036\end{verbatim}
4037Naturally, this call draws the circle~\code{C1}. Generally, a member
4038function call consists of a class object's name, a period, and the
4039name of the member function. Arguments, if any, go in the parentheses
4040after the member function name, just as in a regular function call.
4041
4042A few short paragraphs cannot do more than scratch the surface of
4043classes and object-oriented programming. For more details, please
4044consult a book, such as Prata~\cite{Prata} or Stroustrup~\cite{S}, or
4045Cline's on-line FAQ~\cite{Cline}.
4046\index{Classes|)}
4047
4048
4049\subsection{References and Function Arguments}
4050
4051\index{Function!call syntax}
4052\index{Variable!reference}
4053\label{references}
4054\code{C}~and \CXX\ are ``call by value'' languages. Variables are not
4055passed to a function; instead a copy of the value is made, and the
4056function operates only on the copy. Though this feature causes
4057occasional inconvenience, it prevents an object from being altered
4058unexpectedly by a function call in a different part of the program.
4059Calling by value helps localize the logic of a program, and
4060circumvents easy-to-write but extremely hard-to-find bugs.
4061
4062In \CXX, a function may accept reference arguments. Passing an object
4063by reference grants the calling function access to the object itself,
4064not to a copy. There are two common applications: The object is a
4065large data structure for which copying is ``expensive'', or the
4066function \emph{needs} to modify its arguments (e.g., a function
4067\code{swap(x,y)} that exchanges the values of \code{x}~and
4068\code{y}).
4069
4070For the first situation, \CXX\ provides the \code{const} keyword,
4071which ensures the function does not modify its arguments, but accepts
4072a reference merely for efficiency. Any attempt to modify a
4073\code{const} argument will be caught by the compiler. Most \ePiX\
4074commands accept \code{const} reference arguments.
4075
4076The ability to pass function arguments by reference is sometimes
4077touted as a feature in \CXX\ texts. However, the technique circumvents
4078the data encapsulation of calling by value, and should be avoided
4079unless absolutely necessary. If a function merely ``updates'' the
4080value of a variable, probably the variable should be of class type,
4081and the update should be performed by a member function.
4082
4083A function declaration must indicate that its arguments are
4084references. The declarations below have the indicated idiomatic
4085meanings.
4086\begin{verbatim}
4087  class matrix;
4088  double det(matrix); // call by value, perhaps inefficient
4089  matrix& transpose(matrix&); // probably changes its argument
4090  double trace(const matrix&); // does not change its argument
4091\end{verbatim}
4092Unlike pointer arguments, reference arguments impose no syntactic
4093burden on the user. If~\code{A} is a~\code{matrix}, then
4094\code{transpose(A);} and \code{trace(A);} will compile. You need not
4095declare explicit reference variables and pass those to the function.
4096
4097
4098\subsection{Overloading}
4099
4100\index{Function!overloaded}
4101\CXX\ provides ``overloading'': Multiple functions can be given the
4102same name, so long as the number and/or type of their arguments
4103differ. (It is \emph{not} enough for the return types alone to differ.
4104The compiler must be able to select a function from its calling
4105syntax.)  To the user, the appearance is that a single function
4106intelligently handles multiple argument lists. Naturally, overloaded
4107names should refer to functions that are conceptually related.
4108\index{Function|)}
4109
4110
4111\subsection{Scope}
4112
4113\index{Variable!local}
4114A \CXX\ statement ends with a semicolon. A collection of statements
4115enclosed by curly braces is a ``code block'', and may be viewed as a
4116single logical statement. Curly braces determine a ``scope'', inside
4117which variable names may be re-used without ambiguity.  Function
4118bodies are code blocks, as are the alternatives associated to control
4119statements.  A variable defined between curly braces is said to be
4120\emph{local} to the scope in which it is defined; its value cannot
4121be used out of scope.  Variables should be declared in the smallest
4122scope possible.
4123
4124The compiler is not picky about spaces, tabs, and newlines, so an
4125input file should be formatted to make local scopes visually
4126apparent. \code{emacs} automatically indents code to reflect scope,
4127though the default behavior does not please all users.  As with
4128variable naming, clarity and consistency are paramount.
4129
4130
4131\subsection{Headers and Pre-Processing}
4132
4133A \CXX\ source file is compiled in multiple stages that occur
4134transparently to the user. The first step, pre-processing, involves
4135simple text replacement for file inclusion, macro expansion and
4136conditional compilation. Next, the source is compiled and assembled:
4137Human-readable language instructions are parsed, then represented in
4138assembly language. Finally, the object files are linked: Function
4139calls are resolved to hard-coded file offsets, possibly involving
4140external library files, and the program instructions are packaged into
4141an executable binary that the operating system can run.
4142
4143Pre-processing is used much less in~\CXX\ than in~\code{C}; the
4144language itself supports safer and more featureful alternatives to
4145macros, such as \code{const} variables and inline functions. File
4146inclusion and conditional compilation are the chief uses of the
4147pre-processor. Lines of the form
4148\begin{verbatim}
4149  #include <iostream>
4150  #include "epix.h"
4151\end{verbatim}
4152cause the contents of a \emph{header file} to be read into the source
4153file. A header file contains variable and function
4154\emph{declarations}, statements that specify types and names but do
4155not define actual data. Declarations tell the compiler just enough
4156to resolve expressions and function calls without knowing specific
4157values or function definitions.
4158
4159\index{Input file!conditional compilation}
4160Conditional compilation is similar to conditional \LaTeX\ code. For
4161example, a file might produce either color or monochrome output as
4162follows:
4163\begin{verbatim}
4164#ifdef COLOR
4165  ...  // code for generating color figure
4166#endif /* COLOR */
4167#ifndef COLOR
4168  ...  // monochrome code
4169#endif /* undef COLOR */
4170\end{verbatim}
4171The ``compiler symbol'' \code{COLOR} is an ordinary \CXX\ name. To
4172control compilation, either put a \code{\#define COLOR} line in the
4173file, or (better) supply the flag on the command line: \\
4174\verb+  epix -DCOLOR <file.xp>+ \\
4175Every \code{\#ifdef} must have a matching \code{\#endif}. Commenting
4176the \code{\#endif} is a good habit; in a realistic file, the start and
4177end of a conditional block may be separated by more than one screen.
4178
4179
4180\subsection{Comparison with \LaTeX\ Syntax}
4181
4182As a programming language, \CXX\ provides certain features common to
4183all languages (such as \LaTeX, MetaPost, Perl, Lisp\ldots) and adheres
4184to rules of grammar. Salient differences between \LaTeX\ and \CXX\
4185include:
4186
4187\begin{enumerate}
4188\item Every \CXX\ statement and function call must end with a
4189  semicolon. An omitted semicolon may result in a cryptic error
4190  message from the compiler. Pre-processor directives, which start
4191  with a~\code{\#}, do not end with a semicolon.
4192
4193\item Backslash is an escape character in \CXX:
4194  \index{Label}
4195\begin{verbatim}
4196  // Put label $y=\sin x$ at (2,1)
4197  // Note single  ^ backslash in output
4198  label(P(2,1), P(0,0), "$y=\\sin x$");
4199  //       Double backslash ^^ in source
4200\end{verbatim}
4201
4202\item Variable and function names may contain letters (including
4203  underscore) and digits \emph{only}, are case sensitive, and must
4204  begin with a letter.
4205
4206\item Variables in \CXX\ must have a declared \emph{type}, such as
4207  \code{int} (integer) or \code{double} (double-precision floating
4208  point). If a variable has global scope and its value does not
4209  change, the definition should probably come in the preamble or at
4210  the beginning of \code{main}. Local variables should be defined in
4211  the smallest possible scope. Unlike~\C, \CXX\ allows variables to be
4212  defined where they first appear.
4213
4214\item \CXX~requires explicit use of~\code{*} to denote multiplication;
4215  juxtaposition is not enough. \CXX~does not support the use of
4216  \verb+^+ for exponentiation, e.g., \verb+t^2+ is invalid. Instead,
4217  use \code{t*t}~or \code{pow(t,2)}.
4218
4219\item \CXX\ has single- and multi-line comments. Everything between a
4220  double slash and the next newline is ignored, while the strings
4221  \verb+/*+~and \verb+*/+ delimit multi-line comments. A single-line
4222  comment may appear within a multi-line comment, but the compiler
4223  does not nest multi-line comments.
4224  \index{Input file!comment in}
4225
4226\end{enumerate}
4227
4228Between them, \C~and \CXX~have about 100~reserved keywords which
4229cannot be used as function or variable names.
4230\index{Cplusplus@\CXX|)}
4231
4232
4233\section{Attribute Quick Reference}
4234\label{section-quickref}
4235
4236In the body of an input file, the ``drawing state'' determines the
4237figure's appearance. Attributes are declarations, set by commands that
4238accept arguments of the stated type.
4239
4240A \code{len} argument is a double-quoted string containing a number
4241and a two-letter \LaTeX\ length unit, such as \code{"1.5pt"} or
4242\code{"6cm"}. A \code{color} argument is a named primary
4243(\code{Red()}, \code{Cyan()}, \code{White()}, etc.), a \code{Color}
4244specified by densities (\code{RGB(...)}, \code{CMYK(...)}, etc.), or a
4245\code{Color} object. Using \code{Neutral()} as a \code{Color} argument
4246generally turns off the corresponding attribute.
4247
4248\begin{itemize}
4249
4250\item Angular mode: \code{radians()}, \code{degrees()}, or
4251  \code{revolutions()}.
4252
4253  The angular mode affects all trigonometric operations, including
4254  camera rotations, the drawing of arcs and ellipses, polar plotting,
4255  label angle, and the trig functions themselves. Angle-sensitive trig
4256  functions are capitalized, e.g., \code{Cos}, \code{Tan}.
4257
4258\item Fill style: \code{fill(color)}, \code{fill(bool)},
4259  \code{nofill()}.
4260
4261\item Path style:
4262
4263  \begin{itemize}
4264
4265  \item Width: \code{plain()}, \code{bold()}, \code{bbold()},
4266    \code{pen(len)}.
4267
4268  \item Line style: \code{line\_style(string)}. The argument is a
4269    WYSIWYG sequence of dashes, spaces, and periods.
4270    \code{dash\_size(double)} and \code{dot\_sep(double)} set the
4271    (approximate) length in~\code{pt} of the pattern.  The commands
4272    \code{solid()}, \code{dashed()}, \code{dotted()} define
4273    ``standard'' defaults for brevity.
4274
4275  \item Path color:
4276    Paths can be drawn using \emph{two} pens, one atop the other. When
4277    the ``base'' pen is white (or the background color) and wider than
4278    the ``line'' pen, a path masks parts of the figure it crosses. A
4279    3-D effect may be obtained by making the base pen a darker shade
4280    than the ``line'' pen.
4281
4282    \code{pen(color,[len])}, \code{base(color,[len])}
4283
4284    Standard widths: \code{plain(color)}, \code{bold(color)},
4285    \code{bbold(color)}
4286
4287  \end{itemize}
4288
4289\item Text attributes:
4290
4291  \begin{itemize}
4292
4293  \item Color: \code{label\_color(color)}
4294
4295  \item Mask: \code{label\_mask(color)}, \code{label\_pad(len)}
4296
4297  \item Border: \code{label\_border(color, [len])},
4298    \code{label\_border(len)}. The command \code{no\_label\_border()}
4299    turns off label borders.
4300
4301  \item Font size: \code{font\_size(LaTeX size)}, no argument means
4302    \code{normalsize}.
4303
4304  \item Font face: \code{font\_face(LaTeX font)}, two-letter font
4305    selection string, default is \code{rm}.
4306
4307  \item Rotation: \code{label\_angle(double)}
4308
4309  \end{itemize}
4310
4311\end{itemize}
4312
4313Do not confuse \code{Color} constructors with the similarly-named
4314(deprecated) lowercase attribute-setting commands, \code{rgb(r,g,b)},
4315\code{cmyk(c,m,y,k)}, \code{red(d)}, etc. These commands affect text,
4316paths, and filled regions. For example, the single command
4317\code{red()} has the same effect as the three commands
4318\code{pen(Red())}, \code{fill(Red())}, and \code{label\_color(Red())}.
4319
4320
4321\texinfochapter{4}{Advanced Topics}
4322\label{chapter-adv}
4323
4324This chapter covers \emph{ad hoc} tricks and open-ended techniques
4325that require relatively more programming sophistication. You will
4326almost surely need an external \CXX\ reference if you do not speak the
4327language.
4328
4329
4330\section{Hidden Object Removal}
4331\label{section-hidden}
4332
4333\index{Hidden object removal|(}
4334\ePiX\ writes the output file in the same order that objects appear in
4335the input. The order is significant because PostScript builds a figure
4336in layers: Objects are drawn over objects that come earlier in the
4337file. Shaded polygons can be used to obtain surprisingly effective
4338hidden object removal in surface meshes. This section describes the
4339data structures defined in the source files \code{surface.*}.
4340
4341\index{Camera}
4342The basic idea is to create a shaded polygon class that knows its
4343approximate distance to the camera. For computational simplicity, a
4344mesh ``facet'' is treated as a quadrilateral, located at the
4345arithmetic mean of its vertices. A facet's boundary is created from a
4346map and a domain by tracing a fine mesh rectangle counterclockwise.
4347
4348To draw a parametrized surface, facets are stored in a \CXX\ vector,
4349sorted in decreasing order of distance to the camera, and printed to
4350the output file. If filling is active, the gray density of a facet
4351depends on the cosine of the angle between the normal vector and the
4352vector from the camera to the element.
4353
4354This simple algorithm works surprisingly well when mesh elements
4355intersect at most along complete edges. To incorporate line-like
4356elements (e.g., coordinate axes, wire-mesh plots) with shaded
4357surfaces, the best technique is often to order high-level scene
4358elements manually, breaking up shaded surfaces (for example, with
4359domain resizing or clipping) as necessary. The sample file
4360\filename{saddle.xp} illustrates possible techniques.
4361
4362Shaded surfaces can be decorated with a bit of hackery. For example,
4363the \code{facet::draw} function in \filename{facet.cc} can be
4364modified easily to draw line elements, tangents, or normal vectors
4365along with the facet itself. The sample file
4366\filename{decorate.xp} contains a couple of ideas. (The
4367decorations are activated by compiler flags; please consult the file
4368itself for information on compiling.)
4369\index{Hidden object removal|)}
4370
4371
4372\section{Extensions}
4373\label{section-extensions}
4374
4375Thanks to a suggestion of Andrew Sterian, \ePiX\ is extensible. User
4376extensions span a spectrum, from header files that require only basic
4377knowledge of~\CXX\ to separately compiled libraries that add
4378substantial new features.  The structure of the source code is
4379outlined in Section~\ref{section-programmers}.
4380
4381
4382\subsection{Header Files}
4383
4384A \CXX~header file conventionally has suffix~\filename{.h}, as in
4385\filename{myheader.h}. To use this custom header, put a line
4386\code{\#include "myheader.h"} in your source file.
4387
4388User definitions can be easily and robustly implemented with ``inline
4389functions''. Inline functions are superficially similar to macros, but
4390are far more safe and featureful (since they are handled by the
4391compiler rather than by the pre-processor).  Examples are
4392\begin{verbatim}
4393  inline void Bold() { pen(1.6); }
4394  inline void purple() { rgb(0.5, 0, 0.7); }
4395  inline void draw_square(double s) { rect(P(-s,-s),P(s,s)); }
4396  inline double cube(double x) { return pow(x,3); // x^3 }
4397\end{verbatim}
4398The keyword \code{void} signifies a function that does not return a
4399value, or (when used as an implicit parameter) a function that does
4400not accept arguments. Inline function definitions are syntactically
4401identical to ordinary function definitions, but \emph{must} occur in a
4402header file or in the source file where they are used. The examples
4403above might be used in an input file as follows:
4404\begin{verbatim}
4405  Bold();
4406  draw_square(cube(1.25));
4407\end{verbatim}
4408
4409
4410\subsection{Compiling}
4411
4412The next few sections outline the creation of a ``static library'' on
4413GNU/Linux, and explain how to incorporate custom features at runtime.
4414The extensively-commented sample files \filename{std\_F.cc}~and
4415\filename{std\_F.h} illustrate the techniques described below, and may
4416be used for guidance and experimentation.
4417
4418A small library is usually written as a \emph{header} file, which
4419contains class and function declarations (also called ``prototypes''),
4420and a \emph{source} file, which contains the actual
4421code. Conventionally (under *nix), these files have extension
4422\filename{.h}~and \filename{.cc} respectively. Header and source files
4423may ``include'' other header files, to incorporate additional
4424functionality.
4425\begin{verbatim}
4426/* my_code.h */
4427#ifndef MY_CODE
4428#define MY_CODE
4429#include <cmath>   // standard library math header
4430#include "epix.h"  // ePiX header
4431using ePiX::P;
4432
4433namespace Mine {   // to avoid name conflicts
4434  // functions for special relativity
4435  double lorentz_norm(const P&);
4436  bool   spacelike(const P&);
4437} // end of namespace
4438#endif /* MY_CODE */
4439\end{verbatim}
4440This file exhibits two ``safety features''. The three \code{MY\_CODE}
4441lines prevent the file from being included multiple times. In a file
4442of this size, inclusion protection is overkill, but as your code base
4443grows and the number of header files increases, this protection is
4444essential. Second, the header introduces a ``Mine'' namespace. Inside
4445this namespace, two functions are declared as prototypes, giving the
4446function's return type, name, and argument type(s). A header file
4447should be commented fairly liberally, so that a year or two from now
4448you'll be able to decipher the file's contents.  For a longer file,
4449version and contact information, an overall comment describing the
4450file's features, and license information are appropriate.
4451
4452Next, the corresponding source file; definitions are also placed into
4453the namespace, and must match their prototypes from the header file
4454exactly.
4455\begin{verbatim}
4456/* my_code.cc */
4457#include "my_code.h"
4458using namespace ePiX;
4459
4460namespace Mine {
4461  double lorentz_norm(const P& arg)
4462  {
4463    double x(arg.x1()), y(arg.x2()), z(arg.x3()); // extract coords
4464    return (y-x)*(y+x) + z*z; // -x^2 + y^2 + z^2
4465  }
4466  bool spacelike(const P& arg)
4467  {
4468    return (lorentz_norm(arg) > 0); // true if inequality is
4469  }
4470} // end of namespace
4471\end{verbatim}
4472Copies of these files are included with the source code so you can
4473experiment with them. Next, the source file must be ``compiled'',
4474``archived'', and ``indexed''. In the commands below, the percent sign
4475is the prompt.
4476\begin{verbatim}
4477% g++ -c my_code.cc
4478% ar -ru libcustom.a my_code.o
4479% ranlib libcustom.a
4480\end{verbatim}
4481Please see your system documentation for details on command options
4482and what each step does. For linking (below), the name of the library
4483file must begin ``lib'' and have the extension~\filename{.a}. Once these
4484steps are successfully completed, put the library \filename{libcustom.a}
4485and header file \filename{my\_code.h} in your project directory. You're
4486ready to use the code in an \ePiX\ figure.
4487
4488
4489\subsection{Runtime Linking}
4490
4491The script~\epix\ allows input files to be linked with external
4492libraries at run time, when the input file is compiled into a
4493temporary executable.
4494
4495\epix\ recognizes command line options and passes them verbatim to the
4496compiler. The most commonly used options are those of the form
4497\begin{verbatim}
4498   -I<include>     -L<libdir>     -l<lib>
4499\end{verbatim}
4500For example, to link \filename{figure.xp} against
4501\filename{mylibs/libcustom.a}, run the command
4502\begin{verbatim}
4503   epix -Lmylibs -lcustom figure
4504\end{verbatim}
4505The options \code{-I. -L.} tell the compiler to look in the current
4506directory for header and library files.  Compiler options may appear
4507in any order, but must come before the name of the input file(s).
4508
4509Compiler options may be placed in the configuration file
4510\filename{\$HOME/.epixrc}, with syntax as above. A line in the config
4511file that contains a pound sign~(\code{\#}) is a comment, no matter
4512where in the line the~\code{\#} appears. If any non-comment line
4513fails to start with a dash, the rest of the file is silently
4514discarded.  Command-line options are read before the config file.
4515
4516
4517\subsection{Using Multiple Versions}
4518
4519The script \filename{epix}~links by default against the \code{C}~math
4520library \code{libm.a}~and the \ePiX\ library \code{libepix.a}.  The
4521command option \code{--no-defaults} clears the header and include
4522paths and removes \code{libepix.a} from the link list. The script may
4523therefore be used with multiple versions of \ePiX, a potentially
4524useful feature if you regularly need to compile old source files, or
4525simply prefer the syntax of an older version.
4526
4527To install and use (say) Version~1.0.0, build the package according to
4528its \filename{INSTALL} instructions, but \emph{do not use the makefile
4529  to install}. Instead, manually install the header and library only,
4530using their version number:
4531\begin{verbatim}
4532# install -m 644 epix.h /usr/local/include/epix-1.0.h
4533# install -m 644 libepix.a /usr/local/lib/libepix-1.0.a
4534\end{verbatim}
4535A non-system directory may be used instead of \filename{/usr/local}.
4536To use the old version, a source file must \code{include} the
4537appropriate header file (which is identified by its version number).
4538To compile, issue a command such as
4539\begin{verbatim}
4540epix --no-defaults -I/usr/local -L/usr/local -lepix-1.0 file.xp
4541\end{verbatim}
4542
4543
4544\section{Programmer's Guide}
4545\label{section-programmers}
4546
4547This section briefly surveys \ePiX's implementation, and is intended
4548for (potential) programmers. The source code is divided into modules
4549with small, well-defined responsibilities, but the user interface is
4550mostly compatible with the syntax of Version~1.0. These constraints
4551demanded a degree of implementation hiding. For example, the
4552user-visible classes defined in \filename{Color.h}, \filename{path.h},
4553and~\filename{screen.h} contain only a pointer to the implementation
4554class, and style data is hidden behind global commands.
4555
4556Functionally, the code consists of the user interface; implementation
4557class\-es comprising drawing attributes, spatial objects, screens and
4558representations of their elements, and output; and miscellaneous
4559utility functions. The headers in each group, and their contents, are
4560described in Section~\ref{section-interface}.
4561
4562The user interface headers are assembled into a single file,
4563\filename{epix.h}, and installed in \filename{/usr/local/include} by
4564default. In normal use, the shell scripts read only the user interface
4565header.  The individual headers, including the components of
4566\filename{epix.h}, are installed in
4567\filename{/usr/local/include/epix}. These are provided for authors of
4568external libraries, who may need access to implementation details.
4569
4570
4571\subsection{External Packages}
4572
4573\ePiX\ harnesses the computational power of~\CXX\ to the typographical
4574capabilities of \LaTeX. Consequently, \ePiX\ should be viewed in part
4575as a framework for expressing numerical data visually.
4576
4577In the course of your work, you may develop specialized code filling a
4578gap in \ePiX's functionality. If your code seems likely to be of
4579interest to other users, please consider bundling it as an external
4580package and notifying the \ePiX\ community so your work can be linked
4581from the project pages and distributed to interested users.
4582
4583There are no formal requirements for external packages, but in the
4584interest of uniformity contributed code should follow the GNU Coding
4585Standards~\cite{GNUCoding}. At a minimum, an external package should
4586build with the standard \code{./configure; make; make install}
4587commands, and the \code{configure} script should accept an option
4588\code{--with-epix} for the user to specify a non-default \ePiX\
4589install directory.
4590
4591If an external package builds a static library, it should provide a
4592single header containing all the package's entry points, and enclose
4593its interface in a namespace. Entry points should not collide with
4594\ePiX\ functions. Naming the package ``\filename{epix-<...>}'' is a
4595good idea, but not essential. For example, a package providing textual
4596nodes and diagram layout might be named \filename{epix-nodes}.  Input
4597files would use the package with the lines
4598\begin{verbatim}
4599  #include "epix-nodes.h"
4600  using namespace ePiX-nodes;
4601\end{verbatim}
4602and be compiled with
4603\begin{verbatim}
4604  epix -lepix-nodes <file>
4605\end{verbatim}
4606
4607The user and internal interfaces of \ePiX-1.2 are not likely to
4608change. Still, it's prudent to rely only on the user interface in
4609contributed code whenever possible. Doing so also simplifies your work
4610as an author; your library can simply \code{include} the user header
4611file, and deal only with high-level objects and drawing attributes.
4612
4613
4614\subsection{User Interface}
4615\label{section-interface}
4616
4617\index{Header file listing|(}
4618These files (in order) comprise the global header \filename{epix.h}.
4619
4620\Header{enums.h} Marker, alignment, Riemann integral, and vector field
4621types.
4622
4623\Header{length.h} Physical lengths, conceptually a number and
4624two-letter \LaTeX\ length unit.
4625
4626\Header{interval.h} Closed, open, and half-open interval ranges for
4627data culling.
4628
4629\Header{triples.h} The \code{P} class.
4630
4631\Header{Complex.h} The \code{Complex} class.
4632
4633\Header{functions.h} Angle-sensitive trig functions, miscellaneous
4634utility functions, the \code{Deriv}~and \code{Integral} classes.
4635
4636\Header{pairs.h} Screen locations and displacements, with complex
4637arithmetic operations.
4638
4639\Header{Color.h} The Color class interface, named
4640primaries and constructors.
4641
4642\Header{state.h} Angle mode; clipping and cropping; label styles;
4643filling; arrow head style; dot and tick sizes, dash length; line
4644style; line and base pen attributes; color-setting commands.
4645
4646\Header{frame.h} Orthonormal bases.
4647
4648\Header{domain.h} Coordinate boxes for function plotting.
4649
4650\Header{camera.h} The camera.
4651
4652\Header{screen.h} The screen class.
4653
4654\Header{picture.h} Dimension-setting, offset, layout, decoration,
4655verbatim text, and output format commands.
4656
4657\Header{markers.h} Point markers, axis labels, and coordinate axes.
4658
4659\Header{axis.h} Coordinate axes and labels in various styles.
4660
4661\Header{legend.h} Plot legends.
4662
4663\Header{path.h} The path class.
4664
4665\Header{curves.h} Polygons, arrows, ellipses, arcs, splines,
4666coordinate grids, and recursive fractal curves.
4667
4668\Header{circle.h} The \code{Circle} shape object class.
4669
4670\Header{plane.h} The \code{Plane} shape object class.
4671
4672\Header{segment.h} The \code{Segment} shape object class.
4673
4674\Header{sphere.h} The \code{Sphere} shape object class.
4675
4676\Header{intersections.h} Shape object intersection operators.
4677
4678\Header{plots.h} Plotting commands.
4679
4680\Header{surface.h} Shaded surface plots.
4681
4682\Header{data\_mask.h} Helper class for data pruning.
4683
4684\Header{data\_file.h} Class for storing and representing data.
4685
4686\Header{data\_bins.h} Class for sorting and counting data.
4687
4688\Header{geometry.h} Latitudes and longitudes; spherical plotting,
4689arcs, polygons, and polyhedra; hyperbolic arcs.
4690
4691\Header{Sline.h} The \code{Sline} (spherical line) class.
4692
4693
4694\subsection{Implementation Classes}
4695
4696\Header{Color\_Base.h} The Color implementation interface.
4697
4698\Header{Color\_CMY.h} The CMY color model.
4699
4700\Header{Color\_CMYK.h} The CMYK color model.
4701
4702\Header{Color\_Gray.h} The Gray color model.
4703
4704\Header{Color\_Neutral.h} Each color class has a ``Neutral'' member
4705that converts colors to that model by filtering. This file defines the
4706unique ``model-less'' Neutral color for which filtering performs no
4707action.
4708
4709\Header{Color\_RGB.h} The RGB color model.
4710
4711\Header{Color\_Sep.h} Classes for CMYK separation.
4712
4713\Header{active\_screen.h} Simple manipulator for the active screen.
4714
4715\Header{picture\_data.h} Picture implementation: two \code{screen}s
4716(representing the \code{canvas}~and the output page), true dimensions
4717and offsets, pointer to output format, list of colors, and lists of
4718verbatim text to write before and after printing the \code{picture}
4719environment in the output file. For simplicity, the \code{screen}s and
4720dimensions are public; encapsulation from the user results from
4721``hiding'' this header.
4722
4723
4724\subsubsection*{Style Attributes}
4725
4726Declaration-style attributes are maintained with functions returning
4727static references: \code{the\_angle\_style()},
4728\code{the\_arrowhead\_style()}, \code{the\_label\_style()},
4729\code{the\_mark\_size()}, \code{the\_paint\_style()}, and
4730\code{the\_path\_style()}. Each function is declared in the
4731analogously-named header.
4732
4733\Header{angle\_units.h} Angular modes: \code{radians},
4734\code{revolutions}, and \code{degrees}.
4735
4736\Header{arrow\_style.h} Arrow head style data: width, ratio, and
4737inset.
4738
4739\Header{label\_style.h} Text object style: Label and mask colors,
4740padding, border color and width, alignment, font size, font face, and
4741angle.
4742
4743\Header{marker\_style.h} Dot and tick sizes.
4744
4745\Header{paint\_style.h} Line and base pens, fill color.
4746
4747\Header{path\_style.h} Solid, dashed, dotted lines.
4748
4749\Header{pen\_data.h} The pen class.
4750
4751
4752\subsubsection*{Objects}
4753
4754\Header{arrow\_data.h} Arrow representation.
4755
4756\Header{facet.h} Shaded surface elements.
4757
4758\Header{label\_data.h} Text (label and marker) objects.
4759
4760\Header{legend\_item.h} Items for \code{legend}s.
4761
4762\Header{path\_data.h} Path implementation.
4763
4764\Header{spline.h} The natural spline class.
4765
4766\Header{spline\_data.h} Templates for quadratic and cubic splines.
4767
4768
4769\subsubsection*{Screen Representation}
4770
4771Elements in a \code{screen} are represented polymorphically as
4772``\code{tile}s'', of which there are six types: \code{glyph} (textual
4773elements), \code{pen\_arrow} (arrows), \code{pen\_fill} (filled
4774regions), \code{pen\_line} (path-like elements), \code{verbatim}
4775(raw text), and \code{legend\_tile} (legends).
4776
4777Border and background shape are dictated by the \code{screen\_mask}
4778class. The cropping algorithm assumes the contour of a screen mask is
4779convex.
4780
4781\Header{affine.h} Affine maps.
4782
4783\Header{cropping.h} Screen mask cropping.
4784
4785\Header{glyph.h} Markers and labels.
4786
4787\Header{legend\_tile.h} Screen representation of a \code{legend}.
4788
4789\Header{mask\_diamond.h} Screen diamond mask.
4790
4791\Header{mask\_ellipse.h} Screen elliptical mask.
4792
4793\Header{mask\_rectangle.h} Screen rectangular mask.
4794
4795\Header{pen\_arrow.h} Arrows.
4796
4797\Header{pen\_fill.h} Filled regions.
4798
4799\Header{pen\_line.h} Paths.
4800
4801\Header{screen\_data.h} Screen implementation class.
4802
4803\Header{screen\_mask.h} Screen mask interface.
4804
4805\Header{tile.h} Screen element interface.
4806
4807\Header{verbatim.h} Text in output stream.
4808
4809
4810\subsubsection*{Output}
4811
4812Output is divided into a couple of high-level operations and several
4813``atomic'' low-level operations.  To create a new output
4814format, one need only implement the \code{format} interface for the
4815desired file type. Paths and filled regions may be implemented however
4816the output type dictates.
4817
4818\Header{eepic.h} eepic macros.
4819
4820\Header{fmt\_template.h} ``skeleton'' header for new output formats.
4821
4822\Header{format.h} The output interface.
4823
4824\Header{pst.h} PSTricks macros.
4825
4826\Header{tikz.h} tikz macros.
4827
4828
4829\subsubsection*{Utilities}
4830
4831\Header{Color\_Utils.h} Functions for setting color channel densities.
4832
4833\Header{clipping.h} The clip box.
4834
4835\Header{constants.h} Global constants: Line widths; dot, tick, and
4836dash sizes; arrowhead parameters; miscellaneous numerical constants
4837and internal parameters.
4838
4839\Header{crop\_algorithms.h} Path and loop clipping templates.
4840
4841\Header{deriv.h} Finite difference template.
4842
4843\Header{edge\_data.h} Path element representation template.
4844
4845\Header{errors.h} Warning and error messages.
4846
4847\Header{frac.h} Rational numbers and operators.
4848
4849\Header{halfspace.h} Halfspace cutting.
4850
4851\Header{hatching.h} Filling regions in eepic.
4852
4853\Header{lens.h} Camera lenses.
4854
4855\Header{map.h} Wrappers for templated plotting.
4856
4857\Header{plot\_algorithms.h} Plotting templates.
4858
4859\Header{screen\_crop.h} Crop paths and loops.
4860
4861\Header{utils.h} Truncation, date and time, line breaking.
4862\index{Header file listing|)}
4863
4864
4865\appendix
4866\texinfoappendix{A}{Software Freedom}
4867\index{Free software|(}
4868
4869Academics in general, and mathematicians in particular, depend on free
4870exchange of information. We prove theorems or establish experimental
4871results, write up formal accounts, place preprints on public file
4872servers, and submit papers to peer-reviewed journals. If accepted, the
4873results---data, techniques, methods of reasoning, citations, and
4874conclusions---are published in print and become part of the public
4875record, governed by copyright law. Libraries purchase journal
4876subscriptions, but researchers and scholars may use ideas from the
4877literature merely by giving appropriate citations in their own
4878work. ``Theft'' arises from false claims of authorship.
4879
4880Carried over to software, the academic process would guarantee rights
4881similar to those provided by the GNU General Public License (GPL):
4882
4883\begin{itemize}
4884
4885\item (GPL~0) To run a program for any purpose.
4886
4887\item (GPL~1) To study how the program works, and adapt it to your
4888  needs.
4889
4890\item (GPL~2) To redistribute copies of the program.
4891
4892\item (GPL~3) To improve the program, and release improvements to the
4893  public, so that the whole community benefits.
4894
4895\end{itemize}
4896
4897In reality, attitudes toward software differ markedly. Most academics
4898work on a proprietary platform, use proprietary software for research
4899and teaching, and share information with colleagues and students in
4900proprietary, even obfuscated, data formats.  Contrary to the academic
4901ethic, proprietary software licenses restrict access to information:
4902preventing users from learning how a program works internally
4903(``reverse engineering''), limiting the number of users who may run a
4904piece of software, and forbidding users from running (or sometimes
4905even installing) a purchased copy on multiple machines.
4906
4907Restrictions on use aside, if one cannot examine a program's source
4908code, one cannot fully trust the output, any more than one can trust
4909(for purposes of scientific publication) results of a commercial
4910testing lab.
4911
4912\texicomment
4913\noindent$\phantom{.}$\hfil\vbox{\hrule width 4in}\hfil
4914\texicommentend
4915
4916Consider a hypothetical future world in which scholarly results are
4917disseminated like software. Instead of subscriptions, journals
4918sell licenses granting readership to a specified number of
4919individuals. Photocopying an article for a class or research seminar
4920constitutes ``piracy'', though if the institution has purchased a
4921sufficiently large site license the teacher or speaker may bring the
4922physical volume to class and project the pages onto a screen.
4923
4924Of course, reading an article is scarcely enlightening. Mathematics
4925papers contain only the statements of theorems. Merely opening the
4926journal binds the reader to a lengthy legal agreement, stating that
4927theorems be used only for specific purposes and threatening serious
4928legal consequences for attempting to discover the author's proofs.
4929
4930The actions of a single student, employee, or faculty member can
4931expose an institution to a costly ``journal audit'' from the
4932Mathematical Society of America (MSA), with the institution
4933responsible for legal costs if the audit reveals license violations
4934anywhere in the organization.
4935
4936Mathematicians who long for the Old Days when papers contained
4937proofs and were shared freely are dismissed as idealistic cranks
4938or labeled anti-business communists. Common knowledge asserts the
4939obvious superiority of proprietary journals, and the necessity of
4940licenses for keeping mathematicians gainfully employed.
4941
4942\texicomment
4943\noindent$\phantom{.}$\hfil\vbox{\hrule width 4in}\hfil
4944\texicommentend
4945
4946Back in our world, some vendors have attempted to placate opponents of
4947closed source with ``shared source'' licenses, under which one may
4948sign a non-disclosure agreement and subsequently examine source
4949code. In the future world analogy, a shared source agreement would
4950allow journal licensees to sign an NDA, then see the proofs of
4951theorems. Readers could thereby correct errors in proofs (benefitting
4952the publisher by improving the reliability of the journal), but would
4953be legally forbidden from using the ideas elsewhere (denying benefit
4954to other mathematicians).
4955
4956Legally and conceptually codifying software as a commodity ignores a
4957fundamental reality: Like an idea or recipe, software can be copied
4958without loss of the original. The perception of ``theft'' by copying
4959arises from an artificial belief that software has an owner who must
4960be monetarily compensated each time a person acquires a copy.  The
4961nature of software does not enforce the ``sale'' model in the way
4962services and physical commodities do. It therefore seems
4963philosophically inappropriate to treat software as a commodity, and
4964perilous to conform the legal system to the enforcement of such a
4965model.
4966
4967At its best, software enhances our productivity and
4968creativity. Sharing software, like sharing ideas, benefits a larger
4969number of people without detriment to existing users.  I hope this
4970modest program is, in conjunction with the much larger efforts of
4971others (especially Donald Knuth, Richard Stallman, and the many people
4972who have contributed to the authorship of \LaTeX\ and its packages),
4973useful to you in your mathematical work.
4974
4975Please visit the Free Software Foundation, at
4976\URL{www.fsf.org}, to learn more about free software and how
4977you can contribute to its development and adoption.
4978\index{Free software|)}
4979
4980\texinfoappendix{B}{Acknowledgments}
4981
4982\ePiX\ is built on the work of many people, many of whom I am
4983unaware. The following people have contributed, sometimes unknowingly
4984but always generously:
4985
4986\paragraph{Infrastructure} Donald Knuth, Conrad Kwok, Leslie Lamport,
4987Tim Morgan, Piet van~Oostrum, Sunil Podar, Richard Stallman, Till
4988Tantau, Herbert Vo\ss, Timothy van~Zandt
4989
4990\paragraph{Enhancements} Jay Belanger, Robin Blume-Kohout, Julian
4991Gilbey, Marcus Hanwell, Yvon Henel, Svend Daug{\aa}rd Pedersen, Andrew
4992Sterian
4993
4994\paragraph{Porting and packaging} Youn\`es Hafri (Crux), Julian Gilbey
4995(Debian); Tsuguru Kato (FreeBSD); Markus Dittrich, Danny van Dyk,
4996Christian Faulhammer, Olivier Fisette, Chris Gianelloni, Michael
4997Hanselmann, Marcus Hanwell, David Holm, Peter Johanson, Patrick
4998Kursawe, Tobias Scherbaum, Markus Ullmann (Gentoo); Guido Gonzato
4999(RPM); Rene Rebe (T2)
5000
5001\paragraph{Debugging, advice, and other assistance} Maik Beckmann, Jay
5002Belanger, Felipe Paulo Guazzi Bergo, Karl Berry, Robin Blume-Kohout,
5003Aran Clauson, Patrick Cousot, Stephen Gibson, Julian Gilbey, Dov
5004Grobgeld, Bob Grover, Jim Hefferon, Jacques L'helgoualc'h, Yvon Henel,
5005Hartmut Henkel, Herng-Jeng Jou, Walter Kehowski, Paul Kornman, Kevin
5006McCormick, Ross Moore, Mike Protts, Thorsten Riess, Jean-Michel
5007Sarlat, Alan Sill, Neel Smith, Michael Somos, Andrew Sterian, Ryszard
5008Tanas, Ben Tillman, Kai Trukenmueller, Torbjorn Vik, Wenguang Wang,
5009Gabe Weaver, Mariusz Wodzicki
5010
5011\texicomment
5012\begin{thebibliography}{9}
5013%
5014\bibitem{Cline} Marshall Cline, \emph{\CXX\ FAQ Lite}, \\
5015  \URL{http://www.parashift.com/c++-faq-lite/}
5016%
5017\bibitem{xcolor} Uwe Kern, \emph{Extending \LaTeX's color facilities:
5018  the \code{xcolor} package}, white paper, Jan.~21, 2007
5019%
5020\bibitem{KnR} Brian Kernighan and Dennis Ritchie, \emph{The \code{C}
5021    Programming Language}, Second Ed., Prentice-Hall Software Series,
5022    1988
5023%
5024\bibitem{GNUC} Sandra Loosemore, Richard M. Stallman, et.\ al.,
5025    \emph{The GNU \code{C}~Library Reference Manual}, GNU Press,
5026    2004
5027%
5028\bibitem{Prata} Stephen Prata, \emph{\CXX\ Primer Plus}, Sams, 2002
5029%
5030\bibitem{R} Keith Reckdahl, \emph{Using Imported Graphics in
5031  \LaTeX2e}, Version~2.0, white paper, Dec.~15, 1997
5032%
5033\bibitem{GNUCoding} Richard M. Stallman, et.\ al., \emph{The GNU
5034  Coding Standards}, \\
5035  \URL{http://www.gnu.org/prep/standards/}
5036%
5037\bibitem{S} Bjarne Stroustrup, \emph{The \CXX\ Programming Language},
5038  Special Ed., Addison-Wesley, 1997
5039%
5040\bibitem{Z} Timothy van~Zandt, \emph{PSTricks: PostScript Macros for
5041  Generic \TeX}, Version~0.93a, white paper, Mar.~12, 1993
5042%
5043\end{thebibliography}
5044
5045%\clearpage
5046
5047%\printindex[xfcns]
5048
5049\printindex
5050
5051\end{document}
5052
5053\texicommentend
5054