text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

AffineTransform::AffineTransform() noexcept
    : mat00 (1.0f), mat01 (0), mat02 (0),
      mat10 (0), mat11 (1.0f), mat12 (0)
{
}

AffineTransform::AffineTransform (const AffineTransform& other) noexcept
  : mat00 (other.mat00), mat01 (other.mat01), mat02 (other.mat02),
    mat10 (other.mat10), mat11 (other.mat11), mat12 (other.mat12)
{
}

AffineTransform::AffineTransform (const float m00, const float m01, const float m02,
                                  const float m10, const float m11, const float m12) noexcept
 :  mat00 (m00), mat01 (m01), mat02 (m02),
    mat10 (m10), mat11 (m11), mat12 (m12)
{
}

AffineTransform& AffineTransform::operator= (const AffineTransform& other) noexcept
{
    mat00 = other.mat00;
    mat01 = other.mat01;
    mat02 = other.mat02;
    mat10 = other.mat10;
    mat11 = other.mat11;
    mat12 = other.mat12;

    return *this;
}

bool AffineTransform::operator== (const AffineTransform& other) const noexcept
{
    return mat00 == other.mat00
        && mat01 == other.mat01
        && mat02 == other.mat02
        && mat10 == other.mat10
        && mat11 == other.mat11
        && mat12 == other.mat12;
}

bool AffineTransform::operator!= (const AffineTransform& other) const noexcept
{
    return ! operator== (other);
}

//==============================================================================
bool AffineTransform::isIdentity() const noexcept
{
    return (mat01 == 0.0f)
        && (mat02 == 0.0f)
        && (mat10 == 0.0f)
        && (mat12 == 0.0f)
        && (mat00 == 1.0f)
        && (mat11 == 1.0f);
}

#if JUCE_ALLOW_STATIC_NULL_VARIABLES
const AffineTransform AffineTransform::identity;
#endif

//==============================================================================
AffineTransform AffineTransform::followedBy (const AffineTransform& other) const noexcept
{
    return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
                            other.mat00 * mat01 + other.mat01 * mat11,
                            other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
                            other.mat10 * mat00 + other.mat11 * mat10,
                            other.mat10 * mat01 + other.mat11 * mat11,
                            other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
}

AffineTransform AffineTransform::translated (const float dx, const float dy) const noexcept
{
    return AffineTransform (mat00, mat01, mat02 + dx,
                            mat10, mat11, mat12 + dy);
}

AffineTransform AffineTransform::translation (const float dx, const float dy) noexcept
{
    return AffineTransform (1.0f, 0, dx,
                            0, 1.0f, dy);
}

AffineTransform AffineTransform::withAbsoluteTranslation (const float tx, const float ty) const noexcept
{
    return AffineTransform (mat00, mat01, tx,
                            mat10, mat11, ty);
}

AffineTransform AffineTransform::rotated (const float rad) const noexcept
{
    const float cosRad = std::cos (rad);
    const float sinRad = std::sin (rad);

    return AffineTransform (cosRad * mat00 + -sinRad * mat10,
                            cosRad * mat01 + -sinRad * mat11,
                            cosRad * mat02 + -sinRad * mat12,
                            sinRad * mat00 + cosRad * mat10,
                            sinRad * mat01 + cosRad * mat11,
                            sinRad * mat02 + cosRad * mat12);
}

AffineTransform AffineTransform::rotation (const float rad) noexcept
{
    const float cosRad = std::cos (rad);
    const float sinRad = std::sin (rad);

    return AffineTransform (cosRad, -sinRad, 0,
                            sinRad, cosRad, 0);
}

AffineTransform AffineTransform::rotation (const float rad, const float pivotX, const float pivotY) noexcept
{
    const float cosRad = std::cos (rad);
    const float sinRad = std::sin (rad);

    return AffineTransform (cosRad, -sinRad, -cosRad * pivotX + sinRad * pivotY + pivotX,
                            sinRad, cosRad, -sinRad * pivotX + -cosRad * pivotY + pivotY);
}

AffineTransform AffineTransform::rotated (const float angle, const float pivotX, const float pivotY) const noexcept
{
    return followedBy (rotation (angle, pivotX, pivotY));
}

AffineTransform AffineTransform::scaled (const float factorX, const float factorY) const noexcept
{
    return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
                            factorY * mat10, factorY * mat11, factorY * mat12);
}

AffineTransform AffineTransform::scaled (const float factor) const noexcept
{
    return AffineTransform (factor * mat00, factor * mat01, factor * mat02,
                            factor * mat10, factor * mat11, factor * mat12);
}

AffineTransform AffineTransform::scale (const float factorX, const float factorY) noexcept
{
    return AffineTransform (factorX, 0, 0, 0, factorY, 0);
}

AffineTransform AffineTransform::scale (const float factor) noexcept
{
    return AffineTransform (factor, 0, 0, 0, factor, 0);
}

AffineTransform AffineTransform::scaled (const float factorX, const float factorY,
                                         const float pivotX, const float pivotY) const noexcept
{
    return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02 + pivotX * (1.0f - factorX),
                            factorY * mat10, factorY * mat11, factorY * mat12 + pivotY * (1.0f - factorY));
}

AffineTransform AffineTransform::scale (const float factorX, const float factorY,
                                        const float pivotX, const float pivotY) noexcept
{
    return AffineTransform (factorX, 0, pivotX * (1.0f - factorX),
                            0, factorY, pivotY * (1.0f - factorY));
}

AffineTransform AffineTransform::shear (float shearX, float shearY) noexcept
{
    return AffineTransform (1.0f, shearX, 0,
                            shearY, 1.0f, 0);
}

AffineTransform AffineTransform::sheared (const float shearX, const float shearY) const noexcept
{
    return AffineTransform (mat00 + shearX * mat10,
                            mat01 + shearX * mat11,
                            mat02 + shearX * mat12,
                            mat10 + shearY * mat00,
                            mat11 + shearY * mat01,
                            mat12 + shearY * mat02);
}

AffineTransform AffineTransform::verticalFlip (const float height) noexcept
{
    return AffineTransform (1.0f, 0, 0, 0, -1.0f, height);
}

AffineTransform AffineTransform::inverted() const noexcept
{
    double determinant = (mat00 * mat11 - mat10 * mat01);

    if (determinant != 0.0)
    {
        determinant = 1.0 / determinant;

        const float dst00 = (float) ( mat11 * determinant);
        const float dst10 = (float) (-mat10 * determinant);
        const float dst01 = (float) (-mat01 * determinant);
        const float dst11 = (float) ( mat00 * determinant);

        return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
                                dst10, dst11, -mat02 * dst10 - mat12 * dst11);
    }

    // singularity..
    return *this;
}

bool AffineTransform::isSingularity() const noexcept
{
    return (mat00 * mat11 - mat10 * mat01) == 0.0f;
}

AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
                                                   const float x10, const float y10,
                                                   const float x01, const float y01) noexcept
{
    return AffineTransform (x10 - x00, x01 - x00, x00,
                            y10 - y00, y01 - y00, y00);
}

AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
                                                   const float sx2, const float sy2, const float tx2, const float ty2,
                                                   const float sx3, const float sy3, const float tx3, const float ty3) noexcept
{
    return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
            .inverted()
            .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
}

bool AffineTransform::isOnlyTranslation() const noexcept
{
    return (mat01 == 0.0f)
        && (mat10 == 0.0f)
        && (mat00 == 1.0f)
        && (mat11 == 1.0f);
}

float AffineTransform::getScaleFactor() const noexcept
{
    return (std::abs (mat00) + std::abs (mat11)) / 2.0f;
}

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
/**
    Represents a line.

    This class contains a bunch of useful methods for various geometric
    tasks.

    The ValueType template parameter should be a primitive type - float or double
    are what it's designed for. Integer types will work in a basic way, but some methods
    that perform mathematical operations may not compile, or they may not produce
    sensible results.

    @see Point, Rectangle, Path, Graphics::drawLine
*/
template <typename ValueType>
class Line
{
public:
    //==============================================================================
    /** Creates a line, using (0, 0) as its start and end points. */
    Line() noexcept {}

    /** Creates a copy of another line. */
    Line (const Line& other) noexcept
        : start (other.start), end (other.end)
    {
    }

    /** Creates a line based on the coordinates of its start and end points. */
    Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) noexcept
        : start (startX, startY), end (endX, endY)
    {
    }

    /** Creates a line from its start and end points. */
    Line (Point<ValueType> startPoint, Point<ValueType> endPoint) noexcept
        : start (startPoint), end (endPoint)
    {
    }

    /** Copies a line from another one. */
    Line& operator= (const Line& other) noexcept
    {
        start = other.start;
        end = other.end;
        return *this;
    }

    /** Destructor. */
    ~Line() noexcept {}

    //==============================================================================
    /** Returns the x coordinate of the line's start point. */
    inline ValueType getStartX() const noexcept                             { return start.x; }

    /** Returns the y coordinate of the line's start point. */
    inline ValueType getStartY() const noexcept                             { return start.y; }

    /** Returns the x coordinate of the line's end point. */
    inline ValueType getEndX() const noexcept                               { return end.x; }

    /** Returns the y coordinate of the line's end point. */
    inline ValueType getEndY() const noexcept                               { return end.y; }

    /** Returns the line's start point. */
    inline Point<ValueType> getStart() const noexcept                       { return start; }

    /** Returns the line's end point. */
    inline Point<ValueType> getEnd() const noexcept                         { return end; }

    /** Changes this line's start point */
    void setStart (ValueType newStartX, ValueType newStartY) noexcept       { start.setXY (newStartX, newStartY); }

    /** Changes this line's end point */
    void setEnd (ValueType newEndX, ValueType newEndY) noexcept             { end.setXY (newEndX, newEndY); }

    /** Changes this line's start point */
    void setStart (const Point<ValueType> newStart) noexcept                { start = newStart; }

    /** Changes this line's end point */
    void setEnd (const Point<ValueType> newEnd) noexcept                    { end = newEnd; }

    /** Returns a line that is the same as this one, but with the start and end reversed, */
    Line reversed() const noexcept                                          { return { end, start }; }

    /** Applies an affine transform to the line's start and end points. */
    void applyTransform (const AffineTransform& transform) noexcept
    {
        start.applyTransform (transform);
        end.applyTransform (transform);
    }

    //==============================================================================
    /** Returns the length of the line. */
    ValueType getLength() const noexcept                                    { return start.getDistanceFrom (end); }

    /** Returns the length of the line. */
    ValueType getLengthSquared() const noexcept                             { return start.getDistanceSquaredFrom (end); }

    /** Returns true if the line's start and end x coordinates are the same. */
    bool isVertical() const noexcept                                        { return start.x == end.x; }

    /** Returns true if the line's start and end y coordinates are the same. */
    bool isHorizontal() const noexcept                                      { return start.y == end.y; }

    /** Returns the line's angle.

        This value is the number of radians clockwise from the 12 o'clock direction,
        where the line's start point is considered to be at the centre.
    */
    typename Point<ValueType>::FloatType getAngle() const noexcept          { return start.getAngleToPoint (end); }

    /** Creates a line from a start point, length and angle.

        This angle is the number of radians clockwise from the 12 o'clock direction,
        where the line's start point is considered to be at the centre.
    */
    static Line fromStartAndAngle (Point<ValueType> startPoint, ValueType length, ValueType angle) noexcept
    {
        return { startPoint, startPoint.getPointOnCircumference (length, angle) };
    }

    //==============================================================================
    /** Casts this line to float coordinates. */
    Line<float> toFloat() const noexcept                                    { return { start.toFloat(), end.toFloat() }; }

    /** Casts this line to double coordinates. */
    Line<double> toDouble() const noexcept                                  { return { start.toDouble(), end.toDouble() }; }

    //==============================================================================
    /** Compares two lines. */
    bool operator== (Line other) const noexcept                             { return start == other.start && end == other.end; }

    /** Compares two lines. */
    bool operator!= (Line other) const noexcept                             { return start != other.start || end != other.end; }

    //==============================================================================
    /** Finds the intersection between two lines.

        @param line     the line to intersect with
        @returns        the point at which the lines intersect, even if this lies beyond the end of the lines
    */
    Point<ValueType> getIntersection (Line line) const noexcept
    {
        Point<ValueType> p;
        findIntersection (start, end, line.start, line.end, p);
        return p;
    }

    /** Finds the intersection between two lines.

        @param line             the other line
        @param intersection     the position of the point where the lines meet (or
                                where they would meet if they were infinitely long)
                                the intersection (if the lines intersect). If the lines
                                are parallel, this will just be set to the position
                                of one of the line's endpoints.
        @returns    true if the line segments intersect; false if they dont. Even if they
                    don't intersect, the intersection coordinates returned will still
                    be valid
    */
    bool intersects (Line line, Point<ValueType>& intersection) const noexcept
    {
        return findIntersection (start, end, line.start, line.end, intersection);
    }

    /** Returns true if this line intersects another. */
    bool intersects (Line other) const noexcept
    {
        Point<ValueType> ignored;
        return findIntersection (start, end, other.start, other.end, ignored);
    }

    //==============================================================================
    /** Returns the location of the point which is a given distance along this line.

        @param distanceFromStart    the distance to move along the line from its
                                    start point. This value can be negative or longer
                                    than the line itself
        @see getPointAlongLineProportionally
    */
    Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const noexcept
    {
        return start + (end - start) * (distanceFromStart / getLength());
    }

    /** Returns a point which is a certain distance along and to the side of this line.

        This effectively moves a given distance along the line, then another distance
        perpendicularly to this, and returns the resulting position.

        @param distanceFromStart    the distance to move along the line from its
                                    start point. This value can be negative or longer
                                    than the line itself
        @param perpendicularDistance    how far to move sideways from the line. If you're
                                    looking along the line from its start towards its
                                    end, then a positive value here will move to the
                                    right, negative value move to the left.
    */
    Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
                                        ValueType perpendicularDistance) const noexcept
    {
        auto delta = end - start;
        auto length = juce_hypot ((double) delta.x,
                                  (double) delta.y);
        if (length <= 0)
            return start;

        return { start.x + static_cast<ValueType> ((delta.x * distanceFromStart - delta.y * perpendicularDistance) / length),
                 start.y + static_cast<ValueType> ((delta.y * distanceFromStart + delta.x * perpendicularDistance) / length) };
    }

    /** Returns the location of the point which is a given distance along this line
        proportional to the line's length.

        @param proportionOfLength   the distance to move along the line from its
                                    start point, in multiples of the line's length.
                                    So a value of 0.0 will return the line's start point
                                    and a value of 1.0 will return its end point. (This value
                                    can be negative or greater than 1.0).
        @see getPointAlongLine
    */
    Point<ValueType> getPointAlongLineProportionally (typename Point<ValueType>::FloatType proportionOfLength) const noexcept
    {
        return start + (end - start) * proportionOfLength;
    }

    /** Returns the smallest distance between this line segment and a given point.

        So if the point is close to the line, this will return the perpendicular
        distance from the line; if the point is a long way beyond one of the line's
        end-point's, it'll return the straight-line distance to the nearest end-point.

        pointOnLine receives the position of the point that is found.

        @returns the point's distance from the line
        @see getPositionAlongLineOfNearestPoint
    */
    ValueType getDistanceFromPoint (Point<ValueType> targetPoint,
                                    Point<ValueType>& pointOnLine) const noexcept
    {
        auto delta = end - start;
        auto length = delta.x * delta.x + delta.y * delta.y;

        if (length > 0)
        {
            auto prop = ((targetPoint.x - start.x) * delta.x
                       + (targetPoint.y - start.y) * delta.y) / (double) length;

            if (prop >= 0 && prop <= 1.0)
            {
                pointOnLine = start + delta * prop;
                return targetPoint.getDistanceFrom (pointOnLine);
            }
        }

        auto fromStart = targetPoint.getDistanceFrom (start);
        auto fromEnd   = targetPoint.getDistanceFrom (end);

        if (fromStart < fromEnd)
        {
            pointOnLine = start;
            return fromStart;
        }

        pointOnLine = end;
        return fromEnd;
    }

    /** Finds the point on this line which is nearest to a given point, and
        returns its position as a proportional position along the line.

        @returns    a value 0 to 1.0 which is the distance along this line from the
                    line's start to the point which is nearest to the point passed-in. To
                    turn this number into a position, use getPointAlongLineProportionally().
        @see getDistanceFromPoint, getPointAlongLineProportionally
    */
    ValueType findNearestProportionalPositionTo (Point<ValueType> point) const noexcept
    {
        auto delta = end - start;
        auto length = delta.x * delta.x + delta.y * delta.y;

        return length <= 0 ? 0
                           : jlimit (ValueType(), static_cast<ValueType> (1),
                                     static_cast<ValueType> ((((point.x - start.x) * delta.x
                                                             + (point.y - start.y) * delta.y) / length)));
    }

    /** Finds the point on this line which is nearest to a given point.
        @see getDistanceFromPoint, findNearestProportionalPositionTo
    */
    Point<ValueType> findNearestPointTo (Point<ValueType> point) const noexcept
    {
        return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
    }

    /** Returns true if the given point lies above this line.

        The return value is true if the point's y coordinate is less than the y
        coordinate of this line at the given x (assuming the line extends infinitely
        in both directions).
    */
    bool isPointAbove (Point<ValueType> point) const noexcept
    {
        return start.x != end.x
                && point.y < ((end.y - start.y) * (point.x - start.x)) / (end.x - start.x) + start.y;
    }

    //==============================================================================
    /** Returns a shortened copy of this line.

        This will chop off part of the start of this line by a certain amount, (leaving the
        end-point the same), and return the new line.
    */
    Line withShortenedStart (ValueType distanceToShortenBy) const noexcept
    {
        return { getPointAlongLine (jmin (distanceToShortenBy, getLength())), end };
    }

    /** Returns a shortened copy of this line.

        This will chop off part of the end of this line by a certain amount, (leaving the
        start-point the same), and return the new line.
    */
    Line withShortenedEnd (ValueType distanceToShortenBy) const noexcept
    {
        auto length = getLength();
        return { start, getPointAlongLine (length - jmin (distanceToShortenBy, length)) };
    }

private:
    //==============================================================================
    Point<ValueType> start, end;

    static bool isZeroToOne (ValueType v) noexcept      { return v >= 0 && v <= static_cast<ValueType> (1); }

    static bool findIntersection (const Point<ValueType> p1, const Point<ValueType> p2,
                                  const Point<ValueType> p3, const Point<ValueType> p4,
                                  Point<ValueType>& intersection) noexcept
    {
        if (p2 == p3)
        {
            intersection = p2;
            return true;
        }

        auto d1 = p2 - p1;
        auto d2 = p4 - p3;
        auto divisor = d1.x * d2.y - d2.x * d1.y;

        if (divisor == 0)
        {
            if (! (d1.isOrigin() || d2.isOrigin()))
            {
                if (d1.y == 0 && d2.y != 0)
                {
                    auto along = (p1.y - p3.y) / d2.y;
                    intersection = p1.withX (p3.x + along * d2.x);
                    return isZeroToOne (along);
                }

                if (d2.y == 0 && d1.y != 0)
                {
                    auto along = (p3.y - p1.y) / d1.y;
                    intersection = p3.withX (p1.x + along * d1.x);
                    return isZeroToOne (along);
                }

                if (d1.x == 0 && d2.x != 0)
                {
                    auto along = (p1.x - p3.x) / d2.x;
                    intersection = p1.withY (p3.y + along * d2.y);
                    return isZeroToOne (along);
                }

                if (d2.x == 0 && d1.x != 0)
                {
                    auto along = (p3.x - p1.x) / d1.x;
                    intersection = p3.withY (p1.y + along * d1.y);
                    return isZeroToOne (along);
                }
            }

            intersection = (p2 + p3) / static_cast<ValueType> (2);
            return false;
        }

        auto along1 = ((p1.y - p3.y) * d2.x - (p1.x - p3.x) * d2.y) / divisor;
        intersection = p1 + d1 * along1;

        if (! isZeroToOne (along1))
            return false;

        auto along2 = ((p1.y - p3.y) * d1.x - (p1.x - p3.x) * d1.y) / divisor;
        return isZeroToOne (along2);
    }
};

} // namespace juce

repo_name: fedden/RenderMan

mime_type: text/x-c++


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
/**
    Specifies a set of gaps to be left around the sides of a rectangle.

    This is basically the size of the spaces at the top, bottom, left and right of
    a rectangle. It's used by various component classes to specify borders.

    @see Rectangle
*/
template <typename ValueType>
class BorderSize
{
public:
    //==============================================================================
    /** Creates a null border.
        All sizes are left as 0.
    */
    BorderSize() noexcept
        : top(), left(), bottom(), right()
    {
    }

    /** Creates a copy of another border. */
    BorderSize (const BorderSize& other) noexcept
        : top (other.top), left (other.left), bottom (other.bottom), right (other.right)
    {
    }

    /** Creates a border with the given gaps. */
    BorderSize (ValueType topGap, ValueType leftGap, ValueType bottomGap, ValueType rightGap) noexcept
        : top (topGap), left (leftGap), bottom (bottomGap), right (rightGap)
    {
    }

    /** Creates a border with the given gap on all sides. */
    explicit BorderSize (ValueType allGaps) noexcept
        : top (allGaps), left (allGaps), bottom (allGaps), right (allGaps)
    {
    }

    //==============================================================================
    /** Returns the gap that should be left at the top of the region. */
    ValueType getTop() const noexcept                   { return top; }

    /** Returns the gap that should be left at the top of the region. */
    ValueType getLeft() const noexcept                  { return left; }

    /** Returns the gap that should be left at the top of the region. */
    ValueType getBottom() const noexcept                { return bottom; }

    /** Returns the gap that should be left at the top of the region. */
    ValueType getRight() const noexcept                 { return right; }

    /** Returns the sum of the top and bottom gaps. */
    ValueType getTopAndBottom() const noexcept          { return top + bottom; }

    /** Returns the sum of the left and right gaps. */
    ValueType getLeftAndRight() const noexcept          { return left + right; }

    /** Returns true if this border has no thickness along any edge. */
    bool isEmpty() const noexcept                       { return left + right + top + bottom == ValueType(); }

    //==============================================================================
    /** Changes the top gap. */
    void setTop (ValueType newTopGap) noexcept          { top = newTopGap; }

    /** Changes the left gap. */
    void setLeft (ValueType newLeftGap) noexcept        { left = newLeftGap; }

    /** Changes the bottom gap. */
    void setBottom (ValueType newBottomGap) noexcept    { bottom = newBottomGap; }

    /** Changes the right gap. */
    void setRight (ValueType newRightGap) noexcept      { right = newRightGap; }

    //==============================================================================
    /** Returns a rectangle with these borders removed from it. */
    Rectangle<ValueType> subtractedFrom (const Rectangle<ValueType>& original) const noexcept
    {
        return Rectangle<ValueType> (original.getX() + left,
                                     original.getY() + top,
                                     original.getWidth() - (left + right),
                                     original.getHeight() - (top + bottom));
    }

    /** Removes this border from a given rectangle. */
    void subtractFrom (Rectangle<ValueType>& rectangle) const noexcept
    {
        rectangle = subtractedFrom (rectangle);
    }

    /** Returns a rectangle with these borders added around it. */
    Rectangle<ValueType> addedTo (const Rectangle<ValueType>& original) const noexcept
    {
        return Rectangle<ValueType> (original.getX() - left,
                                     original.getY() - top,
                                     original.getWidth() + (left + right),
                                     original.getHeight() + (top + bottom));
    }

    /** Adds this border around a given rectangle. */
    void addTo (Rectangle<ValueType>& rectangle) const noexcept
    {
        rectangle = addedTo (rectangle);
    }

    //==============================================================================
    bool operator== (const BorderSize& other) const noexcept
    {
        return top == other.top && left == other.left && bottom == other.bottom && right == other.right;
    }

    bool operator!= (const BorderSize& other) const noexcept
    {
        return ! operator== (other);
    }

private:
    //==============================================================================
    ValueType top, left, bottom, right;
};

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
/**
    Describes a type of stroke used to render a solid outline along a path.

    A PathStrokeType object can be used directly to create the shape of an outline
    around a path, and is used by Graphics::strokePath to specify the type of
    stroke to draw.

    @see Path, Graphics::strokePath
*/
class JUCE_API  PathStrokeType
{
public:
    //==============================================================================
    /** The type of shape to use for the corners between two adjacent line segments. */
    enum JointStyle
    {
        mitered,    /**< Indicates that corners should be drawn with sharp joints.
                         Note that for angles that curve back on themselves, drawing a
                         mitre could require extending the point too far away from the
                         path, so a mitre limit is imposed and any corners that exceed it
                         are drawn as bevelled instead. */
        curved,     /**< Indicates that corners should be drawn as rounded-off. */
        beveled     /**< Indicates that corners should be drawn with a line flattening their
                         outside edge. */
    };

    /** The type shape to use for the ends of lines. */
    enum EndCapStyle
    {
        butt,       /**< Ends of lines are flat and don't extend beyond the end point. */
        square,     /**< Ends of lines are flat, but stick out beyond the end point for half
                         the thickness of the stroke. */
        rounded     /**< Ends of lines are rounded-off with a circular shape. */
    };

    //==============================================================================
    /** Creates a stroke type with a given line-width, and default joint/end styles. */
    explicit PathStrokeType (float strokeThickness) noexcept;

    /** Creates a stroke type.

        @param strokeThickness      the width of the line to use
        @param jointStyle           the type of joints to use for corners
        @param endStyle             the type of end-caps to use for the ends of open paths.
    */
    PathStrokeType (float strokeThickness,
                    JointStyle jointStyle,
                    EndCapStyle endStyle = butt) noexcept;

    /** Creates a copy of another stroke type. */
    PathStrokeType (const PathStrokeType&) noexcept;

    /** Copies another stroke onto this one. */
    PathStrokeType& operator= (const PathStrokeType&) noexcept;

    /** Destructor. */
    ~PathStrokeType() noexcept;

    //==============================================================================
    /** Applies this stroke type to a path and returns the resultant stroke as another Path.

        @param destPath         the resultant stroked outline shape will be copied into this path.
                                Note that it's ok for the source and destination Paths to be
                                the same object, so you can easily turn a path into a stroked version
                                of itself.
        @param sourcePath       the path to use as the source
        @param transform        an optional transform to apply to the points from the source path
                                as they are being used
        @param extraAccuracy    if this is greater than 1.0, it will subdivide the path to
                                a higher resolution, which improves the quality if you'll later want
                                to enlarge the stroked path. So for example, if you're planning on drawing
                                the stroke at 3x the size that you're creating it, you should set this to 3.

        @see createDashedStroke
    */
    void createStrokedPath (Path& destPath,
                            const Path& sourcePath,
                            const AffineTransform& transform = AffineTransform(),
                            float extraAccuracy = 1.0f) const;

    //==============================================================================
    /** Applies this stroke type to a path, creating a dashed line.

        This is similar to createStrokedPath, but uses the array passed in to
        break the stroke up into a series of dashes.

        @param destPath         the resultant stroked outline shape will be copied into this path.
                                Note that it's ok for the source and destination Paths to be
                                the same object, so you can easily turn a path into a stroked version
                                of itself.
        @param sourcePath       the path to use as the source
        @param dashLengths      An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
                                a line of length 2, then skip a length of 3, then add a line of length 4,
                                skip 5, and keep repeating this pattern.
        @param numDashLengths   The number of lengths in the dashLengths array. This should really be
                                an even number, otherwise the pattern will get out of step as it
                                repeats.
        @param transform        an optional transform to apply to the points from the source path
                                as they are being used
        @param extraAccuracy    if this is greater than 1.0, it will subdivide the path to
                                a higher resolution, which improves the quality if you'll later want
                                to enlarge the stroked path. So for example, if you're planning on drawing
                                the stroke at 3x the size that you're creating it, you should set this to 3.
    */
    void createDashedStroke (Path& destPath,
                             const Path& sourcePath,
                             const float* dashLengths,
                             int numDashLengths,
                             const AffineTransform& transform = AffineTransform(),
                             float extraAccuracy = 1.0f) const;

    //==============================================================================
    /** Applies this stroke type to a path and returns the resultant stroke as another Path.

        @param destPath             the resultant stroked outline shape will be copied into this path.
                                    Note that it's ok for the source and destination Paths to be
                                    the same object, so you can easily turn a path into a stroked version
                                    of itself.
        @param sourcePath           the path to use as the source
        @param arrowheadStartWidth  the width of the arrowhead at the start of the path
        @param arrowheadStartLength the length of the arrowhead at the start of the path
        @param arrowheadEndWidth    the width of the arrowhead at the end of the path
        @param arrowheadEndLength   the length of the arrowhead at the end of the path
        @param transform            an optional transform to apply to the points from the source path
                                    as they are being used
        @param extraAccuracy        if this is greater than 1.0, it will subdivide the path to
                                    a higher resolution, which improves the quality if you'll later want
                                    to enlarge the stroked path. So for example, if you're planning on drawing
                                    the stroke at 3x the size that you're creating it, you should set this to 3.
        @see createDashedStroke
    */
    void createStrokeWithArrowheads (Path& destPath,
                                     const Path& sourcePath,
                                     float arrowheadStartWidth, float arrowheadStartLength,
                                     float arrowheadEndWidth, float arrowheadEndLength,
                                     const AffineTransform& transform = AffineTransform(),
                                     float extraAccuracy = 1.0f) const;

    //==============================================================================
    /** Returns the stroke thickness. */
    float getStrokeThickness() const noexcept                   { return thickness; }

    /** Sets the stroke thickness. */
    void setStrokeThickness (float newThickness) noexcept       { thickness = newThickness; }

    /** Returns the joint style. */
    JointStyle getJointStyle() const noexcept                   { return jointStyle; }

    /** Sets the joint style. */
    void setJointStyle (JointStyle newStyle) noexcept           { jointStyle = newStyle; }

    /** Returns the end-cap style. */
    EndCapStyle getEndStyle() const noexcept                    { return endStyle; }

    /** Sets the end-cap style. */
    void setEndStyle (EndCapStyle newStyle) noexcept            { endStyle = newStyle; }

    //==============================================================================
    /** Compares the stroke thickness, joint and end styles of two stroke types. */
    bool operator== (const PathStrokeType&) const noexcept;

    /** Compares the stroke thickness, joint and end styles of two stroke types. */
    bool operator!= (const PathStrokeType&) const noexcept;

private:
    //==============================================================================
    float thickness;
    JointStyle jointStyle;
    EndCapStyle endStyle;

    JUCE_LEAK_DETECTOR (PathStrokeType)
};

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
/**
    Flattens a Path object into a series of straight-line sections.

    Use one of these to iterate through a Path object, and it will convert
    all the curves into line sections so it's easy to render or perform
    geometric operations on.

    @see Path
*/
class JUCE_API  PathFlatteningIterator  final
{
public:
    //==============================================================================
    /** Creates a PathFlatteningIterator.

        After creation, use the next() method to initialise the fields in the
        object with the first line's position.

        @param path         the path to iterate along
        @param transform    a transform to apply to each point in the path being iterated
        @param tolerance    the amount by which the curves are allowed to deviate from the lines
                            into which they are being broken down - a higher tolerance contains
                            less lines, so can be generated faster, but will be less smooth.
    */
    PathFlatteningIterator (const Path& path,
                            const AffineTransform& transform = AffineTransform(),
                            float tolerance = Path::defaultToleranceForMeasurement);

    /** Destructor. */
    ~PathFlatteningIterator();

    //==============================================================================
    /** Fetches the next line segment from the path.

        This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
        so that they describe the new line segment.

        @returns false when there are no more lines to fetch.
    */
    bool next();

    float x1;  /**< The x position of the start of the current line segment. */
    float y1;  /**< The y position of the start of the current line segment. */
    float x2;  /**< The x position of the end of the current line segment. */
    float y2;  /**< The y position of the end of the current line segment. */

    /** Indicates whether the current line segment is closing a sub-path.

        If the current line is the one that connects the end of a sub-path
        back to the start again, this will be true.
    */
    bool closesSubPath;

    /** The index of the current line within the current sub-path.

        E.g. you can use this to see whether the line is the first one in the
        subpath by seeing if it's 0.
    */
    int subPathIndex;

    /** Returns true if the current segment is the last in the current sub-path. */
    bool isLastInSubpath() const noexcept;

private:
    //==============================================================================
    const Path& path;
    const AffineTransform transform;
    float* points;
    const float toleranceSquared;
    float subPathCloseX = 0, subPathCloseY = 0;
    const bool isIdentityTransform;

    HeapBlock<float> stackBase { 32 };
    float* stackPos;
    size_t index = 0, stackSize = 32;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PathFlatteningIterator)
};

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
/**
    Represents a 2D affine-transformation matrix.

    An affine transformation is a transformation such as a rotation, scale, shear,
    resize or translation.

    These are used for various 2D transformation tasks, e.g. with Path objects.

    @see Path, Point, Line
*/
class JUCE_API  AffineTransform  final
{
public:
    //==============================================================================
    /** Creates an identity transform. */
    AffineTransform() noexcept;

    /** Creates a copy of another transform. */
    AffineTransform (const AffineTransform& other) noexcept;

    /** Creates a transform from a set of raw matrix values.

        The resulting matrix is:

            (mat00 mat01 mat02)
            (mat10 mat11 mat12)
            (  0     0     1  )
    */
    AffineTransform (float mat00, float mat01, float mat02,
                     float mat10, float mat11, float mat12) noexcept;

    /** Copies from another AffineTransform object */
    AffineTransform& operator= (const AffineTransform& other) noexcept;

    /** Compares two transforms. */
    bool operator== (const AffineTransform& other) const noexcept;

    /** Compares two transforms. */
    bool operator!= (const AffineTransform& other) const noexcept;

   #if JUCE_ALLOW_STATIC_NULL_VARIABLES
    /** A ready-to-use identity transform.
        Note that you should always avoid using a static variable like this, and
        prefer AffineTransform() or {} if you need a default-constructed instance.
    */
    static const AffineTransform identity;
   #endif

    //==============================================================================
    /** Transforms a 2D coordinate using this matrix. */
    template <typename ValueType>
    void transformPoint (ValueType& x, ValueType& y) const noexcept
    {
        const ValueType oldX = x;
        x = static_cast<ValueType> (mat00 * oldX + mat01 * y + mat02);
        y = static_cast<ValueType> (mat10 * oldX + mat11 * y + mat12);
    }

    /** Transforms two 2D coordinates using this matrix.
        This is just a shortcut for calling transformPoint() on each of these pairs of
        coordinates in turn. (And putting all the calculations into one function hopefully
        also gives the compiler a bit more scope for pipelining it).
    */
    template <typename ValueType>
    void transformPoints (ValueType& x1, ValueType& y1,
                          ValueType& x2, ValueType& y2) const noexcept
    {
        const ValueType oldX1 = x1, oldX2 = x2;
        x1 = static_cast<ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
        y1 = static_cast<ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
        x2 = static_cast<ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
        y2 = static_cast<ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
    }

    /** Transforms three 2D coordinates using this matrix.
        This is just a shortcut for calling transformPoint() on each of these pairs of
        coordinates in turn. (And putting all the calculations into one function hopefully
        also gives the compiler a bit more scope for pipelining it).
    */
    template <typename ValueType>
    void transformPoints (ValueType& x1, ValueType& y1,
                          ValueType& x2, ValueType& y2,
                          ValueType& x3, ValueType& y3) const noexcept
    {
        const ValueType oldX1 = x1, oldX2 = x2, oldX3 = x3;
        x1 = static_cast<ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
        y1 = static_cast<ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
        x2 = static_cast<ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
        y2 = static_cast<ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
        x3 = static_cast<ValueType> (mat00 * oldX3 + mat01 * y3 + mat02);
        y3 = static_cast<ValueType> (mat10 * oldX3 + mat11 * y3 + mat12);
    }

    //==============================================================================
    /** Returns a new transform which is the same as this one followed by a translation. */
    AffineTransform translated (float deltaX,
                                float deltaY) const noexcept;

    /** Returns a new transform which is the same as this one followed by a translation. */
    template <typename PointType>
    AffineTransform translated (PointType delta) const noexcept
    {
        return translated ((float) delta.x, (float) delta.y);
    }

    /** Returns a new transform which is a translation. */
    static AffineTransform translation (float deltaX,
                                        float deltaY) noexcept;

    /** Returns a new transform which is a translation. */
    template <typename PointType>
    static AffineTransform translation (PointType delta) noexcept
    {
        return translation ((float) delta.x, (float) delta.y);
    }

    /** Returns a copy of this transform with the specified translation matrix values. */
    AffineTransform withAbsoluteTranslation (float translationX,
                                             float translationY) const noexcept;

    /** Returns a transform which is the same as this one followed by a rotation.

        The rotation is specified by a number of radians to rotate clockwise, centred around
        the origin (0, 0).
    */
    AffineTransform rotated (float angleInRadians) const noexcept;

    /** Returns a transform which is the same as this one followed by a rotation about a given point.

        The rotation is specified by a number of radians to rotate clockwise, centred around
        the coordinates passed in.
    */
    AffineTransform rotated (float angleInRadians,
                             float pivotX,
                             float pivotY) const noexcept;

    /** Returns a new transform which is a rotation about (0, 0). */
    static AffineTransform rotation (float angleInRadians) noexcept;

    /** Returns a new transform which is a rotation about a given point. */
    static AffineTransform rotation (float angleInRadians,
                                     float pivotX,
                                     float pivotY) noexcept;

    /** Returns a transform which is the same as this one followed by a re-scaling.
        The scaling is centred around the origin (0, 0).
    */
    AffineTransform scaled (float factorX,
                            float factorY) const noexcept;

    /** Returns a transform which is the same as this one followed by a re-scaling.
        The scaling is centred around the origin (0, 0).
    */
    AffineTransform scaled (float factor) const noexcept;

    /** Returns a transform which is the same as this one followed by a re-scaling.
        The scaling is centred around the origin provided.
    */
    AffineTransform scaled (float factorX, float factorY,
                            float pivotX, float pivotY) const noexcept;

    /** Returns a new transform which is a re-scale about the origin. */
    static AffineTransform scale (float factorX,
                                  float factorY) noexcept;

    /** Returns a new transform which is a re-scale about the origin. */
    static AffineTransform scale (float factor) noexcept;

    /** Returns a new transform which is a re-scale centred around the point provided. */
    static AffineTransform scale (float factorX, float factorY,
                                  float pivotX, float pivotY) noexcept;

    /** Returns a transform which is the same as this one followed by a shear.
        The shear is centred around the origin (0, 0).
    */
    AffineTransform sheared (float shearX, float shearY) const noexcept;

    /** Returns a shear transform, centred around the origin (0, 0). */
    static AffineTransform shear (float shearX, float shearY) noexcept;

    /** Returns a transform that will flip coordinates vertically within a window of the given height.
        This is handy for converting between upside-down coordinate systems such as OpenGL or CoreGraphics.
    */
    static AffineTransform verticalFlip (float height) noexcept;

    /** Returns a matrix which is the inverse operation of this one.

        Some matrices don't have an inverse - in this case, the method will just return
        an identity transform.
    */
    AffineTransform inverted() const noexcept;

    /** Returns the transform that will map three known points onto three coordinates
        that are supplied.

        This returns the transform that will transform (0, 0) into (x00, y00),
        (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
    */
    static AffineTransform fromTargetPoints (float x00, float y00,
                                             float x10, float y10,
                                             float x01, float y01) noexcept;

    /** Returns the transform that will map three specified points onto three target points. */
    static AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
                                             float sourceX2, float sourceY2, float targetX2, float targetY2,
                                             float sourceX3, float sourceY3, float targetX3, float targetY3) noexcept;

    //==============================================================================
    /** Returns the result of concatenating another transformation after this one. */
    AffineTransform followedBy (const AffineTransform& other) const noexcept;

    /** Returns true if this transform has no effect on points. */
    bool isIdentity() const noexcept;

    /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
    bool isSingularity() const noexcept;

    /** Returns true if the transform only translates, and doesn't scale or rotate the
        points. */
    bool isOnlyTranslation() const noexcept;

    /** If this transform is only a translation, this returns the X offset.
        @see isOnlyTranslation
    */
    float getTranslationX() const noexcept                  { return mat02; }

    /** If this transform is only a translation, this returns the X offset.
        @see isOnlyTranslation
    */
    float getTranslationY() const noexcept                  { return mat12; }

    /** Returns the approximate scale factor by which lengths will be transformed.
        Obviously a length may be scaled by entirely different amounts depending on its
        direction, so this is only appropriate as a rough guide.
    */
    float getScaleFactor() const noexcept;

    //==============================================================================
    /* The transform matrix is:

        (mat00 mat01 mat02)
        (mat10 mat11 mat12)
        (  0     0     1  )
    */
    float mat00, mat01, mat02;
    float mat10, mat11, mat12;
};

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

PathStrokeType::PathStrokeType (float strokeThickness) noexcept
    : thickness (strokeThickness), jointStyle (mitered), endStyle (butt)
{
}

PathStrokeType::PathStrokeType (float strokeThickness, JointStyle joint, EndCapStyle end) noexcept
    : thickness (strokeThickness), jointStyle (joint), endStyle (end)
{
}

PathStrokeType::PathStrokeType (const PathStrokeType& other) noexcept
    : thickness (other.thickness),
      jointStyle (other.jointStyle),
      endStyle (other.endStyle)
{
}

PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) noexcept
{
    thickness = other.thickness;
    jointStyle = other.jointStyle;
    endStyle = other.endStyle;
    return *this;
}

PathStrokeType::~PathStrokeType() noexcept
{
}

bool PathStrokeType::operator== (const PathStrokeType& other) const noexcept
{
    return thickness == other.thickness
        && jointStyle == other.jointStyle
        && endStyle == other.endStyle;
}

bool PathStrokeType::operator!= (const PathStrokeType& other) const noexcept
{
    return ! operator== (other);
}

//==============================================================================
namespace PathStrokeHelpers
{
    static bool lineIntersection (const float x1, const float y1,
                                  const float x2, const float y2,
                                  const float x3, const float y3,
                                  const float x4, const float y4,
                                  float& intersectionX,
                                  float& intersectionY,
                                  float& distanceBeyondLine1EndSquared) noexcept
    {
        if (x2 != x3 || y2 != y3)
        {
            auto dx1 = x2 - x1;
            auto dy1 = y2 - y1;
            auto dx2 = x4 - x3;
            auto dy2 = y4 - y3;
            auto divisor = dx1 * dy2 - dx2 * dy1;

            if (divisor == 0.0f)
            {
                if (! ((dx1 == 0.0f && dy1 == 0.0f) || (dx2 == 0.0f && dy2 == 0.0f)))
                {
                    if (dy1 == 0.0f && dy2 != 0.0f)
                    {
                        auto along = (y1 - y3) / dy2;
                        intersectionX = x3 + along * dx2;
                        intersectionY = y1;

                        distanceBeyondLine1EndSquared = intersectionX - x2;
                        distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
                        if ((x2 > x1) == (intersectionX < x2))
                            distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;

                        return along >= 0 && along <= 1.0f;
                    }

                    if (dy2 == 0.0f && dy1 != 0.0f)
                    {
                        auto along = (y3 - y1) / dy1;
                        intersectionX = x1 + along * dx1;
                        intersectionY = y3;

                        distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
                        distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
                        if (along < 1.0f)
                            distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;

                        return along >= 0 && along <= 1.0f;
                    }

                    if (dx1 == 0.0f && dx2 != 0.0f)
                    {
                        auto along = (x1 - x3) / dx2;
                        intersectionX = x1;
                        intersectionY = y3 + along * dy2;

                        distanceBeyondLine1EndSquared = intersectionY - y2;
                        distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;

                        if ((y2 > y1) == (intersectionY < y2))
                            distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;

                        return along >= 0 && along <= 1.0f;
                    }

                    if (dx2 == 0.0f && dx1 != 0.0f)
                    {
                        auto along = (x3 - x1) / dx1;
                        intersectionX = x3;
                        intersectionY = y1 + along * dy1;

                        distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
                        distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
                        if (along < 1.0f)
                            distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;

                        return along >= 0 && along <= 1.0f;
                    }
                }

                intersectionX = 0.5f * (x2 + x3);
                intersectionY = 0.5f * (y2 + y3);

                distanceBeyondLine1EndSquared = 0.0f;
                return false;
            }

            auto along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;

            intersectionX = x1 + along1 * dx1;
            intersectionY = y1 + along1 * dy1;

            if (along1 >= 0 && along1 <= 1.0f)
            {
                auto along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1) / divisor;

                if (along2 >= 0 && along2 <= 1.0f)
                {
                    distanceBeyondLine1EndSquared = 0.0f;
                    return true;
                }
            }

            distanceBeyondLine1EndSquared = along1 - 1.0f;
            distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
            distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);

            if (along1 < 1.0f)
                distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;

            return false;
        }

        intersectionX = x2;
        intersectionY = y2;

        distanceBeyondLine1EndSquared = 0.0f;
        return true;
    }

    static void addEdgeAndJoint (Path& destPath,
                                 const PathStrokeType::JointStyle style,
                                 const float maxMiterExtensionSquared, const float width,
                                 const float x1, const float y1,
                                 const float x2, const float y2,
                                 const float x3, const float y3,
                                 const float x4, const float y4,
                                 const float midX, const float midY)
    {
        if (style == PathStrokeType::beveled
            || (x3 == x4 && y3 == y4)
            || (x1 == x2 && y1 == y2))
        {
            destPath.lineTo (x2, y2);
            destPath.lineTo (x3, y3);
        }
        else
        {
            float jx, jy, distanceBeyondLine1EndSquared;

            // if they intersect, use this point..
            if (lineIntersection (x1, y1, x2, y2,
                                  x3, y3, x4, y4,
                                  jx, jy, distanceBeyondLine1EndSquared))
            {
                destPath.lineTo (jx, jy);
            }
            else
            {
                if (style == PathStrokeType::mitered)
                {
                    if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
                        && distanceBeyondLine1EndSquared > 0.0f)
                    {
                        destPath.lineTo (jx, jy);
                    }
                    else
                    {
                        // the end sticks out too far, so just use a blunt joint
                        destPath.lineTo (x2, y2);
                        destPath.lineTo (x3, y3);
                    }
                }
                else
                {
                    // curved joints
                    float angle1 = std::atan2 (x2 - midX, y2 - midY);
                    float angle2 = std::atan2 (x3 - midX, y3 - midY);
                    const float angleIncrement = 0.1f;

                    destPath.lineTo (x2, y2);

                    if (std::abs (angle1 - angle2) > angleIncrement)
                    {
                        if (angle2 > angle1 + float_Pi
                             || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
                        {
                            if (angle2 > angle1)
                                angle2 -= float_Pi * 2.0f;

                            jassert (angle1 <= angle2 + float_Pi);

                            angle1 -= angleIncrement;
                            while (angle1 > angle2)
                            {
                                destPath.lineTo (midX + width * std::sin (angle1),
                                                 midY + width * std::cos (angle1));

                                angle1 -= angleIncrement;
                            }
                        }
                        else
                        {
                            if (angle1 > angle2)
                                angle1 -= float_Pi * 2.0f;

                            jassert (angle1 >= angle2 - float_Pi);

                            angle1 += angleIncrement;
                            while (angle1 < angle2)
                            {
                                destPath.lineTo (midX + width * std::sin (angle1),
                                                 midY + width * std::cos (angle1));

                                angle1 += angleIncrement;
                            }
                        }
                    }

                    destPath.lineTo (x3, y3);
                }
            }
        }
    }

    static void addLineEnd (Path& destPath,
                            const PathStrokeType::EndCapStyle style,
                            const float x1, const float y1,
                            const float x2, const float y2,
                            const float width)
    {
        if (style == PathStrokeType::butt)
        {
            destPath.lineTo (x2, y2);
        }
        else
        {
            float offx1, offy1, offx2, offy2;

            auto dx = x2 - x1;
            auto dy = y2 - y1;
            auto len = juce_hypot (dx, dy);

            if (len == 0.0f)
            {
                offx1 = offx2 = x1;
                offy1 = offy2 = y1;
            }
            else
            {
                auto offset = width / len;
                dx *= offset;
                dy *= offset;

                offx1 = x1 + dy;
                offy1 = y1 - dx;
                offx2 = x2 + dy;
                offy2 = y2 - dx;
            }

            if (style == PathStrokeType::square)
            {
                // square ends
                destPath.lineTo (offx1, offy1);
                destPath.lineTo (offx2, offy2);
                destPath.lineTo (x2, y2);
            }
            else
            {
                // rounded ends
                auto midx = (offx1 + offx2) * 0.5f;
                auto midy = (offy1 + offy2) * 0.5f;

                destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
                                  offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
                                  midx, midy);

                destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
                                  offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
                                  x2, y2);
            }
        }
    }

    struct Arrowhead
    {
        float startWidth, startLength;
        float endWidth, endLength;
    };

    static void addArrowhead (Path& destPath,
                              const float x1, const float y1,
                              const float x2, const float y2,
                              const float tipX, const float tipY,
                              const float width,
                              const float arrowheadWidth)
    {
        Line<float> line (x1, y1, x2, y2);
        destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
        destPath.lineTo (tipX, tipY);
        destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
        destPath.lineTo (x2, y2);
    }

    struct LineSection
    {
        float x1, y1, x2, y2;      // original line
        float lx1, ly1, lx2, ly2;  // the left-hand stroke
        float rx1, ry1, rx2, ry2;  // the right-hand stroke
    };

    static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
    {
        while (amountAtEnd > 0 && subPath.size() > 0)
        {
            auto& l = subPath.getReference (subPath.size() - 1);
            auto dx = l.rx2 - l.rx1;
            auto dy = l.ry2 - l.ry1;
            auto len = juce_hypot (dx, dy);

            if (len <= amountAtEnd && subPath.size() > 1)
            {
                LineSection& prev = subPath.getReference (subPath.size() - 2);
                prev.x2 = l.x2;
                prev.y2 = l.y2;
                subPath.removeLast();
                amountAtEnd -= len;
            }
            else
            {
                auto prop = jmin (0.9999f, amountAtEnd / len);
                dx *= prop;
                dy *= prop;
                l.rx1 += dx;
                l.ry1 += dy;
                l.lx2 += dx;
                l.ly2 += dy;
                break;
            }
        }

        while (amountAtStart > 0 && subPath.size() > 0)
        {
            auto& l = subPath.getReference (0);
            auto dx = l.rx2 - l.rx1;
            auto dy = l.ry2 - l.ry1;
            auto len = juce_hypot (dx, dy);

            if (len <= amountAtStart && subPath.size() > 1)
            {
                LineSection& next = subPath.getReference (1);
                next.x1 = l.x1;
                next.y1 = l.y1;
                subPath.remove (0);
                amountAtStart -= len;
            }
            else
            {
                auto prop = jmin (0.9999f, amountAtStart / len);
                dx *= prop;
                dy *= prop;
                l.rx2 -= dx;
                l.ry2 -= dy;
                l.lx1 -= dx;
                l.ly1 -= dy;
                break;
            }
        }
    }

    static void addSubPath (Path& destPath, Array<LineSection>& subPath,
                            const bool isClosed, const float width, const float maxMiterExtensionSquared,
                            const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
                            const Arrowhead* const arrowhead)
    {
        jassert (subPath.size() > 0);

        if (arrowhead != nullptr)
            shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);

        auto& firstLine = subPath.getReference (0);

        auto lastX1 = firstLine.lx1;
        auto lastY1 = firstLine.ly1;
        auto lastX2 = firstLine.lx2;
        auto lastY2 = firstLine.ly2;

        if (isClosed)
        {
            destPath.startNewSubPath (lastX1, lastY1);
        }
        else
        {
            destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);

            if (arrowhead != nullptr && arrowhead->startWidth > 0.0f)
                addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
                              width, arrowhead->startWidth);
            else
                addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
        }

        for (int i = 1; i < subPath.size(); ++i)
        {
            const LineSection& l = subPath.getReference (i);

            addEdgeAndJoint (destPath, jointStyle,
                             maxMiterExtensionSquared, width,
                             lastX1, lastY1, lastX2, lastY2,
                             l.lx1, l.ly1, l.lx2, l.ly2,
                             l.x1, l.y1);

            lastX1 = l.lx1;
            lastY1 = l.ly1;
            lastX2 = l.lx2;
            lastY2 = l.ly2;
        }

        auto& lastLine = subPath.getReference (subPath.size() - 1);

        if (isClosed)
        {
            auto& l = subPath.getReference (0);

            addEdgeAndJoint (destPath, jointStyle,
                             maxMiterExtensionSquared, width,
                             lastX1, lastY1, lastX2, lastY2,
                             l.lx1, l.ly1, l.lx2, l.ly2,
                             l.x1, l.y1);

            destPath.closeSubPath();
            destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
        }
        else
        {
            destPath.lineTo (lastX2, lastY2);

            if (arrowhead != nullptr && arrowhead->endWidth > 0.0f)
                addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
                              width, arrowhead->endWidth);
            else
                addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
        }

        lastX1 = lastLine.rx1;
        lastY1 = lastLine.ry1;
        lastX2 = lastLine.rx2;
        lastY2 = lastLine.ry2;

        for (int i = subPath.size() - 1; --i >= 0;)
        {
            auto& l = subPath.getReference (i);

            addEdgeAndJoint (destPath, jointStyle,
                             maxMiterExtensionSquared, width,
                             lastX1, lastY1, lastX2, lastY2,
                             l.rx1, l.ry1, l.rx2, l.ry2,
                             l.x2, l.y2);

            lastX1 = l.rx1;
            lastY1 = l.ry1;
            lastX2 = l.rx2;
            lastY2 = l.ry2;
        }

        if (isClosed)
        {
            addEdgeAndJoint (destPath, jointStyle,
                             maxMiterExtensionSquared, width,
                             lastX1, lastY1, lastX2, lastY2,
                             lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
                             lastLine.x2, lastLine.y2);
        }
        else
        {
            // do the last line
            destPath.lineTo (lastX2, lastY2);
        }

        destPath.closeSubPath();
    }

    static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
                              const PathStrokeType::EndCapStyle endStyle,
                              Path& destPath, const Path& source,
                              const AffineTransform& transform,
                              const float extraAccuracy, const Arrowhead* const arrowhead)
    {
        jassert (extraAccuracy > 0);

        if (thickness <= 0)
        {
            destPath.clear();
            return;
        }

        const Path* sourcePath = &source;
        Path temp;

        if (sourcePath == &destPath)
        {
            destPath.swapWithPath (temp);
            sourcePath = &temp;
        }
        else
        {
            destPath.clear();
        }

        destPath.setUsingNonZeroWinding (true);

        const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
        const float width = 0.5f * thickness;

        // Iterate the path, creating a list of the
        // left/right-hand lines along either side of it...
        PathFlatteningIterator it (*sourcePath, transform, Path::defaultToleranceForMeasurement / extraAccuracy);

        Array<LineSection> subPath;
        subPath.ensureStorageAllocated (512);
        LineSection l;
        l.x1 = 0;
        l.y1 = 0;

        const float minSegmentLength = 0.0001f;

        while (it.next())
        {
            if (it.subPathIndex == 0)
            {
                if (subPath.size() > 0)
                {
                    addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
                    subPath.clearQuick();
                }

                l.x1 = it.x1;
                l.y1 = it.y1;
            }

            l.x2 = it.x2;
            l.y2 = it.y2;

            float dx = l.x2 - l.x1;
            float dy = l.y2 - l.y1;

            auto hypotSquared = dx * dx + dy * dy;

            if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
            {
                auto len = std::sqrt (hypotSquared);

                if (len == 0.0f)
                {
                    l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
                    l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
                }
                else
                {
                    auto offset = width / len;
                    dx *= offset;
                    dy *= offset;

                    l.rx2 = l.x1 - dy;
                    l.ry2 = l.y1 + dx;
                    l.lx1 = l.x1 + dy;
                    l.ly1 = l.y1 - dx;

                    l.lx2 = l.x2 + dy;
                    l.ly2 = l.y2 - dx;
                    l.rx1 = l.x2 - dy;
                    l.ry1 = l.y2 + dx;
                }

                subPath.add (l);

                if (it.closesSubPath)
                {
                    addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
                    subPath.clearQuick();
                }
                else
                {
                    l.x1 = it.x2;
                    l.y1 = it.y2;
                }
            }
        }

        if (subPath.size() > 0)
            addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
    }
}

void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
                                        const AffineTransform& transform, const float extraAccuracy) const
{
    PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
                                     transform, extraAccuracy, 0);
}

void PathStrokeType::createDashedStroke (Path& destPath,
                                         const Path& sourcePath,
                                         const float* dashLengths,
                                         int numDashLengths,
                                         const AffineTransform& transform,
                                         const float extraAccuracy) const
{
    jassert (extraAccuracy > 0);

    if (thickness <= 0)
        return;

    Path newDestPath;
    PathFlatteningIterator it (sourcePath, transform, Path::defaultToleranceForMeasurement / extraAccuracy);

    bool first = true;
    int dashNum = 0;
    float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
    float dx = 0.0f, dy = 0.0f;

    for (;;)
    {
        const bool isSolid = ((dashNum & 1) == 0);
        const float dashLen = dashLengths [dashNum++ % numDashLengths];

        jassert (dashLen >= 0); // must be a positive increment!
        if (dashLen <= 0)
            continue;

        pos += dashLen;

        while (pos > lineEndPos)
        {
            if (! it.next())
            {
                if (isSolid && ! first)
                    newDestPath.lineTo (it.x2, it.y2);

                createStrokedPath (destPath, newDestPath, AffineTransform(), extraAccuracy);
                return;
            }

            if (isSolid && ! first)
                newDestPath.lineTo (it.x1, it.y1);
            else
                newDestPath.startNewSubPath (it.x1, it.y1);

            dx = it.x2 - it.x1;
            dy = it.y2 - it.y1;
            lineLen = juce_hypot (dx, dy);
            lineEndPos += lineLen;
            first = it.closesSubPath;
        }

        const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;

        if (isSolid)
            newDestPath.lineTo (it.x1 + dx * alpha,
                                it.y1 + dy * alpha);
        else
            newDestPath.startNewSubPath (it.x1 + dx * alpha,
                                         it.y1 + dy * alpha);
    }
}

void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
                                                 const Path& sourcePath,
                                                 const float arrowheadStartWidth, const float arrowheadStartLength,
                                                 const float arrowheadEndWidth, const float arrowheadEndLength,
                                                 const AffineTransform& transform,
                                                 const float extraAccuracy) const
{
    PathStrokeHelpers::Arrowhead head;
    head.startWidth = arrowheadStartWidth;
    head.startLength = arrowheadStartLength;
    head.endWidth = arrowheadEndWidth;
    head.endLength = arrowheadEndLength;

    PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
                                     destPath, sourcePath, transform, extraAccuracy, &head);
}

} // namespace juce


text:
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

//==============================================================================
/**
    A table of horizontal scan-line segments - used for rasterising Paths.

    @see Path, Graphics
*/
class JUCE_API  EdgeTable
{
public:
    //==============================================================================
    /** Creates an edge table containing a path.

        A table is created with a fixed vertical range, and only sections of the path
        which lie within this range will be added to the table.

        @param clipLimits               only the region of the path that lies within this area will be added
        @param pathToAdd                the path to add to the table
        @param transform                a transform to apply to the path being added
    */
    EdgeTable (Rectangle<int> clipLimits,
               const Path& pathToAdd,
               const AffineTransform& transform);

    /** Creates an edge table containing a rectangle. */
    explicit EdgeTable (Rectangle<int> rectangleToAdd);

    /** Creates an edge table containing a rectangle. */
    explicit EdgeTable (Rectangle<float> rectangleToAdd);

    /** Creates an edge table containing a rectangle list. */
    explicit EdgeTable (const RectangleList<int>& rectanglesToAdd);

    /** Creates an edge table containing a rectangle list. */
    explicit EdgeTable (const RectangleList<float>& rectanglesToAdd);

    /** Creates a copy of another edge table. */
    EdgeTable (const EdgeTable&);

    /** Copies from another edge table. */
    EdgeTable& operator= (const EdgeTable&);

    /** Destructor. */
    ~EdgeTable();

    //==============================================================================
    void clipToRectangle (const Rectangle<int>& r);
    void excludeRectangle (const Rectangle<int>& r);
    void clipToEdgeTable (const EdgeTable&);
    void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels);
    bool isEmpty() noexcept;
    const Rectangle<int>& getMaximumBounds() const noexcept      { return bounds; }
    void translate (float dx, int dy) noexcept;

    /** Scales all the alpha-levels in the table by the given multiplier. */
    void multiplyLevels (float factor);

    /** Reduces the amount of space the table has allocated.

        This will shrink the table down to use as little memory as possible - useful for
        read-only tables that get stored and re-used for rendering.
    */
    void optimiseTable();

    //==============================================================================
    /** Iterates the lines in the table, for rendering.

        This function will iterate each line in the table, and call a user-defined class
        to render each pixel or continuous line of pixels that the table contains.

        @param iterationCallback    this templated class must contain the following methods:
                                        @code
                                        inline void setEdgeTableYPos (int y);
                                        inline void handleEdgeTablePixel (int x, int alphaLevel) const;
                                        inline void handleEdgeTablePixelFull (int x) const;
                                        inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
                                        inline void handleEdgeTableLineFull (int x, int width) const;
                                        @endcode
                                        (these don't necessarily have to be 'const', but it might help it go faster)
    */
    template <class EdgeTableIterationCallback>
    void iterate (EdgeTableIterationCallback& iterationCallback) const noexcept
    {
        const int* lineStart = table;

        for (int y = 0; y < bounds.getHeight(); ++y)
        {
            const int* line = lineStart;
            lineStart += lineStrideElements;
            int numPoints = line[0];

            if (--numPoints > 0)
            {
                int x = *++line;
                jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
                int levelAccumulator = 0;

                iterationCallback.setEdgeTableYPos (bounds.getY() + y);

                while (--numPoints >= 0)
                {
                    const int level = *++line;
                    jassert (isPositiveAndBelow (level, 256));
                    const int endX = *++line;
                    jassert (endX >= x);
                    const int endOfRun = (endX >> 8);

                    if (endOfRun == (x >> 8))
                    {
                        // small segment within the same pixel, so just save it for the next
                        // time round..
                        levelAccumulator += (endX - x) * level;
                    }
                    else
                    {
                        // plot the fist pixel of this segment, including any accumulated
                        // levels from smaller segments that haven't been drawn yet
                        levelAccumulator += (0x100 - (x & 0xff)) * level;
                        levelAccumulator >>= 8;
                        x >>= 8;

                        if (levelAccumulator > 0)
                        {
                            if (levelAccumulator >= 255)
                                iterationCallback.handleEdgeTablePixelFull (x);
                            else
                                iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
                        }

                        // if there's a run of similar pixels, do it all in one go..
                        if (level > 0)
                        {
                            jassert (endOfRun <= bounds.getRight());
                            const int numPix = endOfRun - ++x;

                            if (numPix > 0)
                                iterationCallback.handleEdgeTableLine (x, numPix, level);
                        }

                        // save the bit at the end to be drawn next time round the loop.
                        levelAccumulator = (endX & 0xff) * level;
                    }

                    x = endX;
                }

                levelAccumulator >>= 8;

                if (levelAccumulator > 0)
                {
                    x >>= 8;
                    jassert (x >= bounds.getX() && x < bounds.getRight());

                    if (levelAccumulator >= 255)
                        iterationCallback.handleEdgeTablePixelFull (x);
                    else
                        iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
                }
            }
        }
    }

private:
    //==============================================================================
    // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
    struct LineItem
    {
        int x, level;

        bool operator< (const LineItem& other) const noexcept   { return x < other.x; }
    };

    HeapBlock<int> table;
    Rectangle<int> bounds;
    int maxEdgesPerLine, lineStrideElements;
    bool needToCheckEmptiness = true;

    void allocate();
    void clearLineSizes() noexcept;
    void addEdgePoint (int x, int y, int winding);
    void addEdgePointPair (int x1, int x2, int y, int winding);
    void remapTableForNumEdges (int newNumEdgesPerLine);
    void remapWithExtraSpace (int numPointsNeeded);
    void intersectWithEdgeTableLine (int y, const int* otherLine);
    void clipEdgeTableLineToRange (int* line, int x1, int x2) noexcept;
    void sanitiseLevels (bool useNonZeroWinding) noexcept;
    static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) noexcept;

    JUCE_LEAK_DETECTOR (EdgeTable)
};

} // namespace juce