## 3.3 Composing diagrams

The `diagrams`

framework is fundamentally *compositional*: complex
diagrams are created by combining simpler diagrams in various ways.
Many of the combination methods discussed in this section are defined
in `Diagrams.Combinators`

.

### Superimposing diagrams with `atop`

The most fundamental way to combine two diagrams is to place one on
top of the other with `atop`

. The diagram `d1 `atop` d2`

is formed
by placing `d1`

's local origin on top of `d2`

's local origin; that is,
by identifying their local vector spaces.

As noted before, diagrams form a monoid with composition given by
superposition. `atop`

is simply a synonym for `mappend`

(or `(<>)`

),
specialized to two dimensions.

This also means that a list of diagrams can be stacked with `mconcat`

;
that is, `mconcat [d1, d2, d3, ...]`

is the diagram with `d1`

on top
of `d2`

on top of `d3`

on top of...

### Juxtaposing diagrams

Fundamentally, `atop`

is actually the *only* way to compose diagrams;
however, there are a number of other combining methods (all ultimately
implemented in terms of `atop`

) provided for convenience.

Two diagrams can be placed *next to* each other using `beside`

. The
first argument to `beside`

is a vector specifying a direction. The
second and third arguments are diagrams, which are placed next to each
other so that the vector points from the first diagram to the second.

As can be seen from the above example, the *length* of the vector
makes no difference, only its *direction* is taken into account. (To
place diagrams at a certain fixed distance from each other, see
`cat'`

.) As can also be seen, the local origin of the new, combined
diagram is the same as the local origin of the first diagram. This
makes `beside v`

associative, so diagrams under `beside v`

form a
semigroup. In fact, they form a monoid, since `mempty`

is a left and
right identity for `beside v`

, as can be seen in the example below:

In older versions of `diagrams`

, the local origin of the combined
diagram was at the point of tangency between the two diagrams. To
recover the old behavior, simply perform an alignment on the first
diagram in the same direction as the argument to `beside`

before
combining (see Alignment):

If you want to place two diagrams next to each other using the local
origin of the *second* diagram, you can use something like ```
beside' =
flip . beside . negateV
```

, that is, use a vector in the opposite
direction and give the diagrams in the other order.

Since placing diagrams next to one another horizontally and vertically
is quite common, special combinators are provided for convenience.
`(|||)`

and `(===)`

are specializations of `beside`

which juxtapose
diagrams in the \(x\)- and \(y\)-directions, respectively.

### Juxtaposing without composing

Sometimes, one may wish to *position* a diagram next to another
diagram without actually composing them. This can be accomplished
with the `juxtapose`

function. In particular, `juxtapose v d1 d2`

returns a modified version of `d2`

which has been translated to be
next to `d1`

in the direction of `v`

. (In fact, `beside`

itself is
implemented as a call to `juxtapose`

followed by a call to `(<>)`

.)

See envelopes and local vector spaces for more information on what
"next to" means, and Envelopes for information on
functions available for manipulating envelopes. To learn about how
envelopes are implemented, see the core library reference.

### Concatenating diagrams

We have already seen one way to combine a list of diagrams, using
`mconcat`

to stack them. Several other methods for combining lists of
diagrams are also provided in `Diagrams.Combinators`

.

The simplest method of combining multiple diagrams is `position`

,
which takes a list of diagrams paired with points, and places the
local origin of each diagram at the indicated point.

`cat`

is an iterated version of `beside`

, which takes a direction
vector and a list of diagrams, laying out the diagrams beside one
another in a row. The local origins of the subdiagrams will be placed
along a straight line in the direction of the given vector, and the
local origin of the first diagram in the list will be used as the
local origin of the final result.

Semantically, `cat v === foldr (beside v) mempty`

, although the actual
implementation of `cat`

uses a more efficient balanced fold.

For more control over the way in which the diagrams are laid out, use
`cat'`

, a variant of `cat`

which also takes a `CatOpts`

record. See
the documentation for `cat'`

and `CatOpts`

to learn about the various
possibilities.

For convenience, `Diagrams.TwoD.Combinators`

also provides `hcat`

, `hcat'`

,
`vcat`

, and `vcat'`

, variants of `cat`

and `cat'`

which concatenate
diagrams horizontally and vertically.

Finally, `appends`

is like an iterated variant of `beside`

, with the
important difference that multiple diagrams are placed next to a
single central diagram without reference to one another; simply
iterating `beside`

causes each of the previously appended diagrams to
be taken into account when deciding where to place the next one. Of
course, `appends`

is implemented in terms of `juxtapose`

(see
Juxtaposing without composing).

```
> c = circle 1
> dirs = iterate (rotateBy (1/7)) unitX
> cdirs = zip dirs (replicate 7 c)
> example1 = appends c cdirs
> example2 = foldl (\a (v,b) -> beside v a b) c cdirs
> example = example1 ||| strutX 3 ||| example2
```

`Diagrams.Combinators`

also provides `decoratePath`

and
`decorateTrail`

, which are described in Decorating trails and
paths.

## 3.4 Modifying diagrams

### Attributes and styles

Every diagram has a *style* which is an arbitrary collection of
*attributes*. This section will describe some of the default
attributes which are provided by the `diagrams`

library and
recognized by most backends. However, you can easily create your own
attributes as well; for details, see the core library reference.

In many examples, you will see attributes applied to diagrams using
the `(#)`

operator. Keep in mind that there is nothing special about
this operator as far as attributes are concerned. It is merely
backwards function application, which is used for attributes since it
often reads better to have the main diagram come first, followed by
modifications to its attributes. See Postfix transformation.

In general, inner attributes (that is, attributes applied earlier)
override outer ones. Note, however, that this is not a requirement.
Each attribute may define its own specific method for combining
multiple values. Again, see the core library reference for more
details.

Most of the attributes discussed in this section are defined in
`Diagrams.TwoD.Attributes`

.

### Texture

Two-dimensional diagrams can be filled and stroked with a `Texture`

. A
`Texture`

can be either a solid color, a linear gradient or a radial
gradient. Not all backends support gradients, in particular gradients are
supported by the SVG, Cairo, and Rasterific backends (see Rendering backends).
Future releases should also support patterns as textures. The data type
for a texture is

and `Prism`

s `_SC`

, `_LG`

, `_RG`

are provided for access.

#### Color

The color used to stroke the paths can be set with the `lc`

(line color)
function and the color used to fill them with the `fc`

(fill color) function.

By default, diagrams use a black line color and a completely
transparent fill color.

Colors themselves are handled by the `colour`

package, which
provides a large set of predefined color names as well as many more
sophisticated color operations; see its documentation for more
information. The `colour`

package uses a different type for
colors with an alpha channel (*i.e.* transparency). To make use of
transparent colors you can use `lcA`

and `fcA`

. The `palette`

::pkg: package
provides additional sets of colors and algorithms for creating harmonious
color combinations.

Transparency can also be tweaked with the `Opacity`

attribute, which
sets the opacity/transparency of a diagram as a whole. Applying
`opacity p`

to a diagram, where `p`

is a value between `0`

and `1`

,
results in a diagram `p`

times as opaque.

To "set the background color" of a diagram, use the `bg`

function—which does not actually set any attributes, but simply
superimposes the diagram on top of a bounding rectangle of the given
color.

#### Linear Gradients

A linear gradient must have a list of color stops, a starting point, an ending point,
a transformation and a spread method. Color stops are pairs of (color, fraction) where
the fraction is usually between 0 and 1 that are mapped onto the start and end
points. The starting point and endping point are
specified in local coordinates. Typically the transformation starts as the identity
transform `mempty`

and records any transformations that are applied to the object
using the gradient. The spread method defines how space beyond the starting and
ending points should be handled, `GradPad`

will fill the space with the final stop
color, `GradRepeat`

will restart the gradient, and `GradReflect`

will restart the
gradient but with the stops reversed. This is the data type for a linear gradient.

Lenses are provided to access the record fields. In addition the functions `mkStops`

taking
a list of triples (color, fraction, opacity) and `mkLinearGradient`

which takes a list of stops,
a start and end point, and a spread method and creates a `Texture`

are provided for convenience.
In this example we demonstrate how to make linear gradients with the `mkLinearGradient`

functions and how to adjust it using the lenses and prisms.

```
> stops = mkStops [(gray, 0, 1), (white, 0.5, 1), (purple, 1, 1)]
> gradient = mkLinearGradient stops ((-0.5) ^& 0) (0.5 ^& 0) GradPad
> sq1 = square 1 # fillTexture gradient
> sq2 = square 1 # fillTexture (gradient & _LG . lGradSpreadMethod .~ GradRepeat
> & _LG . lGradStart .~ (-0.1) ^& 0
> & _LG . lGradEnd .~ 0.1 ^& 0)
> sq3 = square 1 # fillTexture (gradient & _LG . lGradSpreadMethod .~ GradReflect
> & _LG . lGradStart .~ (-0.1) ^& 0
> & _LG . lGradEnd .~ 0.1 ^& 0)
>
> example = hcat' (with & sep .~ 0.25) [sq1, sq2, sq3]
```

Here we apply the gradient to the stroke only and give it starting and
ending points towards the corners.

#### Radial Gradients

Radial gradients are similar, only they begin at the perimeter of an inner cirlce and
end at the perimeter of an outer circle.

Where radius and center 0 are for the inner circle, and 1 for the outer circle.
In this example we place the inner circle off center and place a circle filled
with the radial gradient on top of a rectangle filled with a linear gradient
to create a 3D effect.

```
> radial = mkRadialGradient (mkStops [(white,0,1), (black,1,1)])
> ((-0.15) ^& (0.15)) 0.06 (0 ^& 0) 0.5
> GradPad
>
> linear = mkLinearGradient (mkStops [(black,0,1), (white,1,1)])
> (0 ^& (-0.5)) (0 ^& 0.5)
> GradPad
>
> example = circle 0.35 # fillTexture radial # lw none
> <> rect 2 1 # fillTexture linear # lw none
```

#### Line width

Line width is actually more subtle than you might think. Suppose you
create a diagram consisting of a square, and another square twice as
large next to it (using `scale 2`

). How should they be drawn? Should
the lines be the same width, or should the larger square use a line
twice as thick? (Note that similar questions also come up when
considering the dashing style used to draw some shapes—should the
size of the dashes scale with transformations applied to the shapes,
or not?) `diagrams`

allows the user to decide, using `Measure R2`

values to specify things like line width (see Measurement units).

In many situations, it is desirable to have lines drawn in a uniform
way, regardless of any scaling applied to shapes. This is what
happens with line widths measured in `Global`

, `Normalized`

or
`Output`

units, as in the following example:

For line widths that scale along with a diagram, use `Local`

; in this
case line widths will be scaled in proportion to the geometeric
average of the scaling transformatins applied to the diagram.

The `LineWidth`

attribute is used to alter the *width* with which
paths are stroked. The most general functions that can be used to set
the line width are `lineWidth`

and its synonym `lw`

, which take an
argument of type `Measure R2`

. Since typing things like ```
lineWidth
(Normalized 0.01)
```

is cumbersome, there are also shortcuts provided:
`lwG`

, `lwN`

, `lwO`

, and `lwL`

all take an argument of type `Double`

and wrap it in `Global`

, `Normalized`

, `Ouput`

and `Local`

,
respectively.

There are also predefined `Measure R2`

values with intuitive names,
namely, `ultraThin`

, `veryThin`

, `thin`

, `medium`

, `thick`

,
`veryThick`

, `ultraThick`

, and `none`

(the default is `medium`

), which
should often suffice for setting the line width.

```
> line = strokeT . fromOffsets $ [unitX]
> example = vcat' (with & sep .~ 0.1)
> [line # lw w | w <- [ultraThin, veryThin, thin,
> medium, thick, veryThick, ultraThick]]
```

In the above example, there is no discernible difference between
`ultraThin`

, `veryThin`

, and `thin`

; these names all describe
`Normalized`

measurements with a physical lower bound, so the physical
width of the resulting lines depends on the physical size of the
rendered diagram. At larger rendering sizes the differences between
the smaller widths become apparent.

Explain that they all have a minimum output size. Should wait until
we have a better idea what the heck output size actually means.

Note that line width does not affect the envelope of diagrams at all.
To stroke a line "internally", turning it into a `Path`

value
enclosing the stroked area (which *does* contribute to the envelope),
you can use one of the functions described in the section Offsets of
segments, trails, and paths.

#### Other line parameters

Many rendering backends provide some control over the particular way
in which lines are drawn. Currently, `diagrams`

provides support
for three aspects of line drawing:

```
> path = fromVertices (map p2 [(0,0), (1,0.3), (2,0), (2.2,0.3)]) # lwO 10
> example = center . vcat' (with & sep .~ 0.1 )
> $ map (path #)
> [ lineCap LineCapButt . lineJoin LineJoinMiter
> , lineCap LineCapRound . lineJoin LineJoinRound
> , lineCap LineCapSquare . lineJoin LineJoinBevel
> , dashingN [0.03,0.06,0.09,0.03] 0
> ]
```

#### The `HasStyle`

class

Functions such as `fc`

, `lc`

, `lw`

, and `lineCap`

do not take only
diagrams as arguments. They take any type which is an instance of the
`HasStyle`

type class. Of course, diagrams themselves are an
instance.

However, the `Style`

type is also an instance. This is useful in
writing functions which offer the caller flexible control over the
style of generated diagrams. The general pattern is to take a `Style`

(or several) as an argument, then apply it to a diagram along with
some default attributes:

This way, any attributes provided by the user in the `style`

argument
will override the default attributes specified afterwards.

To call `myFun`

, a user can construct a `Style`

by starting with an
empty style (`mempty`

, since `Style`

is an instance of `Monoid`

) and
applying the desired attributes:

If the type `T`

is an instance of `HasStyle`

, then `[T]`

is also.
This means that you can apply styles uniformly to entire lists of
diagrams at once, which occasionally comes in handy, for example, to
assign a default attribute to all diagrams in a list which do not
already have one:

Likewise, there are `HasStyle`

instances for pairs, `Map`

s, `Set`

s,
and functions.

### Static attributes

Diagrams can also have "static attributes" which are applied at a
specific node in the tree representing a diagram. Currently, the only
static attribute is a hyperlink, which is supported only by the SVG
backend. To turn a diagram into a hyperlink, use the `href`

function.

More static attributes (for example, node IDs and transparency
grouping) and wider backend support will be added in future versions.

### 2D Transformations

Any diagram can be transformed by applying arbitrary affine
transformations to it. *Affine* transformations include *linear*
transformations (rotation, scaling, reflection, shears—anything
which leaves the origin fixed and sends lines to lines) as well as
translations. In the simplified case of the real line, an affine
transformation is any function of the form \(f(x) = mx + b\).
Generalizing to \(d\) dimensions, an affine transformation is a
vector function of the form \(f(\mathbf{v}) = \mathbf{M}\mathbf{v} +
\mathbf{B}\), where \(\mathbf{M}\) and \(\mathbf{B}\) are
\(d \times d\) matrices. More general, non-affine
transformations, including projective transformations, are referred to
in `diagrams`

as Deformations.

`Diagrams.TwoD.Transform`

defines a number of common affine
transformations in two-dimensional space. (To construct
transformations more directly, see `Diagrams.Core.Transform`

.)

Every transformation comes in two variants, a noun form and a verb
form. For example, there are two functions for scaling along the
\(x\)-axis, `scalingX`

and `scaleX`

. The noun form (*e.g.*
`scalingX`

) constructs a `Transformation`

value, which can then be
stored in a data structure, passed as an argument, combined with other
transformations, *etc.*, and ultimately applied to a diagram (or other
`Transformable`

value) with the `transform`

function. The verb form
directly applies the transformation. The verb form is much more
common (and the documentation below will only discuss verb forms), but
getting one's hands on a first-class `Transformation`

value can
occasionally be useful.

Both the verb and noun variants of transformations are monoids, and
can be composed with `(<>)`

. However, the results are quite distinct,
as shown in this example.

`dia1`

is the intended result: a character L translated along the X axis,
and then rotated 45 degrees around the origin.

`dia2`

shows the result of naively composing the verb versions of
the transformations: a superposition of a rotated L and a
translated L. To understand this, consider that `(rotate alpha)`

is a *function*, and functions as monoid instances (```
Monoid m =>
Monoid (a -> m)
```

) are composed as `(f <> g) x = f x <> g x`

. To
quote the Typeclassopedia: if `a`

is a Monoid, then so is the
function type `e -> a`

for any `e`

; in particular, ```
g `mappend`
h
```

is the function which applies both `g`

and `h`

to its argument
and then combines the results using the underlying Monoid instance
for `a`

.

Hence `ell # ( rotate alpha <> translateX 2 )`

is
the same as the superposition of two diagrams: ```
rotate alpha ell <>
translateX 2 ell
```

.

`dia3`

shows how the noun versions can be composed (using the
`Monoid`

instance for `Transformation`

) with the intended result.

#### Rotation

Use `rotate`

to rotate a diagram counterclockwise by a given angle
about the origin. Since `rotate`

takes an `Angle`

, you must specify an
angle unit, such as `rotate (80 @@ deg)`

. In the common case that you
wish to rotate by an angle specified as a certain fraction of a
circle, like `rotate (1/8 @@ turn)`

, you can use `rotateBy`

instead. `rotateBy`

takes a `Double`

argument expressing the number of
turns, so in this example you would only have to write ```
rotateBy
(1/8)
```

.

You can also use `rotateAbout`

in the case that you want to rotate
about some point other than the origin.

#### Scaling and reflection

Scaling by a given factor is accomplished with `scale`

(which scales
uniformly in all directions), `scaleX`

(which scales along the \(x\)-axis
only), or `scaleY`

(which scales along the \(y\)-axis only). All of these
can be used both for enlarging (with a factor greater than one) and
shrinking (with a factor less than one). Using a negative factor
results in a reflection (in the case of `scaleX`

and `scaleY`

) or a
180-degree rotation (in the case of `scale`

).

Scaling by zero is forbidden. Let us never speak of it again.

For convenience, `reflectX`

and `reflectY`

perform reflection along
the \(x\)- and \(y\)-axes, respectively. Their names can be
confusing (does `reflectX`

reflect *along* the \(x\)-axis or
*across* the \(x\)-axis?) but you can just remember that
`reflectX = scaleX (-1)`

, and similarly for `reflectY`

; that is,
`reflectQ`

affects `Q`

-coordinates.

To reflect in some line other than an axis, use `reflectAbout`

.

#### Conjugation

`Diagrams.Transform`

exports useful transformation utilities
which are not specific to two dimensions. At the moment there are
only two: `conjugate`

and `under`

. The first simply performs
conjugation: `conjugate t1 t2 == inv t1 <> t2 <> t1`

, that is,
performs `t1`

, then `t2`

, then undoes `t1`

.

`under`

performs a transformation using conjugation. It takes as
arguments a function `f`

as well as a transformation to conjugate by,
and produces a function which performs the transformation, then `f`

,
then the inverse of the transformation. For example, scaling by a
factor of 2 along the diagonal line \(y = x\) can be accomplished
thus:

The letter F is first rotated so that the desired scaling axis lies
along the \(x\)-axis; then `scaleX`

is performed; then it is rotated back
to its original position.

Note that `reflectAbout`

and `rotateAbout`

are implemented using
`under`

.

### Deformations

The affine transformations represented by `Transformation`

include the
most commonly used transformations, but occasionally other sorts are
useful. Non-affine transformations are represented by the
`Deformation`

type. The design is quite similar to that of
`Transformation`

. A `Deformation`

is parameterized by the vector space
over which it acts. There is a `Deformable`

type class, and `deform`

applies a `Deformation`

to a `Deformable`

type in the same vector
space, returning a value of the same type.

`Diagrams.TwoD.Deform`

defines parallel and perspective
projections along the principal axes in 2 dimensions.

The example above projects a square onto the plane x=1. In this
example, only the projected vertices are drawn, since the four
overlapping line segments corresponding to the edges of the square are
not interesting. Note, though, that the `Path`

is deformed, and then
the vertices are taken from the projected result.

`Deformation v`

is a `Monoid`

for any vector space `v`

. New
deformations can be formed by composing two deformations. The
composition of an affine transformation with a `Deformation`

is also a
`Deformation`

. `asDeformation`

converts a `Transformation`

to an
equivalent `Deformation`

, "forgetting" the inverse and other extra
information which distinguishes affine transformations.

The very general nature of deformations prevents certain types
from being `Deformable`

. Because not every `Deformation`

is
invertible, diagrams cannot be deformed. In general, for two points
\(p\) and \(q\), and a deformation \(D\), there is no
deformation \(D_v\) such that, \(Dp - Dq = D_v(p-q)\). For
this reason, only points and concretely located types are deformable.
Finally, segments are not deformable because the image of the segment
may not be representable by a single segment. The `Deformable`

instances for trails and paths will approximate each segment by
several segments as necessary. Points, `Located`

trails, and paths
are all deformable.

Because approximation and subdivision are required for many
`Deformable`

instances, the type class provides a function `deform'`

,
which takes the approximation accuracy as its first argument. For
trails and paths, `deform`

(without a prime) calls `deform'`

with an
error limit of 0.01 times the object's size.

### Alignment

Since diagrams are always combined with respect to their local
origins, moving a diagram's local origin affects the way it combines
with others. The position of a diagram's local origin is referred to
as its *alignment*.

The functions `moveOriginBy`

and `moveOriginTo`

are provided for
explicitly moving a diagram's origin, by an absolute amount and to an
absolute location, respectively. `moveOriginBy`

and `translate`

are
actually dual, in the sense that

`moveOriginBy v === translate (negateV v).`

This duality comes about since `translate`

moves a diagram with
respect to its origin, whereas `moveOriginBy`

moves the *origin* with
respect to the *diagram*. Both are provided so that you can use
whichever one corresponds to the most natural point of view in a given
situation, without having to worry about inserting calls to `negateV`

.

Often, however, one wishes to move a diagram's origin with respect to
its "boundary". Here, boundary usually refers to the diagram's
envelope or trace, with envelope being the default (see Envelopes
and Traces for more information). To this end, some general tools
are provided in `Diagrams.Align`

, and specialized 2D-specific
ones by `Diagrams.TwoD.Align`

.

Functions like `alignT`

(align Top) and `alignBR`

(align Bottom Right)
move the local origin to the edge of the envelope:

There are two things to note about the above example. First, notice
how `alignT`

and `alignBR`

move the local origin of the square in the
way you would expect. Second, notice that when placed "next to" each
other using the `(|||)`

operator, the squares are placed so that their
local origins fall on a horizontal line.

Functions like `alignY`

allow finer control over the alignment. In
the below example, the origin is moved to a series of locations
interpolating between the bottom and top of the square:

To center an object along an axis we provide the functions `centerX`

and `centerY`

. An object can be simultaneously centered along both axis
(actually along all of its basis vectors) using the `center`

function.

The align functions have sister functions like `snugL`

and `snugX`

that work the same way as `alignL`

and `alignX`

. The difference is
that the `snug`

class of functions use the trace as the boundary
instead of the envelope. For example, here we want to snug a convex
shape (the orange triangle) next to a concave shape (the blue
polygon):

```
> import Diagrams.TwoD.Align
>
> concave = polygon ( with & polyType .~ PolyPolar [a, b, b, b]
> [ 0.25,1,1,1,1] & polyOrient .~ NoOrient )
> # fc blue # lw none
> where
> a = 1/8 @@ turn
> b = 1/4 @@ turn
>
> convex = polygon (with & polyType .~ PolyPolar [a,b] [0.25, 1, 1]
> & polyOrient .~ NoOrient)
> # fc orange # lw none
> where
> a = 1/8 @@ turn
> b = 3/4 @@ turn
>
> aligned = (concave # center # alignR # showOrigin)
> <> (convex # center # alignL # showOrigin)
>
> snugged = (concave # center # snugR # showOrigin)
> <> (convex # center # snugL # showOrigin)
>
> example = aligned ||| strutX 0.5 ||| snugged
```

The `snugR`

function moves the origin of the blue polygon to the
rightmost edge of its trace in the diagram on the right, whereas in
the left diagram the `alignR`

function puts it at the edge of the
envelope.

## 3.5 Trails and paths

Trails and paths are some of the most fundamental tools in
`diagrams`

. They can be used not only directly to draw things, but
also as guides to help create and position other diagrams.

For additional practice and a more "hands-on" experience learning
about trails and paths, see the trails and paths tutorial.

### Segments

The most basic component of trails and paths is a `Segment`

, which is
some sort of primitive path from one point to another. Segments are
*translationally invariant*; that is, they have no inherent location,
and applying a translation to a segment has no effect (however, other
sorts of transformations, such as rotations and scales, have the
effect you would expect). In other words, a segment is not a way to
get from some particular point A to another point B; it is a way to
get from *wherever you currently happen to be* to *somewhere else*.

Currently, `diagrams`

supports two types of segment, defined in
`Diagrams.Segment`

:

A *linear* segment is simply a straight line, defined by an offset
from its beginning point to its end point; you can construct one
using `straight`

.

A *Bézier* segment is a cubic curve defined by an offset from its
beginning to its end, along with two control points; you can
construct one using `bezier3`

(or `bézier3`

, if you are feeling
snobby). An example is shown below, with the endpoints shown in red
and the control points in blue. Bézier curves always start off
from the beginning point heading towards the first control point,
and end up at the final point heading away from the last control
point. That is, in any drawing of a Bézier curve like the one
below, the curve will be tangent to the two dotted lines.

Independently of the two types of segments explained above, segments
can be either *closed* or *open*. A *closed* segment has a fixed
endpoint relative to its start. An *open* segment, on the other hand,
has an endpoint determined by its context; open segments are used to
implement loops (explained in the Trails section below). Most
users should have no need to work with open segments. (For that
matter, most users will have no need to work directly with segments at
all.)

If you look in the `Diagrams.Segment`

module, you will see quite
a bit of other stuff related to the implementation of trails
(`SegMeasure`

and so on); this is explained in more detail in the
section Trail and path implementation details.

### Trails

Trails are defined in `Diagrams.Trail`

. Informally, you can
think of trails as lists of segments laid end-to-end. Since segments
are translation-invariant, so are trails. More formally, the
semantics of a trail is a continuous (though not necessarily
differentiable) function from the real interval \([0,1]\) to
vectors in some vector space. This section serves as a reference on
trails; for a more hands-on introduction, refer to the Trail and path
tutorial.

There are two types of trail:

A *loop*, with a type like `Trail' Loop v`

, is a trail which forms
a "closed loop", ending at the same place where it started.

Loops in 2D can be filled, as in the example above.

A *line*, with a type like `Trail' Line v`

, is a trail which does
not form a closed loop, that is, it starts in one place and ends
in another.

Actually, a line can in fact happen to end in the same place where
it starts, but even so it is still not considered closed. Lines
have no inside and outside, and are never filled.

Lines are never filled, even when they happen to start and end in
the same place!

Finally, the type `Trail`

can contain either a line or a loop.

The most important thing to understand about lines, loops, and trails
is how to convert between them.

To convert from a line or a loop to a trail, use `wrapLine`

or
`wrapLoop`

(or `wrapTrail`

, if you don't know or care whether the
parameter is a line or loop).

To convert from a loop to a line, use `cutLoop`

. This results in a
line which just so happens to end where it starts.

To convert from a line to a loop, there are two choices:

`closeLine`

adds a new linear segment from the end to the start of
the line.

`glueLine`

simply modifies the endpoint of the final segment to be
the start of the line. This is most often useful if you have a
line which you know just so happens to end where it starts;
calling `closeLine`

in such a case would result in the addition of
a gratuitous length-zero segment.

Lines form a monoid under concatenation. For example, below we create
a two-segment line called `spoke`

and then construct a starburst
path by concatenating a number of rotated copies. Note how we call
`glueLine`

to turn the starburst into a closed loop, so that we can
fill it (lines cannot be filled). `strokeLoop`

turns a loop into a
diagram, with the start of the loop at the local origin. (There are
also analogous functions `strokeLine`

and `strokeTrail`

.)

For convenience, there is also a monoid instance for `Trail`

based on
the instance for lines: any loops are first cut with `cutLine`

, and
the results concatenated. Typically this would be used in a situation
where you know that all your trails actually contain lines.

Loops, on the other hand, have no monoid instance.

To construct a line, loop, or trail, you can use one of the following:

`fromOffsets`

takes a list of vectors, and turns each one into a
linear segment.

`fromVertices`

takes a list of vertices, generating linear segments
between them.

`(~~)`

creates a simple linear trail between two points.

`cubicSpline`

creates a smooth curve passing through a given list of
points; it is described in more detail in the section on Splines.

`fromSegments`

takes an explicit list of `Segment`

s, which can
occasionally be useful if, say, you want to generate some Bézier

All the above functions construct loops by first constructing a line
and then calling `glueLine`

(see also the below section on
TrailLike).

If you look at the types of these functions, you will note that they
do not, in fact, return just `Trail`

s: they actually return any type
which is an instance of `TrailLike`

, which includes lines, loops,
`Trail`

s, `Path`

s (to be covered in an upcoming section), `Diagram`

s,
lists of points, and any of these wrapped in `Located`

(see below).
See the TrailLike section for more on the `TrailLike`

class.

For details on other functions provided for manipulating trails, see
the documentation for `Diagrams.Trail`

. One other function worth
mentioning is `explodeTrail`

, which turns each segment in a trail into
its own individual `Path`

. This is useful when you want to construct
a trail but then do different things with its individual segments.
For example, we could construct the same starburst as above but color
the edges individually:

```
> spoke :: Trail R2
> spoke = fromOffsets . map r2 $ [(1,3), (1,-3)]
>
> burst = mconcat . take 13 . iterate (rotateBy (-1/13)) $ spoke
>
> colors = cycle [aqua, orange, deeppink, blueviolet, crimson, darkgreen]
>
> example = lw thick
> . mconcat
> . zipWith lc colors
> . map strokeLocTrail . explodeTrail
> $ burst `at` origin
```

(If we wanted to fill the starburst with yellow as before, we would
have to separately draw another copy of the trail with a line width of
zero and fill that; this is left as an exercise for the reader.)

### Located

Something of type `Located a`

consists, essentially, of a value of
type `a`

paired with a point. In this way, `Located`

serves to
transform translation-invariant things (such as `Segment`

s or
`Trail`

s) into things with a fixed location. A `Located Trail`

is a
`Trail`

where we have picked a concrete location for its starting
point, and so on.

The module `Diagrams.Located`

defines the `Located`

type and
utilities for working with it:

`at`

is used to construct `Located`

values, and is designed to be
used infix, like `someTrail `at` somePoint`

.

`viewLoc`

, `unLoc`

, and `loc`

can be used to project out the
components of a `Located`

value.

`mapLoc`

can be used to apply a function to the value of type `a`

inside a value of type `Located a`

. Note that `Located`

is not a
functor, since it is not possible to change the contained type
arbitrarily: `mapLoc`

does not change the location, and the vector
space associated to the type `a`

must therefore remain the same.

Much of the utility of having a concrete type for the `Located`

concept (rather than just passing around values paired with points)
lies in the type class instances we can give to `Located`

:

`HasOrigin`

: translating a `Located a`

simply translates the
associated point, leaving the value of type `a`

unaffected.

`Transformable`

: only the linear component of transformations are
applied to the wrapped value (whereas the entire transformation is
applied to the location).

`Enveloped`

: the envelope of a `Located a`

is the envelope of the
contained `a`

, translated to the stored location (and similarly for
`Traced`

).

The `TrailLike`

instance is also useful; see TrailLike.

### Paths

A `Path`

, also defined in `Diagrams.Path`

, is a (possibly empty)
collection of `Located Trail`

s. Paths of a single trail can be
constructed using the same functions described in the previous
section: `fromSegments`

, `fromOffsets`

, `fromVertices`

, `(~~)`

, and
`cubicSpline`

.

`Path`

s also form a `Monoid`

, but the binary operation is
*superposition* (just like that of diagrams). Paths with
multiple components can be used, for example, to create shapes with
holes:

See the section on Fill rules for more information.

`stroke`

turns a path into a diagram, just as `strokeTrail`

turns a trail
into a diagram. (In fact, `strokeTrail`

really works by first turning the
trail into a path and then calling `stroke`

on the result.)

`explodePath`

, similar to `explodeTrail`

, turns the segments of a path
into individual paths. Since a path is a collection of trails, each
of which is a sequence of segments, `explodePath`

actually returns a
list of lists of paths.

For information on other path manipulation functions such as
`pathFromTrail`

, `pathFromLocTrail`

, `pathVertices`

, `pathOffsets`

,
`scalePath`

, and `reversePath`

, see the Haddock documentation in
`Diagrams.Path`

.

### Stroking trails and paths

The `strokeTrail`

and `stroke`

functions, which turn trails and paths into
diagrams respectively, have already been mentioned; they are defined
in `Diagrams.TwoD.Path`

. Both also have primed variants,
`strokeTrail'`

and `stroke'`

, which take a record of `StrokeOpts`

.
Currently, `StrokeOpts`

has two fields:

`vertexNames`

takes a list of lists of names, and zips each list
with a component of the path, creating point subdiagrams (using
`pointDiagram`

) associated with the names. This means that the
names can be used to later refer to the locations of the path
vertices (see Named subdiagrams). In the case of `strokeTrail'`

,
only the first list is used.

By default, `vertexNames`

is an empty list.

`queryFillRule`

specifies the fill rule (see Fill rules) used to
determine which points are inside the diagram, for the purposes of
its query (see Using queries). Note that it does *not* affect
how the diagram is actually drawn; for that, use the `fillRule`

function. (This is not exactly a feature, but for various technical
reasons it is not at all obvious how to have this field actually
affect both the query and the rendering of the diagram.)

By default, `queryFillRule`

is set to `Winding`

.

### Decorating trails and paths

Paths (and trails) can be used not just to draw certain shapes, but
also as tools for positioning other objects. To this end,
`diagrams`

provides `decoratePath`

, `decorateLocatedTrail`

, and
`decorateTrail`

, which position a list of objects at the vertices of a
given path or trail.

For example, suppose we want to create an equilateral triangular
arrangement of dots. One possibility is to create horizontal rows of
dots, center them, and stack them vertically. However, this is
annoying, because we must manually compute the proper vertical
stacking distance between rows. Whether you think this sounds easy or
not, it is certainly going to involve the `sqrt`

function, or perhaps
some trig, or both, and we'd rather avoid all that.

Fortunately, there's an easier way: after creating the horizontal
rows, we create the path corresponding to the left-hand side of the
triangle (which can be done using `fromOffsets`

and a simple
rotation), and then decorate it with the rows.

```
> dot = circle 1 # fc black
> dotSep = 0.5
> dotOffset = (width (dot :: D R2) + dotSep) *^ unitX
> mkRow n = hcat' (with & sep .~ dotSep) (replicate n dot)
> mkTri n = decoratePath
> (fromOffsets (replicate (n-1) dotOffset) # rotateBy (-1/3))
> (map mkRow [1..n])
> example = mkTri 5
```

### Offsets of segments, trails, and paths

Given a segment and an offset radius \(r\) we can make an *offset segment*
that is the distance \(r\) from the original segment. More specifically,
you can think of the offset as the curve traced by the end of a vector of
length \(r\) perpendicular to the original curve. This vector goes on the
right of the curve for a positive radius and on the left for a negative radius.

Animate tracing an offset?

For a straight segment this will clearly be a parallel straight line with
\(r\) as the distance between the lines. For an counter-clockwise arc of
radius \(R\) the offset will be an arc with the same center, start and end
angles, and radius \(r+R\). Cubic segments present a problem, however.
The offset of a cubic Bézier curve could be a higher degree curve. To
accommodate this we approximate the offset with a sequence of segments. We
now have enough details to write the type for `offsetSegment`

.

The first parameter to `offsetSegment`

is an epsilon factor \(\epsilon\).
When the radius is multiplied by \(\epsilon\) we get the maximum allowed
distance a point on the approximate offset can differ from the true offset.
The final parameters are the radius and the segment. The result is a located
trail. It is located because the offset's start will be distance \(r\)
away from the segment start which is the origin.

If we can offset a segment we naturally will want to extend this to offset a
trail. A first approach might be to simply map `offsetSegment`

over the
segments of a trail. But we quickly notice that if the trail has any sharp
corners, the offset will be disconnected!

```
> import Diagrams.TwoD.Offset
>
> locatedTrailSegments t = zipWith at (trailSegments (unLoc t)) (trailVertices t)
>
> bindLoc f = join' . mapLoc f
> where
> join' x = let (p,a) = viewLoc x in translate (p .-. origin) a
>
> offsetTrailNaive :: Double -> Double -> Trail R2 -> Path R2
> offsetTrailNaive e r = mconcat . map (pathFromLocTrail . bindLoc (offsetSegment e r))
> . locatedTrailSegments . (`at` origin)
>
> example :: Diagram B R2
> example = (p # strokeTrail <> offsetTrailNaive 0.1 0.3 p # stroke # lc blue)
> # lw thick
> where p = fromVertices . map p2 $ [(0,0), (1,0.3), (2,0), (2.2,0.3)]
```

First let's consider the outside corner where the adjacent offset segments do
not cross. If we consider sweeping a perpendicular vector along the original
trail we have a problem when we get to a corner. It is not clear what
*perpendicular* means for that point. One solution is to take all points
distance \(r\) from the corner point. This puts a circle around the corner
of radius \(r\). Better is to just take the portion of that circle that
transitions from what is perpendicular at the end of the first segment to what
is perpendicular at the start of the next. We could also choose to join together
offset segments in other sensible ways. For the choice of join we have the
`_offsetJoin`

field in the `OffsetOpts`

record.

Inside corners are handled in a way that is consistent with outside corners, but
this yields a result that is most likely undesirable. Future versions of Diagrams
will include the ability to clip inside corners with several options for how to
do the clipping.

Update after implementing clipping.

There are other interesting ways we can join segments. We implement the standard
line join styles and will also in the future provide the ability to specify a custom
join.

The `LineJoinMiter`

style in particular can use more information to dictate how
long a miter join can extend. A sharp corner can have a miter join that is an
unbounded distance from the original corner. Usually, however, this long join
is not desired. Diagrams follows the practice of most graphics software and
provides a `_offsetMiterLimit`

field in the `OffsetOpts`

record. When the join
would be beyond the miter limit, the join is instead done with a straight line
as in the `LineJoinBevel`

style. The `OffsetOpts`

record then has three
parameters:

And the type for `offsetTrail'`

is (`offsetTrail`

simply uses the `Default`

instance for `OffsetOpts`

):

Notice this takes a `Trail R2`

which means it works for both `Trail' Line R2`

and `Trail' Loop R2`

. The second parameter is the radius for the offset. A
negative radius gives a `Line`

on the right of the curve, or a `Loop`

inside a
counter-clockwise `Loop`

. For `offsetPath`

we can simply map `offsetTrail`

over the trails in the path in the most natural way.

### Expand segments, trails, and paths

Expanding is just like the offset, but instead of producing a curve that
follows one side we follow both sides and produce a `Loop`

that can be filled
representing all the area within a radius \(r\) of the original curve.

In addition to specifying how segments are joined, we now have to specify the
transition from the offset on one side of a curve to the other side of a curve.
This is given by the `LineCap`

.

The functionality follows closely to the offset functions, but notice that
the result of `expandTrail`

is a `Path R2`

where `offsetTrail`

resulted in
a `Located (Trail R2)`

. This is because an expanded `Loop`

will be a pair
of loops, one inside and one outside. To express this we need a `Path`

.

As long as the expanded path is filled with the winding fill rule we
do not need to worry about having clipping for inside corners. It
works out that the extra loop in the rounded line join will match with
the outside corner. We currently implement all the `LineCap`

styles,
and plan to support custom styles in future releases.

### The `TrailLike`

class

As you may have noticed by now, a large class of functions in the
standard library—such as `square`

, `polygon`

, `fromVertices`

, and so
on—generate not just diagrams, but *any* type which is an instance
of the `TrailLike`

type class.

The `TrailLike`

type class, defined in `Diagrams.TrailLike`

, has
only a single method, `trailLike`

:

That is, a trail-like thing is anything which can be constructed from
a `Located Trail`

.

There are quite a few instances of `TrailLike`

:

`Trail`

: this instance simply throws away the location.

`Trail' Line`

: throw away the location, and perform `cutLoop`

if
necessary. For example, `circle 3 :: Trail' Line R2`

is an open \(360^\circ\)
circular arc.

`Trail' Loop`

: throw away the location, and perform `glueLine`

if
necessary.

`Path`

: construct a path with a single component.

`Diagram b R2`

: as long as the backend `b`

knows how to render 2D
paths, `trailLike`

can construct a diagram by stroking the generated
single-component path.

`[Point v]`

: this instance generates the vertices of the trail.

`Located (Trail v)`

, of course, has an instance which amounts to the
identity function. More generally, however, `Located a`

is an
instance of `TrailLike`

for *any* type `a`

which is also an
instance. In particular, the resulting `Located a`

has the location
of the input `Located Trail`

, and a value of type `a`

generated by
another call to `trailLike`

. This is most useful for generating
values of type `Located (Trail' Line v)`

and ```
Located (Trail' Loop
v)
```

. For example, ```
circle 3 # translateX 2 :: Located (Trail' Line
R2)
```

is an open \(360^\circ\) circular arc centered at
\((2,0)\).

It is quite convenient to be able to use, say, `square 2`

as a
diagram, path, trail, list of vertices, *etc.*, whichever suits one's
needs. Otherwise, either a long list of functions would be needed for
each primitive (like `square`

, `squarePath`

, `squareTrail`

,
`squareVertices`

, `squareLine`

, `squareLocatedLine`

, ... ugh!),
or else explicit conversion functions would have to be inserted when
you wanted something other than what the `square`

function gave you by
default.

As an (admittedly contrived) example, the following diagram defines
`s`

as an alias for `square 2`

and then uses it at four different
instances of `TrailLike`

:

Exercise: figure out which occurrence of `s`

has which type. (Answers
below.)

At its best, this type-directed behavior results in a "it just
works/do what I mean" experience. However, it can occasionally be
confusing, and care is needed. The biggest gotcha occurs when
combining a number of shapes using `(<>)`

or `mconcat`

: diagrams,
paths, trails, and lists of vertices all have `Monoid`

instances, but
they are all different, so the combination of shapes has different
semantics depending on which type is inferred.

The above example defines `ts`

by generating three equilateral
triangles offset by 1/9 rotations, then combining them with `mconcat`

.
The sneaky thing about this is that `ts`

can have the type of any
`TrailLike`

instance, and it has completely different meanings
depending on which type is chosen. The example uses `ts`

at each of
four different monoidal `TrailLike`

types:

Since `example`

is a diagram, the first `ts`

, used by itself, is
also a diagram; hence it is interpreted as three equilateral
triangle diagrams superimposed on one another with `atop`

.

`stroke`

turns `Path`

s into diagrams, so the second `ts`

has type
`Path R2`

. Hence it is interpreted as three closed triangular paths
superimposed into one three-component path, which is then stroked.

`strokeLine`

turns `Trail' Line`

s into diagrams, so the third
occurrence of `ts`

has type `Trail' Line R2`

. It is thus
interpreted as three open triangular trails sequenced end-to-end
into one long open trail. As a line (*i.e.* an open trail), it is
not filled (in order to make it filled we could replace ```
strokeLine
ts
```

with `strokeLoop (glueLine ts)`

).

The last occurrence of `ts`

is a list of points, namely, the
concatenation of the vertices of the three triangles. Turning this
into a diagram with `fromVertices`

generates a single-component,
open trail that visits each of the points in turn.

Of course, one way to avoid all this would be to give `ts`

a specific
type signature, if you know which type you would like it to be. Then
using it at a different type will result in a type error, rather than
confusing semantics.

Answers to the `square 2`

type inference challenge:

`Path R2`

`Diagram b R2`

`[P2]`

`Trail' Line R2`

### Segments and trails as parametric objects

Both segments and trails, semantically, can be seen as *parametric
functions*: that is, for each value of a parameter within some given
range (usually \([0,1]\), there is a corresponding vector value
(or point, for `Located`

segments and trails). The entire collection
of such vectors or points makes up the segment or trail.

The `Diagrams.Parametric`

module provides tools for working with
segments and trails as parametric functions.

#### Parametric

As explained above, parametric objects can be viewed semantically as
functions. In particular, parametric objects of type `p`

can be seen
as functions of type `Scalar (V p) -> Codomain p`

, where the type
family `Codomain`

is defined in such a way as to make this true. For
example, `Codomain (Trail R2) ~ R2`

, because a trail can be thought of
as a function `Double -> R2`

.

The `Parametric`

class defines the single method `atParam`

which
yields this parametric view of an object:

(Note that it is not possible to convert in the other
direction—every function of type `Scalar (V p) -> Codomain p`

need
not correspond to something of type `p`

. For example, to convert from
a function to a trail one would need at the very least a guarantee of
continuity; segments are even more restricted.)

Instances of `Parametric`

include:

`Segment Closed`

: The codomain is the type of vectors. Note there
is no instance for `Segment Open`

, since additional context is
needed to determine the endpoint, and hence the parametrization, of
an open segment.

`FixedSegment`

: The codomain is the type of points.

`Trail'`

: The codomain is the vector space. Note that there is no
difference between `Line`

and `Loop`

.

`Trail`

: same as the instance for `Trail'`

.

`Located a`

: as long as `a`

is also `Parametric`

and the codomain of
`a`

is a vector space, `Located a`

is parametric with points as the
codomain. For example, calling `atParam`

on a `Located (Trail R2)`

returns a `P2`

.

`Path`

s are *not* `Parametric`

, since they may have multiple trail
components and there is no canonical way to assign them a
parametrization.

#### DomainBounds

The `domainLower`

and `domainUpper`

functions simply return the lower
and upper bounds for the parameter. By default, these will be \(0\) and
\(1\), respectively. However, it is possible to have objects
parameterized over some interval other than \([0,1]\).

#### EndValues

The `EndValues`

class provides the functions `atStart`

and `atEnd`

,
which return the value at the start and end of the parameter interval,
respectively. In other words, semantically we have ```
atStart x = x
`atParam` domainLower x
```

, but certain types may have more efficient
or accurate ways of computing their start and end values (for example,
Bézier segments explicitly store their endpoints, so there is no need
to evaluate the generic parametric form).

#### Sectionable

The `Sectionable`

class abstracts over parametric things which can be
split into multiple sections (for example, a trail can be split into
two trails laid end-to-end). It provides three methods:

`splitAtParam :: p -> Scalar (V p) -> (p, p)`

splits something of
type `p`

at the given parameter into two things of type `p`

.
The resulting values will be linearly reparameterized to cover the
same parameter space as the parent value. For example, a segment
with parameter values in \([0,1]\) will be split into two
shorter segments which are also parameterized over \([0,1]\).

`section :: p -> Scalar (V p) -> Scalar (V p) -> p`

extracts the
subpart of the original lying between the given parameters, linearly
reparameterized to the same domain as the original.

`reverseDomain :: p -> p`

reverses the parameterization. It
probably should not be in this class and is likely to move elsewhere
in future versions.

#### HasArcLength

`HasArcLength`

abstracts over parametric things with a notion of arc
length. It provides five methods:

#### Adjusting length

Anything which is an instance of `DomainBounds`

, `Sectionable`

, and
`HasArcLength`

can be "adjusted" using the `adjust`

function, which
provides a number of options for changing the length and extent.

#### Computing tangents and normals

The `Diagrams.Tangent`

module contains functions for computing
tangent vectors and normal vectors to segments and trails, at an
arbitrary parametmer (`tangentAtParam`

, `normalAtParam`

) or at the
start or end (`tangentAtStart`

, `tangentAtEnd`

, `normalAtStart`

,
`normalAtEnd`

). (The start/end functions are provided because such
tangent and normal vectors may often be computed more quickly and
precisely than using the general formula with a parameter of 0 or 1.)

### Fill rules

There are two main algorithms or "rules" used when determining which
areas to fill with color when filling the interior of a path: the
*winding rule* and the *even-odd rule*. The rule used to draw a
path-based diagram can be set with `fillRule`

, defined in
`Diagrams.TwoD.Path`

. For simple, non-self-intersecting paths,
determining which points are inside is quite simple, and the two
algorithms give the same results. However, for self-intersecting
paths, they usually result in different regions being filled.

The *even-odd rule* specifies that a point is inside the path if a
straight line extended from the point off to infinity (in one
direction only) crosses the path an odd number of times. Points
with an even number of crossings are outside the path. This rule is
simple to implement and works perfectly well for
non-self-intersecting paths. For self-intersecting paths, however,
it results in a pattern of alternating filled and unfilled
regions, as seen in the above example. Sometimes this pattern is
desirable for its own sake.

The *winding rule* specifies that a point is inside the path if its
*winding number* is nonzero. The winding number measures how many
times the path "winds" around the point, and can be intuitively
computed as follows: imagine yourself standing at the given point,
facing some point on the path. You hold one end of an (infinitely
stretchy) rope; the other end of the rope is attached to a train
sitting at the point on the path at which you are looking. Now the
train begins traveling around the path. As it goes, you keep hold of
your end of the rope while standing fixed in place, not turning at
all. After the train has completed one circuit around the path,
look at the rope: if it is wrapped around you some number of times,
you are inside the path; if it is not wrapped around you, you are
outside the path. More generally, we say that the number of times
the rope is wrapped around you (positive for one direction and
negative for the other) is the point's winding number.

Draw a picture of you and the train

For example, if you stand outside a circle looking at a train
traveling around it, the rope will move from side to side as the
train goes around the circle, but ultimately will return to exactly
the state in which it started. If you are standing inside the
circle, however, the rope will end up wrapped around you once.

For paths with multiple components, the winding number is simply the
sum of the winding numbers for the individual components. This
means, for example, that "holes" can be created in shapes using a
path component traveling in the *opposite direction* from the outer
path.

This rule does a much better job with self-intersecting paths, and
it turns out to be (with some clever optimizations) not much more
difficult to implement or inefficient than the even-odd rule.

You should be aware that queries (see Using queries) use the
winding rule by default, and are not affected by the path fill rule
attribute. Thus, if you apply the even-odd rule to a diagram, the
query may not match in the way you expect. For this reason, if you
want to make a shape with holes in it, it is usually better to form
the holes from paths winding in the opposite direction (using
`reversePath`

and the winding rule) than from the even-odd rule. For
example, in the diagram below, the annulus on the left is formed using
the even-odd fill rule, and the one on the right with the default
winding rule and a reversed inner circle. The dark blue points
indicate places where the associated query evaluates to true.

If you do want to make a diagram whose query uses the even-odd rule,
you can use the `stroke'`

function.

### Clipping

With backends that support clipping, paths can be used to *clip* other
diagrams. Only the portion of a clipped diagram falling inside the
clipping path will be drawn.

Several functions are available, depending on what envelope and trace
you want the resulting diagram to have. `clipBy`

uses the envelope
and trace of the original diagram. `clipped`

uses the envelope and
trace of the clipping path. `clipTo`

uses the intersection of the two
envelopes, and a trace which matches the displayed outline of the
diagram. Note that in general the intersection of envelopes is larger
than the envelope of an intersection. Diagrams does not have a
function which returns the tight envelope of the intersection.

Altering a diagram's envelope can also be accomplished using `withEnvelope`

(see Envelope-related functions). The `view`

function is also
provided for the special case of setting a diagram's envelope to some
rectangle, often used for the purpose of selecting only a part of a
diagram to be "viewed" in the final output. It takes a point—the
lower-left corner of the viewing rectangle—and the vector from the
lower-left to upper-right corner.

Note in the above example how the actual portion of the diagram that
ends up being visible is larger than the specification given to
`view`

—this is because the aspect ratio of the requested output
image does not match the aspect ratio of the rectangle given to
`view`

(and also because of the use of `pad`

by the framework which
renders the user manual examples). If the aspect ratios matched the
viewed portion would be exactly that specified in the call to `view`

.

### Trail and path implementation details

Trails are implemented using finger trees: in particular, lines are
finger trees of closed segments, while loops consist of a finger tree
of closed segments plus a single final open segment.

The benefit of using a finger tree (instead of just, say, a list, or
even a `Seq`

structure from `Data.Sequence`

) is that it allows
caching monoidal "measures" of the entire trail. In particular, the
finger trees underlying trails cache

For more details, see the `Diagrams.Segment`

and
`Diagrams.Trail`

modules.

Another interesting aspect of the implementation is that upon stroking
a path to form a diagram, instead of simply putting the entire path
into a primitive, we separate out the lines and loops into two path
primitives. This is helpful for backends because they often have to
do some active work to *avoid* filling lines, and if
`diagrams-lib`

did not do this separation, they would essentially
have to end up doing it themselves.

## 3.7 Text

Note: The various backends differ substantially in their text-handling
capabilities. For this and other reasons, there are two ways to add
text to diagrams, each with advantages. The method in this section is
heavily dependant on Backend support. The Cairo Backend has the most
complete support; in particular, this is the best approach for complex
(non-Roman) scripts. You may also want to look at `SVGFonts`

package, described in the section Native font support below, which
converts text directly as `Path`

s.

Text objects, defined in `Diagrams.TwoD.Text`

, can be created
most simply with the `text`

function, which turns a `String`

into a
diagram with (centered) text:

`> example = text "Hello world!" <> rect 8 1`

Text with different alignments can be created using `topLeftText`

or
`baselineText`

(or, more generally, `alignedText`

, though it is not
supported by all backends—the SVG backend in particular only
supports an approximation to `alignedText`

):

The most important thing to keep in mind when working with text
objects is that they *take up no space*: they have a *point envelope*
at the origin, *i.e.* for the purposes of things like `beside`

, they
have a width and height of zero. (Note, however, this is not the same
as having an *empty* envelope. In particular, they still behave in an
intuitive manner when included as arguments to things like `hcat`

.)
If we omitted the rectangle from the above example, there would be no
output.

Text objects take up no space!

The main reason for this is that computing the size of some text in a
given font is rather complicated, and `diagrams`

cannot (yet) do it
natively. The cairo backend can do it (see below) but we don't want
to tie diagrams to a particular backend.

Note, however, that the cairo backend includes a module
`Diagrams.Backend.Cairo.Text`

with functions for querying font
and text extents, and creating text diagrams that take up an
appropriate amount of space. So it *is* possible to have
automatically-sized text objects, at the cost of being tied to the
cairo backend and bringing `IO`

into the picture (or being at peace
with some probably-justified uses of `unsafePerformIO`

).

Various attributes of text can be set using `font`

, `bold`

(or, more
generally, `fontWeight`

), `italic`

, and `oblique`

(or, more generally,
`fontSlant`

). Text is colored with the current fill color (see
Color).

### Font size

Font size is set using the `fontSize`

function, and is specified by a
value of type `Measure R2`

(see Measurement units).

Text with a `Local`

font size is measured relative to its local
vector space. Such text is transformed normally by any
transformations applied to it. For example, in the diagram below,
`fontSize (Local 1)`

is specified (this is actually the default, so
it could be omitted without changing the diagram). Note how the F's
are the same size as a unit box, and scale, stretch, and rotate
along with it.

Text whose font size is specified in any measurement other than
`Local`

(that is, `Normalized`

, `Global`

, or `Output`

) behaves
differently.

There are several things to notice about the above example
diagram, which is identical to the previous one except for the
fact that `Normalized 0.1`

is used instead of `Local 1`

:

The F's are 1/10th the size of the overall diagram. If
we added more copies of `eff`

to the right, but kept the
physical size of the rendered image the same, the F's would
remain the same physical size on the screen, but would get
bigger relative to the boxes (since the boxes would be smaller
in absolute terms).

The F's are all about the same size—in particular, the uniform
scaling applied to the second F has no effect, and the fourth F is
not twice as tall as the others. Note, however, that the final F
rotates with the square as expected. Note also that the third and
fourth F's are squished, as one would expect from a non-uniform
scaling. The hand-wavy slogan is that non-`Local`

-sized text is
"affected by transformations, but without changing size".

The technical specification is that applying a transformation
\(T\) to non-`Local`

-sized text actually results in applying
the transformation \(T/|T|\), where \(|T|\) denotes the
*average scaling factor* of the transformation \(T\), computed
as the square root of the positive determinant of \(T\). This
behaves nicely: for example, the average scaling factor of ```
scale
k
```

is `k`

, so applying a uniform scaling to non-`Local`

-sized text
has no effect; it is also compositional, so applying `t`

and then
`s`

to some text has exactly the same effect as applying `s <> t`

.
For more information, see the `avgScale`

function and the comments
associated with its source code.

### Native font support

The SVGFonts package implements native text support for diagrams,
using fonts in the SVG format (note that it can be used with *any*
backend, not just the SVG backend). Among other things, it provides
its own `textSVG`

function which can be used to convert text into a
*path* tracing the outline of the text. Here is a simple example:

For more details and examples, see the Haddock documentation.

## 3.8 Images

The `Diagrams.TwoD.Image`

module provides basic support for
including both external and embedded images in diagrams.
Support for images varies by backend, only the cairo
backend supports external images. The rasterific backend
supports embedded images of many formats and the SVG backend
supports embedded png images.

To create an embedded image use either `loadImageEmb`

to read an
image from a file path using `JuicyPixels`

and return a
`DImage Embedded`

. Then use `image`

to convert the `DImage Embedded`

to a diagram. You can also create an a diagram with an embedded image
by supplying a function that maps pixel coordinates to `alphaColour`

s
plus a width and a height to the`rasterDia` function.

The function `loadImageExt`

checks to make sure the file exists, uses
`JuicyPixels`

to determine its size and returns a reference to
the image. On the otherhand `uncheckedImageRef`

simply packages the
reference with a width and height to make a `DImage External`

.

When using `loadImageEmb`

and `loadImageExt`

you do not need to
provide the width and height of the image as they will be calculated
by `JuicyPixels`

. Otherwise you must specify both a width and
a height for each image. In this case you might hope to be able to
specify just a width or just a height, and have the other dimension
computed so as to preserve the image's aspect ratio. However, there
is no way for `diagrams`

to query an image's aspect ratio until
rendering time, but (until such time as a constraint solver is added)
it needs to know the size of the image when composing it with other
subdiagrams. Hence, both dimensions must be specified, and for the
purposes of positioning relative to other diagrams, the image will
be assumed to occupy a rectangle of the given dimensions.

However, note that the image's aspect ratio will be preserved: if you
specify dimensions that do not match the actual aspect ratio of the
image, blank space will be left in one of the two dimensions to
compensate. If you wish to alter an image's aspect ratio, you can do
so by scaling nonuniformly with `scaleX`

, `scaleY`

, or something
similar.

Currently, the cairo backend can only include images in `png`

format, but hopefully this will be expanded in the future. The rasterific
backend will render many different image formats including, `png`

, `jpg`

,
`tif`

, `bmp`

and `gif`

.