адаптация s13bby/osc под vst и gui. (вайбкод)

вайбкод потому что мне в моменте стало понятно. что проще было сразу писать на фреймворке JUCE, чем адаптировать консольное приложение на MiniAudio.
обновляться данный репозиторий не будет. СmakeLists адаптирован онли под linux.
This commit is contained in:
s13bby committed 2026-11-20 14:52:33 +06:00
1 parent 8384123f87
commit b0a75e98db
10387 files changed
+4025195

No files matched your search

@@ -0,0 +1,771 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
namespace ColourHelpers
{
static uint8 floatToUInt8 (float n) noexcept
{
return n <= 0.0f ? 0 : (n >= 1.0f ? 255 : (uint8) roundToInt (n * 255.0f));
}
static float getHue (Colour col)
{
auto r = (int) col.getRed();
auto g = (int) col.getGreen();
auto b = (int) col.getBlue();
auto hi = jmax (r, g, b);
auto lo = jmin (r, g, b);
float hue = 0.0f;
if (hi > 0 && ! exactlyEqual (hi, lo))
{
auto invDiff = 1.0f / (float) (hi - lo);
auto red = (float) (hi - r) * invDiff;
auto green = (float) (hi - g) * invDiff;
auto blue = (float) (hi - b) * invDiff;
if (r == hi) hue = blue - green;
else if (g == hi) hue = 2.0f + red - blue;
else hue = 4.0f + green - red;
hue *= 1.0f / 6.0f;
if (hue < 0.0f)
hue += 1.0f;
}
return hue;
}
//==============================================================================
struct HSL
{
HSL (Colour col) noexcept
{
auto r = (int) col.getRed();
auto g = (int) col.getGreen();
auto b = (int) col.getBlue();
auto hi = jmax (r, g, b);
auto lo = jmin (r, g, b);
if (hi < 0)
return;
lightness = ((float) (hi + lo) / 2.0f) / 255.0f;
if (lightness <= 0.0f)
return;
hue = getHue (col);
if (1.0f <= lightness)
return;
auto denominator = 1.0f - std::abs ((2.0f * lightness) - 1.0f);
saturation = ((float) (hi - lo) / 255.0f) / denominator;
}
Colour toColour (Colour original) const noexcept
{
return Colour::fromHSL (hue, saturation, lightness, original.getAlpha());
}
static PixelARGB toRGB (float h, float s, float l, uint8 alpha) noexcept
{
auto v = l < 0.5f ? l * (1.0f + s) : l + s - (l * s);
if (approximatelyEqual (v, 0.0f))
return PixelARGB (alpha, 0, 0, 0);
auto min = (2.0f * l) - v;
auto sv = (v - min) / v;
h = ((h - std::floor (h)) * 360.0f) / 60.0f;
auto f = h - std::floor (h);
auto vsf = v * sv * f;
auto mid1 = min + vsf;
auto mid2 = v - vsf;
if (h < 1.0f) return PixelARGB (alpha, floatToUInt8 (v), floatToUInt8 (mid1), floatToUInt8 (min));
else if (h < 2.0f) return PixelARGB (alpha, floatToUInt8 (mid2), floatToUInt8 (v), floatToUInt8 (min));
else if (h < 3.0f) return PixelARGB (alpha, floatToUInt8 (min), floatToUInt8 (v), floatToUInt8 (mid1));
else if (h < 4.0f) return PixelARGB (alpha, floatToUInt8 (min), floatToUInt8 (mid2), floatToUInt8 (v));
else if (h < 5.0f) return PixelARGB (alpha, floatToUInt8 (mid1), floatToUInt8 (min), floatToUInt8 (v));
else if (h < 6.0f) return PixelARGB (alpha, floatToUInt8 (v), floatToUInt8 (min), floatToUInt8 (mid2));
return PixelARGB (alpha, 0, 0, 0);
}
float hue = 0.0f, saturation = 0.0f, lightness = 0.0f;
};
//==============================================================================
struct HSB
{
HSB (Colour col) noexcept
{
auto r = (int) col.getRed();
auto g = (int) col.getGreen();
auto b = (int) col.getBlue();
auto hi = jmax (r, g, b);
auto lo = jmin (r, g, b);
if (hi > 0)
{
saturation = (float) (hi - lo) / (float) hi;
if (saturation > 0.0f)
hue = getHue (col);
brightness = (float) hi / 255.0f;
}
}
Colour toColour (Colour original) const noexcept
{
return Colour (hue, saturation, brightness, original.getAlpha());
}
static PixelARGB toRGB (float h, float s, float v, uint8 alpha) noexcept
{
v = jlimit (0.0f, 255.0f, v * 255.0f);
auto intV = (uint8) roundToInt (v);
if (s <= 0)
return PixelARGB (alpha, intV, intV, intV);
s = jmin (1.0f, s);
h = ((h - std::floor (h)) * 360.0f) / 60.0f;
auto f = h - std::floor (h);
auto x = (uint8) roundToInt (v * (1.0f - s));
if (h < 1.0f) return PixelARGB (alpha, intV, (uint8) roundToInt (v * (1.0f - (s * (1.0f - f)))), x);
if (h < 2.0f) return PixelARGB (alpha, (uint8) roundToInt (v * (1.0f - s * f)), intV, x);
if (h < 3.0f) return PixelARGB (alpha, x, intV, (uint8) roundToInt (v * (1.0f - (s * (1.0f - f)))));
if (h < 4.0f) return PixelARGB (alpha, x, (uint8) roundToInt (v * (1.0f - s * f)), intV);
if (h < 5.0f) return PixelARGB (alpha, (uint8) roundToInt (v * (1.0f - (s * (1.0f - f)))), x, intV);
return PixelARGB (alpha, intV, x, (uint8) roundToInt (v * (1.0f - s * f)));
}
float hue = 0.0f, saturation = 0.0f, brightness = 0.0f;
};
//==============================================================================
struct YIQ
{
YIQ (Colour c) noexcept
{
auto r = c.getFloatRed();
auto g = c.getFloatGreen();
auto b = c.getFloatBlue();
y = 0.2999f * r + 0.5870f * g + 0.1140f * b;
i = 0.5957f * r - 0.2744f * g - 0.3212f * b;
q = 0.2114f * r - 0.5225f * g - 0.3113f * b;
alpha = c.getFloatAlpha();
}
Colour toColour() const noexcept
{
return Colour::fromFloatRGBA (y + 0.9563f * i + 0.6210f * q,
y - 0.2721f * i - 0.6474f * q,
y - 1.1070f * i + 1.7046f * q,
alpha);
}
float y = 0.0f, i = 0.0f, q = 0.0f, alpha = 0.0f;
};
}
//==============================================================================
bool Colour::operator== (const Colour& other) const noexcept { return argb.getNativeARGB() == other.argb.getNativeARGB(); }
bool Colour::operator!= (const Colour& other) const noexcept { return argb.getNativeARGB() != other.argb.getNativeARGB(); }
//==============================================================================
Colour::Colour (uint32 col) noexcept
: argb (static_cast<uint8> ((col >> 24) & 0xff),
static_cast<uint8> ((col >> 16) & 0xff),
static_cast<uint8> ((col >> 8) & 0xff),
static_cast<uint8> (col & 0xff))
{
}
Colour::Colour (uint8 red, uint8 green, uint8 blue) noexcept
{
argb.setARGB (0xff, red, green, blue);
}
Colour Colour::fromRGB (uint8 red, uint8 green, uint8 blue) noexcept
{
return Colour (red, green, blue);
}
Colour::Colour (uint8 red, uint8 green, uint8 blue, uint8 alpha) noexcept
{
argb.setARGB (alpha, red, green, blue);
}
Colour Colour::fromRGBA (uint8 red, uint8 green, uint8 blue, uint8 alpha) noexcept
{
return Colour (red, green, blue, alpha);
}
Colour::Colour (uint8 red, uint8 green, uint8 blue, float alpha) noexcept
{
argb.setARGB (ColourHelpers::floatToUInt8 (alpha), red, green, blue);
}
Colour Colour::fromFloatRGBA (float red, float green, float blue, float alpha) noexcept
{
return Colour (ColourHelpers::floatToUInt8 (red),
ColourHelpers::floatToUInt8 (green),
ColourHelpers::floatToUInt8 (blue), alpha);
}
Colour::Colour (float hue, float saturation, float brightness, float alpha) noexcept
: argb (ColourHelpers::HSB::toRGB (hue, saturation, brightness, ColourHelpers::floatToUInt8 (alpha)))
{
}
Colour Colour::fromHSV (float hue, float saturation, float brightness, float alpha) noexcept
{
return Colour (hue, saturation, brightness, alpha);
}
Colour Colour::fromHSV (float hue, float saturation, float brightness, uint8 alpha) noexcept
{
return Colour (hue, saturation, brightness, alpha);
}
Colour Colour::fromHSL (float hue, float saturation, float lightness, float alpha) noexcept
{
return fromHSL (hue, saturation, lightness, ColourHelpers::floatToUInt8 (alpha));
}
Colour Colour::fromHSL (float hue, float saturation, float lightness, uint8 alpha) noexcept
{
Colour hslColour;
hslColour.argb = ColourHelpers::HSL::toRGB (hue, saturation, lightness, alpha);
return hslColour;
}
Colour::Colour (float hue, float saturation, float brightness, uint8 alpha) noexcept
: argb (ColourHelpers::HSB::toRGB (hue, saturation, brightness, alpha))
{
}
Colour::Colour (PixelARGB argb_) noexcept
: argb (argb_)
{
}
Colour::Colour (PixelRGB rgb) noexcept
: argb (Colour (rgb.getInARGBMaskOrder()).argb)
{
}
Colour::Colour (PixelAlpha alpha) noexcept
: argb (Colour (alpha.getInARGBMaskOrder()).argb)
{
}
//==============================================================================
PixelARGB Colour::getPixelARGB() const noexcept
{
PixelARGB p (argb);
p.premultiply();
return p;
}
PixelARGB Colour::getNonPremultipliedPixelARGB() const noexcept
{
return argb;
}
uint32 Colour::getARGB() const noexcept
{
return argb.getInARGBMaskOrder();
}
//==============================================================================
bool Colour::isTransparent() const noexcept
{
return getAlpha() == 0;
}
bool Colour::isOpaque() const noexcept
{
return getAlpha() == 0xff;
}
Colour Colour::withAlpha (uint8 newAlpha) const noexcept
{
PixelARGB newCol (argb);
newCol.setAlpha (newAlpha);
return Colour (newCol);
}
Colour Colour::withAlpha (float newAlpha) const noexcept
{
jassert (newAlpha >= 0 && newAlpha <= 1.0f);
PixelARGB newCol (argb);
newCol.setAlpha (ColourHelpers::floatToUInt8 (newAlpha));
return Colour (newCol);
}
Colour Colour::withMultipliedAlpha (float alphaMultiplier) const noexcept
{
jassert (alphaMultiplier >= 0);
PixelARGB newCol (argb);
newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
return Colour (newCol);
}
//==============================================================================
Colour Colour::overlaidWith (Colour src) const noexcept
{
auto destAlpha = getAlpha();
if (destAlpha <= 0)
return src;
auto invA = 0xff - (int) src.getAlpha();
auto resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
if (resA <= 0)
return *this;
auto da = (invA * destAlpha) / resA;
return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
(uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
(uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
(uint8) resA);
}
Colour Colour::interpolatedWith (Colour other, float proportionOfOther) const noexcept
{
if (proportionOfOther <= 0)
return *this;
if (proportionOfOther >= 1.0f)
return other;
PixelARGB c1 (getPixelARGB());
PixelARGB c2 (other.getPixelARGB());
c1.tween (c2, (uint32) roundToInt (proportionOfOther * 255.0f));
c1.unpremultiply();
return Colour (c1);
}
//==============================================================================
float Colour::getFloatRed() const noexcept { return getRed() / 255.0f; }
float Colour::getFloatGreen() const noexcept { return getGreen() / 255.0f; }
float Colour::getFloatBlue() const noexcept { return getBlue() / 255.0f; }
float Colour::getFloatAlpha() const noexcept { return getAlpha() / 255.0f; }
//==============================================================================
void Colour::getHSB (float& h, float& s, float& v) const noexcept
{
ColourHelpers::HSB hsb (*this);
h = hsb.hue;
s = hsb.saturation;
v = hsb.brightness;
}
void Colour::getHSL (float& h, float& s, float& l) const noexcept
{
ColourHelpers::HSL hsl (*this);
h = hsl.hue;
s = hsl.saturation;
l = hsl.lightness;
}
float Colour::getHue() const noexcept { return ColourHelpers::HSB (*this).hue; }
float Colour::getSaturation() const noexcept { return ColourHelpers::HSB (*this).saturation; }
float Colour::getBrightness() const noexcept { return ColourHelpers::HSB (*this).brightness; }
float Colour::getSaturationHSL() const noexcept { return ColourHelpers::HSL (*this).saturation; }
float Colour::getLightness() const noexcept { return ColourHelpers::HSL (*this).lightness; }
Colour Colour::withHue (float h) const noexcept { ColourHelpers::HSB hsb (*this); hsb.hue = h; return hsb.toColour (*this); }
Colour Colour::withSaturation (float s) const noexcept { ColourHelpers::HSB hsb (*this); hsb.saturation = s; return hsb.toColour (*this); }
Colour Colour::withBrightness (float v) const noexcept { ColourHelpers::HSB hsb (*this); hsb.brightness = v; return hsb.toColour (*this); }
Colour Colour::withSaturationHSL (float s) const noexcept { ColourHelpers::HSL hsl (*this); hsl.saturation = s; return hsl.toColour (*this); }
Colour Colour::withLightness (float l) const noexcept { ColourHelpers::HSL hsl (*this); hsl.lightness = l; return hsl.toColour (*this); }
float Colour::getPerceivedBrightness() const noexcept
{
return std::sqrt (0.241f * square (getFloatRed())
+ 0.691f * square (getFloatGreen())
+ 0.068f * square (getFloatBlue()));
}
//==============================================================================
Colour Colour::withRotatedHue (float amountToRotate) const noexcept
{
ColourHelpers::HSB hsb (*this);
hsb.hue += amountToRotate;
return hsb.toColour (*this);
}
Colour Colour::withMultipliedSaturation (float amount) const noexcept
{
ColourHelpers::HSB hsb (*this);
hsb.saturation = jmin (1.0f, hsb.saturation * amount);
return hsb.toColour (*this);
}
Colour Colour::withMultipliedSaturationHSL (float amount) const noexcept
{
ColourHelpers::HSL hsl (*this);
hsl.saturation = jmin (1.0f, hsl.saturation * amount);
return hsl.toColour (*this);
}
Colour Colour::withMultipliedBrightness (float amount) const noexcept
{
ColourHelpers::HSB hsb (*this);
hsb.brightness = jmin (1.0f, hsb.brightness * amount);
return hsb.toColour (*this);
}
Colour Colour::withMultipliedLightness (float amount) const noexcept
{
ColourHelpers::HSL hsl (*this);
hsl.lightness = jmin (1.0f, hsl.lightness * amount);
return hsl.toColour (*this);
}
//==============================================================================
Colour Colour::brighter (float amount) const noexcept
{
jassert (amount >= 0.0f);
amount = 1.0f / (1.0f + amount);
return Colour ((uint8) (255 - (amount * (255 - getRed()))),
(uint8) (255 - (amount * (255 - getGreen()))),
(uint8) (255 - (amount * (255 - getBlue()))),
getAlpha());
}
Colour Colour::darker (float amount) const noexcept
{
jassert (amount >= 0.0f);
amount = 1.0f / (1.0f + amount);
return Colour ((uint8) (amount * getRed()),
(uint8) (amount * getGreen()),
(uint8) (amount * getBlue()),
getAlpha());
}
//==============================================================================
Colour Colour::greyLevel (float brightness) noexcept
{
auto level = ColourHelpers::floatToUInt8 (brightness);
return Colour (level, level, level);
}
//==============================================================================
Colour Colour::contrasting (float amount) const noexcept
{
return overlaidWith ((getPerceivedBrightness() >= 0.5f
? Colours::black
: Colours::white).withAlpha (amount));
}
Colour Colour::contrasting (Colour target, float minContrast) const noexcept
{
ColourHelpers::YIQ bg (*this);
ColourHelpers::YIQ fg (target);
if (std::abs (bg.y - fg.y) >= minContrast)
return target;
auto y1 = jmax (0.0f, bg.y - minContrast);
auto y2 = jmin (1.0f, bg.y + minContrast);
fg.y = (std::abs (y1 - bg.y) > std::abs (y2 - bg.y)) ? y1 : y2;
return fg.toColour();
}
Colour Colour::contrasting (Colour colour1,
Colour colour2) noexcept
{
auto b1 = colour1.getPerceivedBrightness();
auto b2 = colour2.getPerceivedBrightness();
float best = 0.0f, bestDist = 0.0f;
for (float i = 0.0f; i < 1.0f; i += 0.02f)
{
auto d1 = std::abs (i - b1);
auto d2 = std::abs (i - b2);
auto dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
if (dist > bestDist)
{
best = i;
bestDist = dist;
}
}
return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
.withBrightness (best);
}
//==============================================================================
String Colour::toString() const
{
return String::toHexString ((int) argb.getInARGBMaskOrder());
}
Colour Colour::fromString (StringRef encodedColourString)
{
return Colour (CharacterFunctions::HexParser<uint32>::parse (encodedColourString.text));
}
String Colour::toDisplayString (const bool includeAlphaValue) const
{
return String::toHexString ((int) (argb.getInARGBMaskOrder() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
.paddedLeft ('0', includeAlphaValue ? 8 : 6)
.toUpperCase();
}
//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS
class ColourTests final : public UnitTest
{
public:
ColourTests()
: UnitTest ("Colour", UnitTestCategories::graphics)
{}
void runTest() override
{
auto testColour = [this] (Colour colour,
uint8 expectedRed, uint8 expectedGreen, uint8 expectedBlue,
uint8 expectedAlpha = 255)
{
expectEquals (colour.getRed(), expectedRed);
expectEquals (colour.getGreen(), expectedGreen);
expectEquals (colour.getBlue(), expectedBlue);
expectEquals (colour.getAlpha(), expectedAlpha);
};
beginTest ("Constructors");
{
Colour c1;
testColour (c1, (uint8) 0, (uint8) 0, (uint8) 0, (uint8) 0);
Colour c2 ((uint32) 0);
testColour (c2, (uint8) 0, (uint8) 0, (uint8) 0, (uint8) 0);
Colour c3 ((uint32) 0xffffffff);
testColour (c3, (uint8) 255, (uint8) 255, (uint8) 255, (uint8) 255);
Colour c4 (0, 0, 0);
testColour (c4, (uint8) 0, (uint8) 0, (uint8) 0, (uint8) 255);
Colour c5 (255, 255, 255);
testColour (c5, (uint8) 255, (uint8) 255, (uint8) 255, (uint8) 255);
Colour c6 ((uint8) 0, (uint8) 0, (uint8) 0, (uint8) 0);
testColour (c6, (uint8) 0, (uint8) 0, (uint8) 0, (uint8) 0);
Colour c7 ((uint8) 255, (uint8) 255, (uint8) 255, (uint8) 255);
testColour (c7, (uint8) 255, (uint8) 255, (uint8) 255, (uint8) 255);
Colour c8 ((uint8) 0, (uint8) 0, (uint8) 0, 0.0f);
testColour (c8, (uint8) 0, (uint8) 0, (uint8) 0, (uint8) 0);
Colour c9 ((uint8) 255, (uint8) 255, (uint8) 255, 1.0f);
testColour (c9, (uint8) 255, (uint8) 255, (uint8) 255, (uint8) 255);
}
beginTest ("HSV");
{
// black
testColour (Colour::fromHSV (0.0f, 0.0f, 0.0f, 1.0f), 0, 0, 0);
testColour (Colour::fromHSV (0.0f, 0.0f, 0.0f, 0.5f), 0, 0, 0, 128);
// white
testColour (Colour::fromHSV (0.0f, 0.0f, 1.0f, 1.0f), 255, 255, 255);
testColour (Colour::fromHSV (0.0f, 0.0f, 1.0f, 0.5f), 255, 255, 255, 128);
// red
testColour (Colour::fromHSV (0.0f, 1.0f, 1.0f, 1.0f), 255, 0, 0);
testColour (Colour::fromHSV (0.0f, 1.0f, 1.0f, 0.5f), 255, 0, 0, 128);
testColour (Colour::fromHSV (1.0f, 1.0f, 1.0f, 1.0f), 255, 0, 0);
testColour (Colour::fromHSV (1.0f, 1.0f, 1.0f, 0.5f), 255, 0, 0, 128);
// lime
testColour (Colour::fromHSV (120 / 360.0f, 1.0f, 1.0f, 1.0f), 0, 255, 0);
testColour (Colour::fromHSV (120 / 360.0f, 1.0f, 1.0f, 0.5f), 0, 255, 0, 128);
// blue
testColour (Colour::fromHSV (240 / 360.0f, 1.0f, 1.0f, 1.0f), 0, 0, 255);
testColour (Colour::fromHSV (240 / 360.0f, 1.0f, 1.0f, 0.5f), 0, 0, 255, 128);
// yellow
testColour (Colour::fromHSV (60 / 360.0f, 1.0f, 1.0f, 1.0f), 255, 255, 0);
testColour (Colour::fromHSV (60 / 360.0f, 1.0f, 1.0f, 0.5f), 255, 255, 0, 128);
// cyan
testColour (Colour::fromHSV (180 / 360.0f, 1.0f, 1.0f, 1.0f), 0, 255, 255);
testColour (Colour::fromHSV (180 / 360.0f, 1.0f, 1.0f, 0.5f), 0, 255, 255, 128);
// magenta
testColour (Colour::fromHSV (300 / 360.0f, 1.0f, 1.0f, 1.0f), 255, 0, 255);
testColour (Colour::fromHSV (300 / 360.0f, 1.0f, 1.0f, 0.5f), 255, 0, 255, 128);
// silver
testColour (Colour::fromHSV (0.0f, 0.0f, 0.75f, 1.0f), 191, 191, 191);
testColour (Colour::fromHSV (0.0f, 0.0f, 0.75f, 0.5f), 191, 191, 191, 128);
// grey
testColour (Colour::fromHSV (0.0f, 0.0f, 0.5f, 1.0f), 128, 128, 128);
testColour (Colour::fromHSV (0.0f, 0.0f, 0.5f, 0.5f), 128, 128, 128, 128);
// maroon
testColour (Colour::fromHSV (0.0f, 1.0f, 0.5f, 1.0f), 128, 0, 0);
testColour (Colour::fromHSV (0.0f, 1.0f, 0.5f, 0.5f), 128, 0, 0, 128);
// olive
testColour (Colour::fromHSV (60 / 360.0f, 1.0f, 0.5f, 1.0f), 128, 128, 0);
testColour (Colour::fromHSV (60 / 360.0f, 1.0f, 0.5f, 0.5f), 128, 128, 0, 128);
// green
testColour (Colour::fromHSV (120 / 360.0f, 1.0f, 0.5f, 1.0f), 0, 128, 0);
testColour (Colour::fromHSV (120 / 360.0f, 1.0f, 0.5f, 0.5f), 0, 128, 0, 128);
// purple
testColour (Colour::fromHSV (300 / 360.0f, 1.0f, 0.5f, 1.0f), 128, 0, 128);
testColour (Colour::fromHSV (300 / 360.0f, 1.0f, 0.5f, 0.5f), 128, 0, 128, 128);
// teal
testColour (Colour::fromHSV (180 / 360.0f, 1.0f, 0.5f, 1.0f), 0, 128, 128);
testColour (Colour::fromHSV (180 / 360.0f, 1.0f, 0.5f, 0.5f), 0, 128, 128, 128);
// navy
testColour (Colour::fromHSV (240 / 360.0f, 1.0f, 0.5f, 1.0f), 0, 0, 128);
testColour (Colour::fromHSV (240 / 360.0f, 1.0f, 0.5f, 0.5f), 0, 0, 128, 128);
}
beginTest ("HSL");
{
// black
testColour (Colour::fromHSL (0.0f, 0.0f, 0.0f, 1.0f), 0, 0, 0);
testColour (Colour::fromHSL (0.0f, 0.0f, 0.0f, 0.5f), 0, 0, 0, 128);
// white
testColour (Colour::fromHSL (0.0f, 0.0f, 1.0f, 1.0f), 255, 255, 255);
testColour (Colour::fromHSL (0.0f, 0.0f, 1.0f, 0.5f), 255, 255, 255, 128);
// red
testColour (Colour::fromHSL (0.0f, 1.0f, 0.5f, 1.0f), 255, 0, 0);
testColour (Colour::fromHSL (0.0f, 1.0f, 0.5f, 0.5f), 255, 0, 0, 128);
testColour (Colour::fromHSL (1.0f, 1.0f, 0.5f, 1.0f), 255, 0, 0);
testColour (Colour::fromHSL (1.0f, 1.0f, 0.5f, 0.5f), 255, 0, 0, 128);
// lime
testColour (Colour::fromHSL (120 / 360.0f, 1.0f, 0.5f, 1.0f), 0, 255, 0);
testColour (Colour::fromHSL (120 / 360.0f, 1.0f, 0.5f, 0.5f), 0, 255, 0, 128);
// blue
testColour (Colour::fromHSL (240 / 360.0f, 1.0f, 0.5f, 1.0f), 0, 0, 255);
testColour (Colour::fromHSL (240 / 360.0f, 1.0f, 0.5f, 0.5f), 0, 0, 255, 128);
// yellow
testColour (Colour::fromHSL (60 / 360.0f, 1.0f, 0.5f, 1.0f), 255, 255, 0);
testColour (Colour::fromHSL (60 / 360.0f, 1.0f, 0.5f, 0.5f), 255, 255, 0, 128);
// cyan
testColour (Colour::fromHSL (180 / 360.0f, 1.0f, 0.5f, 1.0f), 0, 255, 255);
testColour (Colour::fromHSL (180 / 360.0f, 1.0f, 0.5f, 0.5f), 0, 255, 255, 128);
// magenta
testColour (Colour::fromHSL (300 / 360.0f, 1.0f, 0.5f, 1.0f), 255, 0, 255);
testColour (Colour::fromHSL (300 / 360.0f, 1.0f, 0.5f, 0.5f), 255, 0, 255, 128);
// silver
testColour (Colour::fromHSL (0.0f, 0.0f, 0.75f, 1.0f), 191, 191, 191);
testColour (Colour::fromHSL (0.0f, 0.0f, 0.75f, 0.5f), 191, 191, 191, 128);
// grey
testColour (Colour::fromHSL (0.0f, 0.0f, 0.5f, 1.0f), 128, 128, 128);
testColour (Colour::fromHSL (0.0f, 0.0f, 0.5f, 0.5f), 128, 128, 128, 128);
// maroon
testColour (Colour::fromHSL (0.0f, 1.0f, 0.25f, 1.0f), 128, 0, 0);
testColour (Colour::fromHSL (0.0f, 1.0f, 0.25f, 0.5f), 128, 0, 0, 128);
// olive
testColour (Colour::fromHSL (60 / 360.0f, 1.0f, 0.25f, 1.0f), 128, 128, 0);
testColour (Colour::fromHSL (60 / 360.0f, 1.0f, 0.25f, 0.5f), 128, 128, 0, 128);
// green
testColour (Colour::fromHSL (120 / 360.0f, 1.0f, 0.25f, 1.0f), 0, 128, 0);
testColour (Colour::fromHSL (120 / 360.0f, 1.0f, 0.25f, 0.5f), 0, 128, 0, 128);
// purple
testColour (Colour::fromHSL (300 / 360.0f, 1.0f, 0.25f, 1.0f), 128, 0, 128);
testColour (Colour::fromHSL (300 / 360.0f, 1.0f, 0.25f, 0.5f), 128, 0, 128, 128);
// teal
testColour (Colour::fromHSL (180 / 360.0f, 1.0f, 0.25f, 1.0f), 0, 128, 128);
testColour (Colour::fromHSL (180 / 360.0f, 1.0f, 0.25f, 0.5f), 0, 128, 128, 128);
// navy
testColour (Colour::fromHSL (240 / 360.0f, 1.0f, 0.25f, 1.0f), 0, 0, 128);
testColour (Colour::fromHSL (240 / 360.0f, 1.0f, 0.25f, 0.5f), 0, 0, 128, 128);
}
beginTest ("Modifiers");
{
Colour red (255, 0, 0);
testColour (red, 255, 0, 0);
testColour (red.withHue (120.0f / 360.0f), 0, 255, 0);
testColour (red.withSaturation (0.5f), 255, 128, 128);
testColour (red.withSaturationHSL (0.5f), 191, 64, 64);
testColour (red.withBrightness (0.5f), 128, 0, 0);
testColour (red.withLightness (1.0f), 255, 255, 255);
testColour (red.withRotatedHue (120.0f / 360.0f), 0, 255, 0);
testColour (red.withRotatedHue (480.0f / 360.0f), 0, 255, 0);
testColour (red.withRotatedHue (-240.0f / 360.0f), 0, 255, 0);
testColour (red.withRotatedHue (-600.0f / 360.0f), 0, 255, 0);
testColour (red.withMultipliedSaturation (0.0f), 255, 255, 255);
testColour (red.withMultipliedSaturationHSL (0.0f), 128, 128, 128);
testColour (red.withMultipliedBrightness (0.5f), 128, 0, 0);
testColour (red.withMultipliedLightness (2.0f), 255, 255, 255);
testColour (red.withMultipliedLightness (1.0f), 255, 0, 0);
testColour (red.withLightness (red.getLightness()), 255, 0, 0);
testColour (red.withAlpha ((uint8) 128), 255, 0, 0, 128);
testColour (red.withAlpha (0.5f), 255, 0, 0, 128);
}
}
};
static ColourTests colourTests;
#endif
} // namespace juce
+451
View File
@@ -0,0 +1,451 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
Represents a colour, also including a transparency value.
The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
@tags{Graphics}
*/
class JUCE_API Colour final
{
public:
//==============================================================================
/** Creates a transparent black colour. */
Colour() = default;
/** Creates a copy of another Colour object. */
Colour (const Colour&) = default;
/** Creates a colour from a 32-bit ARGB value.
The format of this number is:
((alpha << 24) | (red << 16) | (green << 8) | blue).
All components in the range 0x00 to 0xff.
An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
@see getPixelARGB
*/
explicit Colour (uint32 argb) noexcept;
/** Creates an opaque colour using 8-bit red, green and blue values */
Colour (uint8 red,
uint8 green,
uint8 blue) noexcept;
/** Creates an opaque colour using 8-bit red, green and blue values */
static Colour fromRGB (uint8 red,
uint8 green,
uint8 blue) noexcept;
/** Creates a colour using 8-bit red, green, blue and alpha values. */
Colour (uint8 red,
uint8 green,
uint8 blue,
uint8 alpha) noexcept;
/** Creates a colour using 8-bit red, green, blue and alpha values. */
static Colour fromRGBA (uint8 red,
uint8 green,
uint8 blue,
uint8 alpha) noexcept;
/** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
Values outside the valid range will be clipped.
*/
Colour (uint8 red,
uint8 green,
uint8 blue,
float alpha) noexcept;
/** Creates a colour using floating point red, green, blue and alpha values.
Numbers outside the range 0..1 will be clipped.
*/
static Colour fromFloatRGBA (float red,
float green,
float blue,
float alpha) noexcept;
/** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
The floating point values must be between 0.0 and 1.0.
An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
Values outside the valid range will be clipped.
*/
Colour (float hue,
float saturation,
float brightness,
uint8 alpha) noexcept;
/** Creates a colour using floating point hue, saturation, brightness and alpha values.
All values must be between 0.0 and 1.0.
Numbers outside the valid range will be clipped.
*/
Colour (float hue,
float saturation,
float brightness,
float alpha) noexcept;
/** Creates a colour using floating point hue, saturation, brightness and alpha values.
All values must be between 0.0 and 1.0.
Numbers outside the valid range will be clipped.
*/
static Colour fromHSV (float hue,
float saturation,
float brightness,
float alpha) noexcept;
/** Creates a colour using floating point hue, saturation, brightness values, and an 8-bit alpha.
All values must be between 0.0 and 1.0.
An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
Numbers outside the valid range will be clipped.
*/
static Colour fromHSV (float hue,
float saturation,
float brightness,
uint8 alpha) noexcept;
/** Creates a colour using floating point hue, saturation, lightness and alpha values.
All values must be between 0.0 and 1.0.
Numbers outside the valid range will be clipped.
*/
static Colour fromHSL (float hue,
float saturation,
float lightness,
float alpha) noexcept;
/** Creates a colour using floating point hue, saturation, lightness values, and an 8-bit alpha.
All values must be between 0.0 and 1.0.
An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
Numbers outside the valid range will be clipped.
*/
static Colour fromHSL (float hue,
float saturation,
float lightness,
uint8 alpha) noexcept;
/** Creates a colour using a PixelARGB object. This function assumes that the argb pixel is
not premultiplied.
*/
Colour (PixelARGB argb) noexcept;
/** Creates a colour using a PixelRGB object.
*/
Colour (PixelRGB rgb) noexcept;
/** Creates a colour using a PixelAlpha object.
*/
Colour (PixelAlpha alpha) noexcept;
/** Destructor. */
~Colour() = default;
/** Copies another Colour object. */
Colour& operator= (const Colour&) = default;
/** Compares two colours. */
bool operator== (const Colour& other) const noexcept;
/** Compares two colours. */
bool operator!= (const Colour& other) const noexcept;
//==============================================================================
/** Returns the red component of this colour.
@returns a value between 0x00 and 0xff.
*/
uint8 getRed() const noexcept { return argb.getRed(); }
/** Returns the green component of this colour.
@returns a value between 0x00 and 0xff.
*/
uint8 getGreen() const noexcept { return argb.getGreen(); }
/** Returns the blue component of this colour.
@returns a value between 0x00 and 0xff.
*/
uint8 getBlue() const noexcept { return argb.getBlue(); }
/** Returns the red component of this colour as a floating point value.
@returns a value between 0.0 and 1.0
*/
float getFloatRed() const noexcept;
/** Returns the green component of this colour as a floating point value.
@returns a value between 0.0 and 1.0
*/
float getFloatGreen() const noexcept;
/** Returns the blue component of this colour as a floating point value.
@returns a value between 0.0 and 1.0
*/
float getFloatBlue() const noexcept;
/** Returns a premultiplied ARGB pixel object that represents this colour.
*/
PixelARGB getPixelARGB() const noexcept;
/** Returns an ARGB pixel object that represents this colour.
*/
PixelARGB getNonPremultipliedPixelARGB() const noexcept;
/** Returns a 32-bit integer that represents this colour.
The format of this number is:
((alpha << 24) | (red << 16) | (green << 8) | blue).
*/
uint32 getARGB() const noexcept;
//==============================================================================
/** Returns the colour's alpha (opacity).
Alpha of 0x00 is completely transparent, 0xff is completely opaque.
*/
uint8 getAlpha() const noexcept { return argb.getAlpha(); }
/** Returns the colour's alpha (opacity) as a floating point value.
Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
*/
float getFloatAlpha() const noexcept;
/** Returns true if this colour is completely opaque.
Equivalent to (getAlpha() == 0xff).
*/
bool isOpaque() const noexcept;
/** Returns true if this colour is completely transparent.
Equivalent to (getAlpha() == 0x00).
*/
bool isTransparent() const noexcept;
/** Returns a colour that's the same colour as this one, but with a new alpha value. */
Colour withAlpha (uint8 newAlpha) const noexcept;
/** Returns a colour that's the same colour as this one, but with a new alpha value. */
Colour withAlpha (float newAlpha) const noexcept;
/** Returns a colour that's the same colour as this one, but with a modified alpha value.
The new colour's alpha will be this object's alpha multiplied by the value passed-in.
*/
Colour withMultipliedAlpha (float alphaMultiplier) const noexcept;
//==============================================================================
/** Returns a colour that is the result of alpha-compositing a new colour over this one.
If the foreground colour is semi-transparent, it is blended onto this colour accordingly.
*/
Colour overlaidWith (Colour foregroundColour) const noexcept;
/** Returns a colour that lies somewhere between this one and another.
If amountOfOther is zero, the result is 100% this colour, if amountOfOther
is 1.0, the result is 100% of the other colour.
*/
Colour interpolatedWith (Colour other, float proportionOfOther) const noexcept;
//==============================================================================
/** Returns the colour's hue component.
The value returned is in the range 0.0 to 1.0
*/
float getHue() const noexcept;
/** Returns the colour's saturation component.
The value returned is in the range 0.0 to 1.0
*/
float getSaturation() const noexcept;
/** Returns the colour's saturation component as represented in the HSL colour space.
The value returned is in the range 0.0 to 1.0
*/
float getSaturationHSL() const noexcept;
/** Returns the colour's brightness component.
The value returned is in the range 0.0 to 1.0
*/
float getBrightness() const noexcept;
/** Returns the colour's lightness component.
The value returned is in the range 0.0 to 1.0
*/
float getLightness() const noexcept;
/** Returns a skewed brightness value, adjusted to better reflect the way the human
eye responds to different colour channels. This makes it better than getBrightness()
for comparing differences in brightness.
*/
float getPerceivedBrightness() const noexcept;
/** Returns the colour's hue, saturation and brightness components all at once.
The values returned are in the range 0.0 to 1.0
*/
void getHSB (float& hue,
float& saturation,
float& brightness) const noexcept;
/** Returns the colour's hue, saturation and lightness components all at once.
The values returned are in the range 0.0 to 1.0
*/
void getHSL (float& hue,
float& saturation,
float& lightness) const noexcept;
//==============================================================================
/** Returns a copy of this colour with a different hue. */
[[nodiscard]] Colour withHue (float newHue) const noexcept;
/** Returns a copy of this colour with a different saturation. */
[[nodiscard]] Colour withSaturation (float newSaturation) const noexcept;
/** Returns a copy of this colour with a different saturation in the HSL colour space. */
[[nodiscard]] Colour withSaturationHSL (float newSaturation) const noexcept;
/** Returns a copy of this colour with a different brightness.
@see brighter, darker, withMultipliedBrightness
*/
[[nodiscard]] Colour withBrightness (float newBrightness) const noexcept;
/** Returns a copy of this colour with a different lightness.
@see lighter, darker, withMultipliedLightness
*/
[[nodiscard]] Colour withLightness (float newLightness) const noexcept;
/** Returns a copy of this colour with its hue rotated.
The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
@see brighter, darker, withMultipliedBrightness
*/
[[nodiscard]] Colour withRotatedHue (float amountToRotate) const noexcept;
/** Returns a copy of this colour with its saturation multiplied by the given value.
The new colour's saturation is (this->getSaturation() * multiplier)
(the result is clipped to legal limits).
*/
[[nodiscard]] Colour withMultipliedSaturation (float multiplier) const noexcept;
/** Returns a copy of this colour with its saturation multiplied by the given value.
The new colour's saturation is (this->getSaturation() * multiplier)
(the result is clipped to legal limits).
This will be in the HSL colour space.
*/
[[nodiscard]] Colour withMultipliedSaturationHSL (float multiplier) const noexcept;
/** Returns a copy of this colour with its brightness multiplied by the given value.
The new colour's brightness is (this->getBrightness() * multiplier)
(the result is clipped to legal limits).
*/
[[nodiscard]] Colour withMultipliedBrightness (float amount) const noexcept;
/** Returns a copy of this colour with its lightness multiplied by the given value.
The new colour's lightness is (this->lightness() * multiplier)
(the result is clipped to legal limits).
*/
[[nodiscard]] Colour withMultipliedLightness (float amount) const noexcept;
//==============================================================================
/** Returns a brighter version of this colour.
@param amountBrighter how much brighter to make it - a value greater than or equal to 0,
where 0 is unchanged, and higher values make it brighter
@see withMultipliedBrightness
*/
[[nodiscard]] Colour brighter (float amountBrighter = 0.4f) const noexcept;
/** Returns a darker version of this colour.
@param amountDarker how much darker to make it - a value greater than or equal to 0,
where 0 is unchanged, and higher values make it darker
@see withMultipliedBrightness
*/
[[nodiscard]] Colour darker (float amountDarker = 0.4f) const noexcept;
//==============================================================================
/** Returns a colour that will be clearly visible against this colour.
The amount parameter indicates how contrasting the new colour should
be, so e.g. Colours::black.contrasting (0.1f) will return a colour
that's just a little bit lighter; Colours::black.contrasting (1.0f) will
return white; Colours::white.contrasting (1.0f) will return black, etc.
*/
[[nodiscard]] Colour contrasting (float amount = 1.0f) const noexcept;
/** Returns a colour that is as close as possible to a target colour whilst
still being in contrast to this one.
The colour that is returned will be the targetColour, but with its luminosity
nudged up or down so that it differs from the luminosity of this colour
by at least the amount specified by minLuminosityDiff.
*/
[[nodiscard]] Colour contrasting (Colour targetColour, float minLuminosityDiff) const noexcept;
/** Returns a colour that contrasts against two colours.
Looks for a colour that contrasts with both of the colours passed-in.
Handy for things like choosing a highlight colour in text editors, etc.
*/
[[nodiscard]] static Colour contrasting (Colour colour1,
Colour colour2) noexcept;
//==============================================================================
/** Returns an opaque shade of grey.
@param brightness the level of grey to return - 0 is black, 1.0 is white
*/
[[nodiscard]] static Colour greyLevel (float brightness) noexcept;
//==============================================================================
/** Returns a stringified version of this colour.
The string can be turned back into a colour using the fromString() method.
*/
String toString() const;
/** Reads the colour from a string that was created with toString(). */
[[nodiscard]] static Colour fromString (StringRef encodedColourString);
/** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
String toDisplayString (bool includeAlphaValue) const;
private:
//==============================================================================
PixelARGB argb { 0, 0, 0, 0 };
};
} // namespace juce
@@ -0,0 +1,309 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
ColourGradient::ColourGradient() noexcept : isRadial (false)
{
#if JUCE_DEBUG
point1.setX (987654.0f);
#define JUCE_COLOURGRADIENT_CHECK_COORDS_INITIALISED jassert (! exactlyEqual (point1.x, 987654.0f));
#else
#define JUCE_COLOURGRADIENT_CHECK_COORDS_INITIALISED
#endif
}
ColourGradient::ColourGradient (Colour colour1, float x1, float y1,
Colour colour2, float x2, float y2, bool radial)
: ColourGradient (colour1, Point<float> (x1, y1),
colour2, Point<float> (x2, y2), radial)
{
}
ColourGradient::ColourGradient (Colour colour1, Point<float> p1,
Colour colour2, Point<float> p2, bool radial)
: point1 (p1),
point2 (p2),
isRadial (radial)
{
colours.add (ColourPoint { 0.0, colour1 },
ColourPoint { 1.0, colour2 });
}
ColourGradient ColourGradient::vertical (Colour c1, float y1, Colour c2, float y2)
{
return { c1, 0, y1, c2, 0, y2, false };
}
ColourGradient ColourGradient::horizontal (Colour c1, float x1, Colour c2, float x2)
{
return { c1, x1, 0, c2, x2, 0, false };
}
struct PointComparisons
{
auto tie() const { return std::tie (point->x, point->y); }
bool operator== (const PointComparisons& other) const { return tie() == other.tie(); }
bool operator!= (const PointComparisons& other) const { return tie() != other.tie(); }
bool operator< (const PointComparisons& other) const { return tie() < other.tie(); }
const Point<float>* point = nullptr;
};
struct ColourGradient::ColourPointArrayComparisons
{
bool operator== (const ColourPointArrayComparisons& other) const { return *array == *other.array; }
bool operator!= (const ColourPointArrayComparisons& other) const { return *array != *other.array; }
bool operator< (const ColourPointArrayComparisons& other) const
{
return std::lexicographical_compare (array->begin(), array->end(), other.array->begin(), other.array->end());
}
const Array<ColourGradient::ColourPoint>* array = nullptr;
};
auto ColourGradient::tie() const
{
return std::tuple (PointComparisons { &point1 },
PointComparisons { &point2 },
isRadial,
ColourPointArrayComparisons { &colours });
}
bool ColourGradient::operator== (const ColourGradient& other) const noexcept { return tie() == other.tie(); }
bool ColourGradient::operator!= (const ColourGradient& other) const noexcept { return tie() != other.tie(); }
bool ColourGradient::operator< (const ColourGradient& other) const noexcept { return tie() < other.tie(); }
bool ColourGradient::operator<= (const ColourGradient& other) const noexcept { return tie() <= other.tie(); }
bool ColourGradient::operator> (const ColourGradient& other) const noexcept { return tie() > other.tie(); }
bool ColourGradient::operator>= (const ColourGradient& other) const noexcept { return tie() >= other.tie(); }
//==============================================================================
void ColourGradient::clearColours()
{
colours.clear();
}
int ColourGradient::addColour (const double proportionAlongGradient, Colour colour)
{
// must be within the two end-points
jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
if (proportionAlongGradient <= 0)
{
colours.set (0, { 0.0, colour });
return 0;
}
auto pos = jmin (1.0, proportionAlongGradient);
int i;
for (i = 0; i < colours.size(); ++i)
if (colours.getReference (i).position > pos)
break;
colours.insert (i, { pos, colour });
return i;
}
void ColourGradient::removeColour (int index)
{
jassert (isPositiveAndBelow (index, colours.size()));
colours.remove (index);
}
void ColourGradient::multiplyOpacity (const float multiplier) noexcept
{
for (auto& c : colours)
c.colour = c.colour.withMultipliedAlpha (multiplier);
}
//==============================================================================
int ColourGradient::getNumColours() const noexcept
{
return colours.size();
}
double ColourGradient::getColourPosition (int index) const noexcept
{
if (isPositiveAndBelow (index, colours.size()))
return colours.getReference (index).position;
return 0;
}
Colour ColourGradient::getColour (int index) const noexcept
{
if (isPositiveAndBelow (index, colours.size()))
return colours.getReference (index).colour;
return {};
}
void ColourGradient::setColour (int index, Colour newColour) noexcept
{
if (isPositiveAndBelow (index, colours.size()))
colours.getReference (index).colour = newColour;
}
Colour ColourGradient::getColourAtPosition (double position) const noexcept
{
jassert (approximatelyEqual (colours.getReference (0).position, 0.0)); // the first colour specified has to go at position 0
if (position <= 0 || colours.size() <= 1)
return colours.getReference (0).colour;
int i = colours.size() - 1;
while (position < colours.getReference (i).position)
--i;
auto& p1 = colours.getReference (i);
if (i >= colours.size() - 1)
return p1.colour;
auto& p2 = colours.getReference (i + 1);
return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
}
//==============================================================================
void ColourGradient::createLookupTable (PixelARGB* const lookupTable, const int numEntries) const noexcept
{
JUCE_COLOURGRADIENT_CHECK_COORDS_INITIALISED // Trying to use this object without setting its coordinates?
jassert (colours.size() >= 2);
jassert (numEntries > 0);
auto paddedColours = colours;
const auto colour0 = colours.getReference (0);
if (! approximatelyEqual (colour0.position, 0.0))
paddedColours.insert (0, { 0.0, colour0.colour });
int index = 0;
for (int j = 0; j < paddedColours.size() - 1; ++j)
{
const auto& o = paddedColours.getReference (j + 0);
const auto& p = paddedColours.getReference (j + 1);
const auto numToDo = roundToInt (p.position * (numEntries - 1)) - index;
const auto pix1 = o.colour.getNonPremultipliedPixelARGB();
const auto pix2 = p.colour.getNonPremultipliedPixelARGB();
for (auto i = 0; i < numToDo; ++i)
{
auto blended = pix1;
blended.tween (pix2, (uint32) ((i << 8) / numToDo));
blended.premultiply();
jassert (0 <= index && index < numEntries);
lookupTable[index++] = blended;
}
}
std::fill (lookupTable + index, lookupTable + numEntries, paddedColours.getLast().colour.getPixelARGB());
}
int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock<PixelARGB>& lookupTable) const
{
JUCE_COLOURGRADIENT_CHECK_COORDS_INITIALISED // Trying to use this object without setting its coordinates?
jassert (colours.size() >= 2);
const auto maxExtent = std::invoke ([&]
{
if (! isRadial)
{
return 3 * (int) point1.transformedBy (transform)
.getDistanceFrom (point2.transformedBy (transform));
}
detail::RadialGradientView rg { this };
// If the transform is skewed the maximum extent could be in any direction
const auto r = rg.getEndCircle().r;
Point<float> extentX { r, 0.0f };
Point<float> extentY { 0.0f, r };
return roundToInt (jmax (extentX.transformedBy (transform).getDistanceFromOrigin(),
extentY.transformedBy (transform).getDistanceFromOrigin()));
});
const auto numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8), 3 * (int) maxExtent);
lookupTable.malloc (numEntries);
createLookupTable (lookupTable, numEntries);
return numEntries;
}
bool ColourGradient::isOpaque() const noexcept
{
for (auto& c : colours)
if (! c.colour.isOpaque())
return false;
return true;
}
bool ColourGradient::isInvisible() const noexcept
{
for (auto& c : colours)
if (! c.colour.isTransparent())
return false;
return true;
}
auto ColourGradient::ColourPoint::tie() const
{
return std::tuple (position, colour.getPixelARGB().getNativeARGB());
}
bool ColourGradient::ColourPoint::operator== (ColourPoint other) const noexcept
{
return tie() == other.tie();
}
bool ColourGradient::ColourPoint::operator!= (ColourPoint other) const noexcept
{
return tie() != other.tie();
}
bool ColourGradient::ColourPoint::operator< (ColourPoint other) const noexcept
{
return tie() < other.tie();
}
} // namespace juce
@@ -0,0 +1,279 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
Describes the layout and colours that should be used to paint a colour gradient.
@see Graphics::setGradientFill
@tags{Graphics}
*/
class JUCE_API ColourGradient final
{
public:
/** Specifies how the gradient range outside [0, 1] should be mapped onto the colours.
Follows the SVG/CSS terminology.
*/
enum class SpreadMethod
{
pad,
reflect,
repeat
};
/** Creates an uninitialised gradient.
If you use this constructor instead of the other one, be sure to set all the
object's public member variables before using it!
*/
ColourGradient() noexcept;
//==============================================================================
/** Creates a gradient object.
(x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
colour2 should be. In between them there's a gradient.
If isRadial is true, the colours form a circular gradient with (x1, y1) at
its centre.
The alpha transparencies of the colours are used, so note that
if you blend from transparent to a solid colour, the RGB of the transparent
colour will become visible in parts of the gradient. e.g. blending
from Colour::transparentBlack to Colours::white will produce a
muddy grey colour midway, but Colour::transparentWhite to Colours::white
will be white all the way across.
@see ColourGradient
*/
ColourGradient (Colour colour1, float x1, float y1,
Colour colour2, float x2, float y2,
bool isRadial);
/** Creates a gradient object.
point1 is the location to draw with colour1. Likewise point2 is where
colour2 should be. In between them there's a gradient.
If isRadial is true, the colours form a circular gradient with point1 at
its centre.
The alpha transparencies of the colours are used, so note that
if you blend from transparent to a solid colour, the RGB of the transparent
colour will become visible in parts of the gradient. e.g. blending
from Colour::transparentBlack to Colours::white will produce a
muddy grey colour midway, but Colour::transparentWhite to Colours::white
will be white all the way across.
@see ColourGradient
*/
ColourGradient (Colour colour1, Point<float> point1,
Colour colour2, Point<float> point2,
bool isRadial);
//==============================================================================
/** Creates a vertical linear gradient between two Y coordinates */
static ColourGradient vertical (Colour colour1, float y1,
Colour colour2, float y2);
/** Creates a horizontal linear gradient between two X coordinates */
static ColourGradient horizontal (Colour colour1, float x1,
Colour colour2, float x2);
/** Creates a vertical linear gradient from top to bottom in a rectangle */
template <typename Type>
static ColourGradient vertical (Colour colourTop, Colour colourBottom, Rectangle<Type> area)
{
return vertical (colourTop, (float) area.getY(), colourBottom, (float) area.getBottom());
}
/** Creates a horizontal linear gradient from right to left in a rectangle */
template <typename Type>
static ColourGradient horizontal (Colour colourLeft, Colour colourRight, Rectangle<Type> area)
{
return horizontal (colourLeft, (float) area.getX(), colourRight, (float) area.getRight());
}
//==============================================================================
/** Removes any colours that have been added.
This will also remove any start and end colours, so the gradient won't work. You'll
need to add more colours with addColour().
*/
void clearColours();
/** Adds a colour at a point along the length of the gradient.
This allows the gradient to go through a spectrum of colours, instead of just a
start and end colour.
@param proportionAlongGradient a value between 0 and 1.0, which is the proportion
of the distance along the line between the two points
at which the colour should occur.
@param colour the colour that should be used at this point
@returns the index at which the new point was added
*/
int addColour (double proportionAlongGradient, Colour colour);
/** Removes one of the colours from the gradient. */
void removeColour (int index);
/** Multiplies the alpha value of all the colours by the given scale factor */
void multiplyOpacity (float multiplier) noexcept;
//==============================================================================
/** Returns the number of colour-stops that have been added. */
int getNumColours() const noexcept;
/** Returns the position along the length of the gradient of the colour with this index.
The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
*/
double getColourPosition (int index) const noexcept;
/** Returns the colour that was added with a given index.
The index is from 0 to getNumColours() - 1.
*/
Colour getColour (int index) const noexcept;
/** Changes the colour at a given index.
The index is from 0 to getNumColours() - 1.
*/
void setColour (int index, Colour newColour) noexcept;
/** Returns the an interpolated colour at any position along the gradient.
@param position the position along the gradient, between 0 and 1
*/
Colour getColourAtPosition (double position) const noexcept;
//==============================================================================
/** Creates a set of interpolated premultiplied ARGB values.
This will resize the HeapBlock, fill it with the colours, and will return the number of
colours that it added.
When calling this, the ColourGradient must have at least 2 colour stops specified.
*/
int createLookupTable (const AffineTransform& transform, HeapBlock<PixelARGB>& resultLookupTable) const;
/** Creates a set of interpolated premultiplied ARGB values.
This will fill an array of a user-specified size with the gradient, interpolating to fit.
The numEntries argument specifies the size of the array, and this size must be greater than zero.
When calling this, the ColourGradient must have at least 2 colour stops specified.
*/
void createLookupTable (PixelARGB* resultLookupTable, int numEntries) const noexcept;
/** Creates a set of interpolated premultiplied ARGB values.
This will fill an array of a user-specified size with the gradient, interpolating to fit.
When calling this, the ColourGradient must have at least 2 colour stops specified.
*/
template <size_t NumEntries>
void createLookupTable (PixelARGB (&resultLookupTable)[NumEntries]) const noexcept
{
static_assert (NumEntries != 0);
createLookupTable (resultLookupTable, NumEntries);
}
/** Returns true if all colours are opaque. */
bool isOpaque() const noexcept;
/** Returns true if all colours are completely transparent. */
bool isInvisible() const noexcept;
//==============================================================================
Point<float> point1, point2;
/** If true, the gradient should be filled circularly, centred around
point1, with point2 defining a point on the circumference.
If false, the gradient is linear between the two points.
*/
bool isRadial;
/** When isRadial is true, and this value is set to a non-negative value, point2 becomes the
centre of the gradient's end circle, and endRadius defines its radius. point1 then becomes
the centre of the gradient's start circle, and startRadius defines its radius.
Otherwise, point1 is the centre of both the start and end circles, and point2 defines a
point on the circumference. The end radius is then calculated as the distance between
point1 and point2.
*/
float endRadius = -1.0f;
/** If isRadial is true, and endRadius is set to a non-negative value, this specifies the radius
of the gradient's start circle.
*/
float startRadius = 0.0f;
/** @see SpreadMethod */
SpreadMethod spreadMethod = SpreadMethod::pad;
bool operator== (const ColourGradient&) const noexcept;
bool operator!= (const ColourGradient&) const noexcept;
/** This comparison, and the other ordered comparisons are provided only for compatibility with
ordered container types like std::set and std::map.
*/
bool operator< (const ColourGradient&) const noexcept;
bool operator<= (const ColourGradient&) const noexcept;
bool operator> (const ColourGradient&) const noexcept;
bool operator>= (const ColourGradient&) const noexcept;
private:
//==============================================================================
struct ColourPoint
{
bool operator== (ColourPoint other) const noexcept;
bool operator!= (ColourPoint other) const noexcept;
bool operator< (ColourPoint other) const noexcept;
double position;
Colour colour;
private:
auto tie() const;
};
struct ColourPointArrayComparisons;
auto tie() const;
Array<ColourPoint> colours;
JUCE_LEAK_DETECTOR (ColourGradient)
};
} // namespace juce
@@ -0,0 +1,205 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
Colour Colours::findColourForName (const String& colourName,
Colour defaultColour)
{
struct StringHashAndColour { uint32 stringHash, colour; };
static const StringHashAndColour presets[]
{
{ 0x05978fff, 0xff000000 }, /* black */
{ 0x06bdcc29, 0xffffffff }, /* white */
{ 0x002e305a, 0xff0000ff }, /* blue */
{ 0x00308adf, 0xff808080 }, /* grey */
{ 0x00308a63, 0xff808080 }, /* gray */
{ 0x05e0cf03, 0xff008000 }, /* green */
{ 0x0001b891, 0xffff0000 }, /* red */
{ 0xd43c6474, 0xffffff00 }, /* yellow */
{ 0x620886da, 0xfff0f8ff }, /* aliceblue */
{ 0x20a2676a, 0xfffaebd7 }, /* antiquewhite */
{ 0x002dcebc, 0xff00ffff }, /* aqua */
{ 0x46bb5f7e, 0xff7fffd4 }, /* aquamarine */
{ 0x0590228f, 0xfff0ffff }, /* azure */
{ 0x05947fe4, 0xfff5f5dc }, /* beige */
{ 0xad388e35, 0xffffe4c4 }, /* bisque */
{ 0x00674f7e, 0xffffebcd }, /* blanchedalmond */
{ 0x39129959, 0xff8a2be2 }, /* blueviolet */
{ 0x059a8136, 0xffa52a2a }, /* brown */
{ 0x89cea8f9, 0xffdeb887 }, /* burlywood */
{ 0x0fa260cf, 0xff5f9ea0 }, /* cadetblue */
{ 0x6b748956, 0xff7fff00 }, /* chartreuse */
{ 0x2903623c, 0xffd2691e }, /* chocolate */
{ 0x05a74431, 0xffff7f50 }, /* coral */
{ 0x618d42dd, 0xff6495ed }, /* cornflowerblue */
{ 0xe4b479fd, 0xfffff8dc }, /* cornsilk */
{ 0x3d8c4edf, 0xffdc143c }, /* crimson */
{ 0x002ed323, 0xff00ffff }, /* cyan */
{ 0x67cc74d0, 0xff00008b }, /* darkblue */
{ 0x67cd1799, 0xff008b8b }, /* darkcyan */
{ 0x31bbd168, 0xffb8860b }, /* darkgoldenrod */
{ 0x67cecf55, 0xff555555 }, /* darkgrey */
{ 0x67ceced9, 0xff555555 }, /* darkgray */
{ 0x920b194d, 0xff006400 }, /* darkgreen */
{ 0x923edd4c, 0xffbdb76b }, /* darkkhaki */
{ 0x5c293873, 0xff8b008b }, /* darkmagenta */
{ 0x6b6671fe, 0xff556b2f }, /* darkolivegreen */
{ 0xbcfd2524, 0xffff8c00 }, /* darkorange */
{ 0xbcfdf799, 0xff9932cc }, /* darkorchid */
{ 0x55ee0d5b, 0xff8b0000 }, /* darkred */
{ 0xc2e5f564, 0xffe9967a }, /* darksalmon */
{ 0x61be858a, 0xff8fbc8f }, /* darkseagreen */
{ 0xc2b0f2bd, 0xff483d8b }, /* darkslateblue */
{ 0xc2b34d42, 0xff2f4f4f }, /* darkslategrey */
{ 0xc2b34cc6, 0xff2f4f4f }, /* darkslategray */
{ 0x7cf2b06b, 0xff00ced1 }, /* darkturquoise */
{ 0xc8769375, 0xff9400d3 }, /* darkviolet */
{ 0x25832862, 0xffff1493 }, /* deeppink */
{ 0xfcad568f, 0xff00bfff }, /* deepskyblue */
{ 0x634c8b67, 0xff696969 }, /* dimgrey */
{ 0x634c8aeb, 0xff696969 }, /* dimgray */
{ 0x45c1ce55, 0xff1e90ff }, /* dodgerblue */
{ 0xef19e3cb, 0xffb22222 }, /* firebrick */
{ 0xb852b195, 0xfffffaf0 }, /* floralwhite */
{ 0xd086fd06, 0xff228b22 }, /* forestgreen */
{ 0xe106b6d7, 0xffff00ff }, /* fuchsia */
{ 0x7880d61e, 0xffdcdcdc }, /* gainsboro */
{ 0x2018a2fa, 0xfff8f8ff }, /* ghostwhite */
{ 0x00308060, 0xffffd700 }, /* gold */
{ 0xb3b3bc1e, 0xffdaa520 }, /* goldenrod */
{ 0xbab8a537, 0xffadff2f }, /* greenyellow */
{ 0xe4cacafb, 0xfff0fff0 }, /* honeydew */
{ 0x41892743, 0xffff69b4 }, /* hotpink */
{ 0xd5796f1a, 0xffcd5c5c }, /* indianred */
{ 0xb969fed2, 0xff4b0082 }, /* indigo */
{ 0x05fef6a9, 0xfffffff0 }, /* ivory */
{ 0x06149302, 0xfff0e68c }, /* khaki */
{ 0xad5a05c7, 0xffe6e6fa }, /* lavender */
{ 0x7c4d5b99, 0xfffff0f5 }, /* lavenderblush */
{ 0x41cc4377, 0xff7cfc00 }, /* lawngreen */
{ 0x195756f0, 0xfffffacd }, /* lemonchiffon */
{ 0x28e4ea70, 0xffadd8e6 }, /* lightblue */
{ 0xf3c7ccdb, 0xfff08080 }, /* lightcoral */
{ 0x28e58d39, 0xffe0ffff }, /* lightcyan */
{ 0x21234e3c, 0xfffafad2 }, /* lightgoldenrodyellow */
{ 0xf40157ad, 0xff90ee90 }, /* lightgreen */
{ 0x28e744f5, 0xffd3d3d3 }, /* lightgrey */
{ 0x28e74479, 0xffd3d3d3 }, /* lightgray */
{ 0x28eb3b8c, 0xffffb6c1 }, /* lightpink */
{ 0x9fb78304, 0xffffa07a }, /* lightsalmon */
{ 0x50632b2a, 0xff20b2aa }, /* lightseagreen */
{ 0x68fb7b25, 0xff87cefa }, /* lightskyblue */
{ 0xa8a35ba2, 0xff778899 }, /* lightslategrey */
{ 0xa8a35b26, 0xff778899 }, /* lightslategray */
{ 0xa20d484f, 0xffb0c4de }, /* lightsteelblue */
{ 0xaa2cf10a, 0xffffffe0 }, /* lightyellow */
{ 0x0032afd5, 0xff00ff00 }, /* lime */
{ 0x607bbc4e, 0xff32cd32 }, /* limegreen */
{ 0x06234efa, 0xfffaf0e6 }, /* linen */
{ 0x316858a9, 0xffff00ff }, /* magenta */
{ 0xbf8ca470, 0xff800000 }, /* maroon */
{ 0xbd58e0b3, 0xff66cdaa }, /* mediumaquamarine */
{ 0x967dfd4f, 0xff0000cd }, /* mediumblue */
{ 0x056f5c58, 0xffba55d3 }, /* mediumorchid */
{ 0x07556b71, 0xff9370db }, /* mediumpurple */
{ 0x5369b689, 0xff3cb371 }, /* mediumseagreen */
{ 0x066be19e, 0xff7b68ee }, /* mediumslateblue */
{ 0x3256b281, 0xff00fa9a }, /* mediumspringgreen */
{ 0xc0ad9f4c, 0xff48d1cc }, /* mediumturquoise */
{ 0x628e63dd, 0xffc71585 }, /* mediumvioletred */
{ 0x168eb32a, 0xff191970 }, /* midnightblue */
{ 0x4306b960, 0xfff5fffa }, /* mintcream */
{ 0x4cbc0e6b, 0xffffe4e1 }, /* mistyrose */
{ 0xd9447d59, 0xffffe4b5 }, /* moccasin */
{ 0xe97218a6, 0xffffdead }, /* navajowhite */
{ 0x00337bb6, 0xff000080 }, /* navy */
{ 0xadd2d33e, 0xfffdf5e6 }, /* oldlace */
{ 0x064ee1db, 0xff808000 }, /* olive */
{ 0x9e33a98a, 0xff6b8e23 }, /* olivedrab */
{ 0xc3de262e, 0xffffa500 }, /* orange */
{ 0x58bebba3, 0xffff4500 }, /* orangered */
{ 0xc3def8a3, 0xffda70d6 }, /* orchid */
{ 0x28cb4834, 0xffeee8aa }, /* palegoldenrod */
{ 0x3d9dd619, 0xff98fb98 }, /* palegreen */
{ 0x74022737, 0xffafeeee }, /* paleturquoise */
{ 0x15e2ebc8, 0xffdb7093 }, /* palevioletred */
{ 0x5fd898e2, 0xffffefd5 }, /* papayawhip */
{ 0x93e1b776, 0xffffdab9 }, /* peachpuff */
{ 0x003472f8, 0xffcd853f }, /* peru */
{ 0x00348176, 0xffffc0cb }, /* pink */
{ 0x00348d94, 0xffdda0dd }, /* plum */
{ 0xd036be93, 0xffb0e0e6 }, /* powderblue */
{ 0xc5c507bc, 0xff800080 }, /* purple */
{ 0xf381f607, 0xff663399 }, /* rebeccapurple */
{ 0xa89d65b3, 0xffbc8f8f }, /* rosybrown */
{ 0xbd9413e1, 0xff4169e1 }, /* royalblue */
{ 0xf456044f, 0xff8b4513 }, /* saddlebrown */
{ 0xc9c6f66e, 0xfffa8072 }, /* salmon */
{ 0x0bb131e1, 0xfff4a460 }, /* sandybrown */
{ 0x34636c14, 0xff2e8b57 }, /* seagreen */
{ 0x3507fb41, 0xfffff5ee }, /* seashell */
{ 0xca348772, 0xffa0522d }, /* sienna */
{ 0xca37d30d, 0xffc0c0c0 }, /* silver */
{ 0x80da74fb, 0xff87ceeb }, /* skyblue */
{ 0x44a8dd73, 0xff6a5acd }, /* slateblue */
{ 0x44ab37f8, 0xff708090 }, /* slategrey */
{ 0x44ab377c, 0xff708090 }, /* slategray */
{ 0x0035f183, 0xfffffafa }, /* snow */
{ 0xd5440d16, 0xff00ff7f }, /* springgreen */
{ 0x3e1524a5, 0xff4682b4 }, /* steelblue */
{ 0x0001bfa1, 0xffd2b48c }, /* tan */
{ 0x0036425c, 0xff008080 }, /* teal */
{ 0xafc8858f, 0xffd8bfd8 }, /* thistle */
{ 0xcc41600a, 0xffff6347 }, /* tomato */
{ 0xfeea9b21, 0xff40e0d0 }, /* turquoise */
{ 0xcf57947f, 0xffee82ee }, /* violet */
{ 0x06bdbae7, 0xfff5deb3 }, /* wheat */
{ 0x10802ee6, 0xfff5f5f5 }, /* whitesmoke */
{ 0xe1b5130f, 0xff9acd32 }, /* yellowgreen */
};
const auto hash = (uint32) colourName.trim().toLowerCase().hashCode();
for (auto entry : presets)
if (entry.stringHash == hash)
return Colour (entry.colour);
return defaultColour;
}
} // namespace juce
@@ -0,0 +1,200 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
/**
Contains a set of predefined named colours (mostly standard HTML colours)
@see Colour
@tags{Graphics}
*/
namespace juce::Colours
{
const Colour transparentBlack { 0 };
const Colour transparentWhite { 0x00ffffff };
const Colour aliceblue { 0xfff0f8ff };
const Colour antiquewhite { 0xfffaebd7 };
const Colour aqua { 0xff00ffff };
const Colour aquamarine { 0xff7fffd4 };
const Colour azure { 0xfff0ffff };
const Colour beige { 0xfff5f5dc };
const Colour bisque { 0xffffe4c4 };
const Colour black { 0xff000000 };
const Colour blanchedalmond { 0xffffebcd };
const Colour blue { 0xff0000ff };
const Colour blueviolet { 0xff8a2be2 };
const Colour brown { 0xffa52a2a };
const Colour burlywood { 0xffdeb887 };
const Colour cadetblue { 0xff5f9ea0 };
const Colour chartreuse { 0xff7fff00 };
const Colour chocolate { 0xffd2691e };
const Colour coral { 0xffff7f50 };
const Colour cornflowerblue { 0xff6495ed };
const Colour cornsilk { 0xfffff8dc };
const Colour crimson { 0xffdc143c };
const Colour cyan { 0xff00ffff };
const Colour darkblue { 0xff00008b };
const Colour darkcyan { 0xff008b8b };
const Colour darkgoldenrod { 0xffb8860b };
const Colour darkgrey { 0xff555555 };
const Colour darkgreen { 0xff006400 };
const Colour darkkhaki { 0xffbdb76b };
const Colour darkmagenta { 0xff8b008b };
const Colour darkolivegreen { 0xff556b2f };
const Colour darkorange { 0xffff8c00 };
const Colour darkorchid { 0xff9932cc };
const Colour darkred { 0xff8b0000 };
const Colour darksalmon { 0xffe9967a };
const Colour darkseagreen { 0xff8fbc8f };
const Colour darkslateblue { 0xff483d8b };
const Colour darkslategrey { 0xff2f4f4f };
const Colour darkturquoise { 0xff00ced1 };
const Colour darkviolet { 0xff9400d3 };
const Colour deeppink { 0xffff1493 };
const Colour deepskyblue { 0xff00bfff };
const Colour dimgrey { 0xff696969 };
const Colour dodgerblue { 0xff1e90ff };
const Colour firebrick { 0xffb22222 };
const Colour floralwhite { 0xfffffaf0 };
const Colour forestgreen { 0xff228b22 };
const Colour fuchsia { 0xffff00ff };
const Colour gainsboro { 0xffdcdcdc };
const Colour ghostwhite { 0xfff8f8ff };
const Colour gold { 0xffffd700 };
const Colour goldenrod { 0xffdaa520 };
const Colour grey { 0xff808080 };
const Colour green { 0xff008000 };
const Colour greenyellow { 0xffadff2f };
const Colour honeydew { 0xfff0fff0 };
const Colour hotpink { 0xffff69b4 };
const Colour indianred { 0xffcd5c5c };
const Colour indigo { 0xff4b0082 };
const Colour ivory { 0xfffffff0 };
const Colour khaki { 0xfff0e68c };
const Colour lavender { 0xffe6e6fa };
const Colour lavenderblush { 0xfffff0f5 };
const Colour lawngreen { 0xff7cfc00 };
const Colour lemonchiffon { 0xfffffacd };
const Colour lightblue { 0xffadd8e6 };
const Colour lightcoral { 0xfff08080 };
const Colour lightcyan { 0xffe0ffff };
const Colour lightgoldenrodyellow { 0xfffafad2 };
const Colour lightgreen { 0xff90ee90 };
const Colour lightgrey { 0xffd3d3d3 };
const Colour lightpink { 0xffffb6c1 };
const Colour lightsalmon { 0xffffa07a };
const Colour lightseagreen { 0xff20b2aa };
const Colour lightskyblue { 0xff87cefa };
const Colour lightslategrey { 0xff778899 };
const Colour lightsteelblue { 0xffb0c4de };
const Colour lightyellow { 0xffffffe0 };
const Colour lime { 0xff00ff00 };
const Colour limegreen { 0xff32cd32 };
const Colour linen { 0xfffaf0e6 };
const Colour magenta { 0xffff00ff };
const Colour maroon { 0xff800000 };
const Colour mediumaquamarine { 0xff66cdaa };
const Colour mediumblue { 0xff0000cd };
const Colour mediumorchid { 0xffba55d3 };
const Colour mediumpurple { 0xff9370db };
const Colour mediumseagreen { 0xff3cb371 };
const Colour mediumslateblue { 0xff7b68ee };
const Colour mediumspringgreen { 0xff00fa9a };
const Colour mediumturquoise { 0xff48d1cc };
const Colour mediumvioletred { 0xffc71585 };
const Colour midnightblue { 0xff191970 };
const Colour mintcream { 0xfff5fffa };
const Colour mistyrose { 0xffffe4e1 };
const Colour moccasin { 0xffffe4b5 };
const Colour navajowhite { 0xffffdead };
const Colour navy { 0xff000080 };
const Colour oldlace { 0xfffdf5e6 };
const Colour olive { 0xff808000 };
const Colour olivedrab { 0xff6b8e23 };
const Colour orange { 0xffffa500 };
const Colour orangered { 0xffff4500 };
const Colour orchid { 0xffda70d6 };
const Colour palegoldenrod { 0xffeee8aa };
const Colour palegreen { 0xff98fb98 };
const Colour paleturquoise { 0xffafeeee };
const Colour palevioletred { 0xffdb7093 };
const Colour papayawhip { 0xffffefd5 };
const Colour peachpuff { 0xffffdab9 };
const Colour peru { 0xffcd853f };
const Colour pink { 0xffffc0cb };
const Colour plum { 0xffdda0dd };
const Colour powderblue { 0xffb0e0e6 };
const Colour purple { 0xff800080 };
const Colour rebeccapurple { 0xff663399 };
const Colour red { 0xffff0000 };
const Colour rosybrown { 0xffbc8f8f };
const Colour royalblue { 0xff4169e1 };
const Colour saddlebrown { 0xff8b4513 };
const Colour salmon { 0xfffa8072 };
const Colour sandybrown { 0xfff4a460 };
const Colour seagreen { 0xff2e8b57 };
const Colour seashell { 0xfffff5ee };
const Colour sienna { 0xffa0522d };
const Colour silver { 0xffc0c0c0 };
const Colour skyblue { 0xff87ceeb };
const Colour slateblue { 0xff6a5acd };
const Colour slategrey { 0xff708090 };
const Colour snow { 0xfffffafa };
const Colour springgreen { 0xff00ff7f };
const Colour steelblue { 0xff4682b4 };
const Colour tan { 0xffd2b48c };
const Colour teal { 0xff008080 };
const Colour thistle { 0xffd8bfd8 };
const Colour tomato { 0xffff6347 };
const Colour turquoise { 0xff40e0d0 };
const Colour violet { 0xffee82ee };
const Colour wheat { 0xfff5deb3 };
const Colour white { 0xffffffff };
const Colour whitesmoke { 0xfff5f5f5 };
const Colour yellow { 0xffffff00 };
const Colour yellowgreen { 0xff9acd32 };
/** Attempts to look up a string in the list of known colour names, and return
the appropriate colour.
A non-case-sensitive search is made of the list of predefined colours, and
if a match is found, that colour is returned. If no match is found, the
colour passed in as the defaultColour parameter is returned.
*/
JUCE_API Colour findColourForName (const String& colourName,
Colour defaultColour);
} // namespace juce::Colours
@@ -0,0 +1,177 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
FillType::FillType() noexcept
: colour (0xff000000)
{
}
FillType::FillType (Colour c) noexcept
: colour (c)
{
}
FillType::FillType (const ColourGradient& g)
: colour (0xff000000), gradient (new ColourGradient (g))
{
}
FillType::FillType (ColourGradient&& g)
: colour (0xff000000), gradient (new ColourGradient (std::move (g)))
{
}
FillType::FillType (const Image& im, const AffineTransform& t) noexcept
: colour (0xff000000), image (im), transform (t)
{
}
FillType::FillType (const FillType& other)
: colour (other.colour),
gradient (createCopyIfNotNull (other.gradient.get())),
image (other.image),
transform (other.transform)
{
}
FillType& FillType::operator= (const FillType& other)
{
if (this != &other)
{
colour = other.colour;
gradient.reset (createCopyIfNotNull (other.gradient.get()));
image = other.image;
transform = other.transform;
}
return *this;
}
FillType::FillType (FillType&& other) noexcept
: colour (other.colour),
gradient (std::move (other.gradient)),
image (std::move (other.image)),
transform (other.transform)
{
}
FillType& FillType::operator= (FillType&& other) noexcept
{
jassert (this != &other); // hopefully the compiler should make this situation impossible!
colour = other.colour;
gradient = std::move (other.gradient);
image = std::move (other.image);
transform = other.transform;
return *this;
}
FillType::~FillType() noexcept
{
}
bool FillType::operator== (const FillType& other) const
{
return colour == other.colour && image == other.image
&& transform == other.transform
&& (gradient == other.gradient
|| (gradient != nullptr && other.gradient != nullptr && *gradient == *other.gradient));
}
bool FillType::operator!= (const FillType& other) const
{
return ! operator== (other);
}
void FillType::setColour (Colour newColour) noexcept
{
gradient.reset();
image = {};
colour = newColour;
}
void FillType::setGradient (const ColourGradient& newGradient)
{
if (gradient != nullptr)
{
*gradient = newGradient;
}
else
{
image = {};
gradient.reset (new ColourGradient (newGradient));
colour = Colours::black;
}
}
Image FillType::getSoftwareGradientImage (const Rectangle<int>& clip) const
{
jassert (isGradient());
Image result (Image::ARGB, clip.getWidth(), clip.getHeight(), true, SoftwareImageType{});
Graphics g (result);
g.setFillType (transformed (AffineTransform::translation ((float) -clip.getX(), (float) -clip.getY())));
g.fillAll();
return result;
}
void FillType::setTiledImage (const Image& newImage, const AffineTransform& newTransform) noexcept
{
gradient.reset();
image = newImage;
transform = newTransform;
colour = Colours::black;
}
void FillType::setOpacity (const float newOpacity) noexcept
{
colour = colour.withAlpha (newOpacity);
}
bool FillType::isInvisible() const noexcept
{
return colour.isTransparent() || (gradient != nullptr && gradient->isInvisible());
}
FillType FillType::transformed (const AffineTransform& t) const
{
FillType f (*this);
f.transform = f.transform.followedBy (t);
return f;
}
} // namespace juce
@@ -0,0 +1,171 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
Represents a colour or fill pattern to use for rendering paths.
This is used by the Graphics and DrawablePath classes as a way to encapsulate
a brush type. It can either be a solid colour, a gradient, or a tiled image.
@see Graphics::setFillType, DrawablePath::setFill
@tags{Graphics}
*/
class JUCE_API FillType final
{
public:
//==============================================================================
/** Creates a default fill type, of solid black. */
FillType() noexcept;
/** Creates a fill type of a solid colour.
@see setColour
*/
FillType (Colour colour) noexcept;
/** Creates a gradient fill type.
@see setGradient
*/
FillType (const ColourGradient& gradient);
/** Creates a gradient fill type.
@see setGradient
*/
FillType (ColourGradient&& gradient);
/** Creates a tiled image fill type. The transform allows you to set the scaling, offset
and rotation of the pattern.
@see setTiledImage
*/
FillType (const Image& image, const AffineTransform& transform) noexcept;
/** Creates a copy of another FillType. */
FillType (const FillType&);
/** Makes a copy of another FillType. */
FillType& operator= (const FillType&);
/** Move constructor */
FillType (FillType&&) noexcept;
/** Move assignment operator */
FillType& operator= (FillType&&) noexcept;
/** Destructor. */
~FillType() noexcept;
//==============================================================================
/** Returns true if this is a solid colour fill, and not a gradient or image. */
bool isColour() const noexcept { return gradient == nullptr && image.isNull(); }
/** Returns true if this is a gradient fill. */
bool isGradient() const noexcept { return gradient != nullptr; }
/** Returns true if this is a tiled image pattern fill. */
bool isTiledImage() const noexcept { return image.isValid(); }
/** Turns this object into a solid colour fill.
If the object was an image or gradient, those fields will no longer be valid. */
void setColour (Colour newColour) noexcept;
/** Turns this object into a gradient fill. */
void setGradient (const ColourGradient& newGradient);
/** Turns this object into a tiled image fill type. The transform allows you to set
the scaling, offset and rotation of the pattern.
*/
void setTiledImage (const Image& image, const AffineTransform& transform) noexcept;
/** Changes the opacity that should be used.
If the fill is a solid colour, this just changes the opacity of that colour. For
gradients and image tiles, it changes the opacity that will be used for them.
*/
void setOpacity (float newOpacity) noexcept;
/** Returns the current opacity to be applied to the colour, gradient, or image.
@see setOpacity
*/
float getOpacity() const noexcept { return colour.getFloatAlpha(); }
/** Returns true if this fill type is completely transparent. */
bool isInvisible() const noexcept;
/** Returns a copy of this fill, adding the specified transform applied to the
existing transform.
*/
FillType transformed (const AffineTransform& transform) const;
//==============================================================================
/** The solid colour being used.
If the fill type is not a solid colour, the alpha channel of this colour indicates
the opacity that should be used for the fill, and the RGB channels are ignored.
*/
Colour colour;
/** Returns the gradient that should be used for filling.
This will be nullptr if the object is some other type of fill.
If a gradient is active, the overall opacity with which it should be applied
is indicated by the alpha channel of the colour variable.
*/
std::unique_ptr<ColourGradient> gradient;
/** The image that should be used for tiling.
If an image fill is active, the overall opacity with which it should be applied
is indicated by the alpha channel of the colour variable.
*/
Image image;
/** The transform that should be applied to the image or gradient that's being drawn. */
AffineTransform transform;
//==============================================================================
bool operator== (const FillType&) const;
bool operator!= (const FillType&) const;
/** @internal
Returns an image that uses the software renderer to fill the clip region.
*/
Image getSoftwareGradientImage (const Rectangle<int>& clip) const;
private:
JUCE_LEAK_DETECTOR (FillType)
};
} // namespace juce
@@ -0,0 +1,539 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
#if JUCE_UNIT_TESTS
struct PixelFormatsConstexprTests
{
PixelFormatsConstexprTests() = delete;
template <typename PixelType>
static constexpr auto constexprCheck (PixelType p)
{
PixelType other{};
other.setARGB (p.getBlue(), p.getAlpha(), p.getGreen(), p.getRed());
p.set (other);
p.blend (p);
p.blend (p, 100);
p.tween (p, 50);
p.multiplyAlpha (0.9f);
p.premultiply();
p.setAlpha (200);
p.unpremultiply();
p.desaturate();
return p.getNativeARGB()
+ p.getInARGBMaskOrder()
+ p.getInARGBMemoryOrder()
+ p.getEvenBytes()
+ p.getOddBytes()
+ p.getAlpha()
+ p.getRed()
+ p.getGreen()
+ p.getBlue()
+ maskPixelComponents (p.getNativeARGB())
+ clampPixelComponents (p.getNativeARGB());
}
};
static_assert (PixelFormatsConstexprTests::constexprCheck<PixelARGB> ({ 10, 20, 30, 40 }) != 0);
static_assert (PixelFormatsConstexprTests::constexprCheck<PixelRGB> ({ 50, 60, 70 }) != 0);
static_assert (PixelFormatsConstexprTests::constexprCheck<PixelAlpha> ({ 80 }) != 0);
//==============================================================================
class PixelDouble
{
public:
explicit PixelDouble (Colour colour)
: r ((double) colour.getRed() / 255.0),
g ((double) colour.getGreen() / 255.0),
b ((double) colour.getBlue() / 255.0),
a ((double) colour.getAlpha() / 255.0)
{
premultiply();
}
explicit PixelDouble (PixelARGB p)
: r ((double) p.getRed() / 255.0),
g ((double) p.getGreen() / 255.0),
b ((double) p.getBlue() / 255.0),
a ((double) p.getAlpha() / 255.0)
{
}
PixelDouble operator* (double scalar) const
{
auto copy = *this;
copy.r = r * scalar;
copy.g = g * scalar;
copy.b = b * scalar;
copy.a = a * scalar;
copy.clamp();
return copy;
}
PixelDouble operator+ (PixelDouble other) const
{
auto copy = *this;
copy.r += other.r;
copy.g += other.g;
copy.b += other.b;
copy.a += other.a;
copy.clamp();
return copy;
}
void blend (PixelDouble src, BlendMode mode, uint32 extraAlpha = 255)
{
src = src * (extraAlpha / 255.0);
switch (mode)
{
// R = S + D * (1 - Sa)
case BlendMode::sourceOver:
*this = src + *this * (1.0 - src.a);
return;
// R = S
case BlendMode::source:
*this = src;
return;
//< R = D * Sa
case BlendMode::destinationIn:
*this = *this * src.a;
return;
// R = D * (1 - Sa)
case BlendMode::destinationOut:
*this = *this * (1.0 - src.a);
return;
}
jassertfalse;
}
void blend (PixelDouble src, uint32 extraAlpha = 255)
{
blend (src, BlendMode::sourceOver, extraAlpha);
}
PixelARGB toPixelARGB() const
{
auto r8 = (uint8) std::round (r * 255.0);
auto g8 = (uint8) std::round (g * 255.0);
auto b8 = (uint8) std::round (b * 255.0);
auto a8 = (uint8) std::round (a * 255.0);
return PixelARGB (a8, r8, g8, b8);
}
bool operator== (const PixelARGB& other) const
{
auto pixelARGB = toPixelARGB();
return pixelARGB.getAlpha() == other.getAlpha()
&& pixelARGB.getRed() == other.getRed()
&& pixelARGB.getGreen() == other.getGreen()
&& pixelARGB.getBlue() == other.getBlue();
}
bool operator!= (const PixelARGB& other) const
{
return ! operator== (other);
}
bool verifyChannelError (const PixelARGB& other, std::array<int64, 4>& acc, int64 maxAllowed = 1) const
{
auto expected = toPixelARGB();
auto dAAbs = std::abs ((int64) expected.getAlpha() - (int64) other.getAlpha());
auto dRAbs = std::abs ((int64) expected.getRed() - (int64) other.getRed());
auto dGAbs = std::abs ((int64) expected.getGreen() - (int64) other.getGreen());
auto dBAbs = std::abs ((int64) expected.getBlue() - (int64) other.getBlue());
acc[0] += dAAbs;
acc[1] += dRAbs;
acc[2] += dGAbs;
acc[3] += dBAbs;
return std::max ({ dAAbs, dRAbs, dGAbs, dBAbs }) <= maxAllowed;
}
private:
void premultiply()
{
r *= a;
g *= a;
b *= a;
}
void clamp()
{
r = std::clamp (r, 0.0, 1.0);
g = std::clamp (g, 0.0, 1.0);
b = std::clamp (b, 0.0, 1.0);
a = std::clamp (a, 0.0, 1.0);
}
double r{};
double g{};
double b{};
double a{};
};
static String toString (PixelARGB p)
{
String s;
s << "("
<< (int) p.getAlpha() << ", " << (int) p.getRed() << ", " << (int) p.getGreen() << ", " << (int) p.getBlue()
<< ")";
return s;
}
static String toString (std::array<int64, 4> err)
{
String s;
s << "(" << err[0] << ", " << err[1] << ", " << err[2] << ", " << err[3] << ")";
return s;
}
static String toString (BlendMode mode)
{
switch (mode)
{
case BlendMode::sourceOver: return "sourceOver";
case BlendMode::source: return "source";
case BlendMode::destinationIn: return "destinationIn";
case BlendMode::destinationOut: return "destinationOut";
}
jassertfalse;
return {};
}
static PixelARGB makePixelARGB (int a, int r, int g, int b)
{
int channels[] = { a, r, g, b };
const auto inputsValid = std::all_of (std::begin (channels),
std::end (channels),
[] (int v) { return 0 <= v && v <= 255; });
if (! inputsValid)
{
jassertfalse;
return {};
}
return PixelARGB { (uint8) a, (uint8) r, (uint8) g, (uint8) b };
}
static bool equals (PixelARGB a, PixelARGB b)
{
return a.getAlpha() == b.getAlpha()
&& a.getRed() == b.getRed()
&& a.getGreen() == b.getGreen()
&& a.getBlue() == b.getBlue();
}
class PixelFormatsUnitTests : public UnitTest
{
public:
PixelFormatsUnitTests() : UnitTest ("PixelFormats", UnitTestCategories::graphics)
{
}
static String createErrorMessage (PixelARGB dest, PixelARGB source, PixelDouble expected, PixelARGB actual)
{
String errorMessage;
errorMessage << toString (dest) << " <- " << toString (source)
<< " expected: " << toString (expected.toPixelARGB())
<< " actual: " << toString (actual);
return errorMessage;
}
template <typename Callback>
static void iterateOverValidPremult (Callback&& func)
{
const uint8 channelValues[] = { 0, 1, 3, 127, 128, 129, 254, 255 };
for (auto sA : channelValues)
{
for (auto dA : channelValues)
{
for (auto sR : channelValues)
{
if (sR > sA)
break;
for (auto sG : channelValues)
{
if (sG > sA)
break;
for (auto sB : channelValues)
{
if (sB > sA)
break;
for (auto dR : channelValues)
{
if (dR > dA)
break;
for (auto dG : channelValues)
{
if (dG > dA)
break;
for (auto dB : channelValues)
{
if (dB > dA)
break;
if (! func (PixelARGB (sA, sR, sG, sB), PixelARGB (dA, dR, dG, dB)))
return;
}
}
}
}
}
}
}
}
}
void runTest() override
{
beginTest ("PixelRGBA basic blending: opaque black over white");
{
const auto dest = makePixelARGB (255, 255, 255, 255);
const auto source = makePixelARGB (255, 0, 0, 0);
const auto expected = makePixelARGB (255, 0, 0, 0);
auto actual = dest;
actual.blend (source);
if (! equals (actual, expected))
{
expect (false,
"Blending opaque black over opaque white should be opaque black. "
+ createErrorMessage (dest, source, PixelDouble (expected), actual));
return;
}
}
beginTest ("PixelRGBA basic blending: transparent black over white");
{
auto dest = makePixelARGB (255, 255, 255, 255);
dest.blend (makePixelARGB (0, 0, 0, 0));
expect (equals (dest, makePixelARGB (255, 255, 255, 255)),
"Blending transparent black over white should be white");
}
beginTest ("PixelRGBA basic blending: Rounding errors should never exceed 1 in any channel");
{
std::array<int64, 4> errors{};
iterateOverValidPremult ([this, &errors] (PixelARGB source, PixelARGB dest)
{
auto actual = dest;
actual.blend (source);
PixelDouble sourcePixel (source);
PixelDouble expected (dest);
expected.blend (sourcePixel);
if (! expected.verifyChannelError (actual, errors))
{
expect (false,
"Rounding error in excess of 1 encountered. "
+ createErrorMessage (dest, source, expected, actual));
return false;
}
return true;
});
const auto expectedErrors = std::array<int64, 4> { 0, 0, 0, 0 };
expect (errors == expectedErrors,
"Rounding errors unexpectedly changed compared to JUCE 8.0.12. Expected: "
+ toString (expectedErrors) + " actual: " + toString (errors));
}
beginTest ("PixelRGBA blending with extra alpha: Rounding errors should never exceed 2 in any channel");
{
for (auto mode : { BlendMode::sourceOver, BlendMode::source, BlendMode::destinationIn, BlendMode::destinationOut })
{
std::array<int64, 4> errors{};
for (auto extraAlpha : { 0u, 1u, 64u, 128u, 192u, 244u, 255u })
{
iterateOverValidPremult ([this, extraAlpha, &errors, mode] (PixelARGB source, PixelARGB dest)
{
auto actual = dest;
actual.blend (source, mode, extraAlpha);
PixelDouble sourcePixel (source);
PixelDouble expected (dest);
expected.blend (sourcePixel, mode, extraAlpha);
if (! expected.verifyChannelError (actual, errors, 2))
{
expect (false,
"Rounding error in excess of 2 encountered in " + toString (mode)
+ " mode. extraAlpha: "
+ String (extraAlpha) + ", "
+ createErrorMessage (dest, source, expected, actual));
return false;
}
return true;
});
}
if (mode == BlendMode::sourceOver)
{
const std::array<int64, 4> expectedErrors { 1607478, 3986467, 3986467, 3986467 };
expect (errors == expectedErrors,
"Rounding errors unexpectedly changed compared to JUCE 8.0.12. Expected: "
+ toString (expectedErrors) + " actual: " + toString (errors));
}
}
}
beginTest ("PixelRGBA blending, all modes: Rounding errors should never exceed 1 in any channel");
{
for (auto mode : { BlendMode::sourceOver, BlendMode::source, BlendMode::destinationIn, BlendMode::destinationOut })
{
std::array<int64, 4> errors{};
iterateOverValidPremult ([this, mode, &errors] (PixelARGB source, PixelARGB dest)
{
auto actual = dest;
actual.blend (source, mode);
PixelDouble sourcePixel (source);
PixelDouble expected (dest);
expected.blend (sourcePixel, mode);
if (! expected.verifyChannelError (actual, errors))
{
expect (false,
"Rounding error in excess of 1 encountered in " + toString (mode)
+ " mode. "
+ createErrorMessage (dest, source, expected, actual));
return false;
}
return true;
});
if (mode == BlendMode::sourceOver)
{
const auto expectedErrors = std::array<int64, 4> { 0, 0, 0, 0 };
expect (errors == expectedErrors,
"Rounding errors unexpectedly changed compared to JUCE 8.0.12. Expected: "
+ toString (expectedErrors) + " actual: " + toString (errors));
}
else if (mode == BlendMode::source)
{
const auto expectedErrors = std::array<int64, 4>{};
expect (errors == expectedErrors,
"There should be 0 rounding error in source mode");
}
else if (mode == BlendMode::destinationIn)
{
const auto expectedErrors = std::array<int64, 4> { 0, 0, 0, 0 };
expect (errors == expectedErrors,
"Rounding errors in destinationIn mode unexpectedly changed compared to earlier version. Expected: "
+ toString (expectedErrors) + " actual: " + toString (errors));
}
else if (mode == BlendMode::destinationOut)
{
const auto expectedErrors = std::array<int64, 4> { 0, 0, 0, 0 };
expect (errors == expectedErrors,
"Rounding errors in destinationOut mode unexpectedly changed compared to earlier version. Expected: "
+ toString (expectedErrors) + " actual: " + toString (errors));
}
}
}
beginTest ("Blending: opaque destination");
{
auto dest = makePixelARGB (255, 0, 91, 0);
dest.blend (makePixelARGB (50, 0, 0, 0), BlendMode::sourceOver);
expect (equals (dest, makePixelARGB (255, 0, 73, 0)),
"Blending into a fully opaque pixel in sourceOver mode should result in a fully opaque pixel.");
}
beginTest ("Blending: opaque black over white");
{
auto dest = makePixelARGB (255, 255, 255, 255);
dest.blend (makePixelARGB (255, 0, 0, 0), BlendMode::sourceOver);
expect (equals (dest, makePixelARGB (255, 0, 0, 0)),
"Blending opaque black over opaque white should be opaque black");
}
beginTest ("Blending: transparent black over white");
{
auto dest = makePixelARGB (255, 255, 255, 255);
dest.blend (makePixelARGB (0, 0, 0, 0), BlendMode::sourceOver);
expect (equals (dest, makePixelARGB (255, 255, 255, 255)),
"Blending transparent black over white should be white");
}
}
};
static PixelFormatsUnitTests pixelFormatsUnitTests;
#endif
} // namespace juce
@@ -0,0 +1,946 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
#if JUCE_MSVC
#pragma pack (push, 1)
#endif
class PixelRGB;
class PixelAlpha;
forcedinline constexpr uint32 maskPixelComponents (uint32 x) noexcept
{
return (x >> 8) & 0x00ff00ff;
}
forcedinline constexpr uint32 clampPixelComponents (uint32 x) noexcept
{
return (x | (0x01000100 - maskPixelComponents (x))) & 0x00ff00ff;
}
//==============================================================================
/** Identifiers for specifying the blending mode.
In the descriptions below R denotes the resulting colour, S is the source colour,
D is the destination colour, Sa and Da are the alpha components of S and D.
@see Graphics::setImageBlendMode
*/
enum class BlendMode
{
sourceOver, ///< R = S + D * (1 - Sa)
source, ///< R = S
destinationIn, ///< R = D * Sa
destinationOut ///< R = D * (1 - Sa)
};
//==============================================================================
/**
Represents a 32-bit INTERNAL pixel with premultiplied alpha, and can perform compositing
operations with it.
This is used internally by the imaging classes.
@see PixelRGB
@tags{Graphics}
*/
class JUCE_API PixelARGB
{
public:
/** Creates a pixel without defining its colour. */
PixelARGB() noexcept = default;
/** Creates a pixel. */
forcedinline constexpr PixelARGB (uint8 a, uint8 r, uint8 g, uint8 b) noexcept
: internal ( shiftedComponent (indexA, a)
| shiftedComponent (indexR, r)
| shiftedComponent (indexG, g)
| shiftedComponent (indexB, b))
{
}
//==============================================================================
/** Returns a uint32 which represents the pixel in a platform dependent format. */
forcedinline constexpr uint32 getNativeARGB() const noexcept { return internal; }
/** Returns a uint32 which will be in argb order as if constructed with the following mask operation
((alpha << 24) | (red << 16) | (green << 8) | blue). */
forcedinline constexpr uint32 getInARGBMaskOrder() const noexcept
{
#if JUCE_ANDROID
return (uint32) ((getAlpha() << 24) | (getRed() << 16) | (getGreen() << 8) | (getBlue() << 0));
#else
return getNativeARGB();
#endif
}
/** Returns a uint32 which when written to memory, will be in the order a, r, g, b. In other words,
if the return-value is read as a uint8 array then the elements will be in the order of a, r, g, b*/
forcedinline constexpr uint32 getInARGBMemoryOrder() const noexcept
{
#if JUCE_BIG_ENDIAN
return getInARGBMaskOrder();
#else
return (uint32) ((getBlue() << 24) | (getGreen() << 16) | (getRed() << 8) | getAlpha());
#endif
}
/** Return channels with an even index and insert zero bytes between them. This is useful for blending
operations. The exact channels which are returned is platform dependent. */
forcedinline constexpr uint32 getEvenBytes() const noexcept { return getEvenBytes (internal); }
/** Return channels with an odd index and insert zero bytes between them. This is useful for blending
operations. The exact channels which are returned is platform dependent. */
forcedinline constexpr uint32 getOddBytes() const noexcept { return getEvenBytes (internal >> 8); }
//==============================================================================
forcedinline constexpr uint8 getAlpha() const noexcept { return getComponent (indexA); }
forcedinline constexpr uint8 getRed() const noexcept { return getComponent (indexR); }
forcedinline constexpr uint8 getGreen() const noexcept { return getComponent (indexG); }
forcedinline constexpr uint8 getBlue() const noexcept { return getComponent (indexB); }
//==============================================================================
/** Copies another pixel colour over this one.
This doesn't blend it - this colour is simply replaced by the other one.
*/
template <class Pixel>
forcedinline constexpr void set (Pixel src) noexcept
{
internal = src.getNativeARGB();
}
//==============================================================================
/** Sets the pixel's colour from individual components. */
forcedinline constexpr void setARGB (uint8 a, uint8 r, uint8 g, uint8 b) noexcept
{
*this = PixelARGB { a, r, g, b };
}
//==============================================================================
/** Blends another pixel onto this one using the specified blend mode.
This takes into account the opacity of the pixel being overlaid, and blends
it accordingly.
*/
template <class Pixel>
forcedinline constexpr void blend (Pixel src, BlendMode mode) noexcept
{
blend (src, mode, 256);
}
/** Blends another pixel onto this one.
This takes into account the opacity of the pixel being overlaid, and blends
it accordingly.
*/
template <class Pixel>
forcedinline constexpr void blend (Pixel src) noexcept
{
blend (src, BlendMode::sourceOver);
}
/** Blends another pixel onto this one.
This takes into account the opacity of the pixel being overlaid, and blends
it accordingly.
*/
forcedinline constexpr void blend (PixelRGB src) noexcept;
/** Blends another pixel onto this one, applying an extra multiplier to its opacity.
The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
being used, so this can blend semi-transparently from a PixelRGB argument.
Scaling with extraAlpha is done using lossy, fixed-point arithmetic, where full opacity
is represented by 256.
*/
template <class Pixel>
forcedinline constexpr void blend (Pixel src, BlendMode mode, uint32 extraAlpha) noexcept
{
auto srcRB = src.getEvenBytes();
auto srcAG = src.getOddBytes();
if (extraAlpha != 256u)
{
srcRB = maskPixelComponents (extraAlpha * srcRB);
srcAG = maskPixelComponents (extraAlpha * srcAG);
}
const auto srcAlpha = srcAG >> 16;
switch (mode)
{
case BlendMode::sourceOver:
{
const uint32 invAlpha = 255u - srcAlpha;
const auto destRB = getEvenBytes() * invAlpha;
const auto destAG = getOddBytes() * invAlpha;
const auto corrRB = (destRB >> 8) & 0x00ff00ffu;
const auto corrAG = (destAG >> 8) & 0x00ff00ffu;
const auto newDestRB = srcRB + ((destRB + corrRB + 0x00800080u) >> 8);
const auto newDestAG = srcAG + ((destAG + corrAG + 0x00800080u) >> 8);
const auto rb = getEvenBytes (newDestRB);
const auto ag = getEvenBytes (newDestAG);
internal = (ag << 8) | rb;
return;
}
case BlendMode::source:
{
internal = (srcAG << 8) | srcRB;
return;
}
case BlendMode::destinationIn:
{
const auto destRB = getEvenBytes() * srcAlpha;
const auto destAG = getOddBytes() * srcAlpha;
const auto corrRB = (destRB >> 8) & 0x00ff00ffu;
const auto corrAG = (destAG >> 8) & 0x00ff00ffu;
const auto newDestRB = (destRB + corrRB + 0x00800080u) >> 8;
const auto newDestAG = (destAG + corrAG + 0x00800080u) >> 8;
const auto rb = getEvenBytes (newDestRB);
const auto ag = getEvenBytes (newDestAG);
internal = (ag << 8) | rb;
return;
}
case BlendMode::destinationOut:
{
const uint32 invAlpha = 255u - srcAlpha;
const auto destRB = getEvenBytes() * invAlpha;
const auto destAG = getOddBytes() * invAlpha;
const auto corrRB = (destRB >> 8) & 0x00ff00ffu;
const auto corrAG = (destAG >> 8) & 0x00ff00ffu;
const auto newDestRB = (destRB + corrRB + 0x00800080u) >> 8;
const auto newDestAG = (destAG + corrAG + 0x00800080u) >> 8;
const auto rb = getEvenBytes (newDestRB);
const auto ag = getEvenBytes (newDestAG);
internal = (ag << 8) | rb;
return;
}
}
}
template <class Pixel>
forcedinline constexpr void blend (Pixel src, uint32 extraAlpha) noexcept
{
blend (src, BlendMode::sourceOver, extraAlpha);
}
/** Blends another pixel with this one, creating a colour that is somewhere
between the two, as specified by the amount.
*/
template <class Pixel>
forcedinline constexpr void tween (Pixel src, uint32 amount) noexcept
{
auto dEvenBytes = getEvenBytes();
dEvenBytes += (((src.getEvenBytes() - dEvenBytes) * amount) >> 8);
dEvenBytes &= 0x00ff00ff;
auto dOddBytes = getOddBytes();
dOddBytes += (((src.getOddBytes() - dOddBytes) * amount) >> 8);
dOddBytes &= 0x00ff00ff;
dOddBytes <<= 8;
dOddBytes |= dEvenBytes;
internal = dOddBytes;
}
//==============================================================================
/** Replaces the colour's alpha value with another one. */
forcedinline constexpr void setAlpha (uint8 newAlpha) noexcept
{
setComponent (indexA, newAlpha);
}
/** Multiplies the colour's alpha value with another one. */
forcedinline constexpr void multiplyAlpha (int multiplier) noexcept
{
// increment alpha by 1, so that if multiplier == 255 (full alpha),
// this function will not change the values.
++multiplier;
internal = ((((uint32) multiplier) * getOddBytes()) & 0xff00ff00)
| (((((uint32) multiplier) * getEvenBytes()) >> 8) & 0x00ff00ff);
}
forcedinline constexpr void multiplyAlpha (float multiplier) noexcept
{
multiplyAlpha ((int) (multiplier * 255.0f));
}
forcedinline constexpr PixelARGB getUnpremultiplied() const noexcept
{
PixelARGB p { *this };
p.unpremultiply();
return p;
}
/** Premultiplies the pixel's RGB values by its alpha. */
forcedinline constexpr void premultiply() noexcept
{
const auto alpha = getAlpha();
if (alpha == 0xff)
return;
if (alpha == 0)
{
setComponent (indexB, 0);
setComponent (indexG, 0);
setComponent (indexR, 0);
}
else
{
setComponent (indexB, (uint8) ((getBlue() * alpha + 0x7f) >> 8));
setComponent (indexG, (uint8) ((getGreen() * alpha + 0x7f) >> 8));
setComponent (indexR, (uint8) ((getRed() * alpha + 0x7f) >> 8));
}
}
/** Unpremultiplies the pixel's RGB values. */
forcedinline constexpr void unpremultiply() noexcept
{
const auto alpha = getAlpha();
if (alpha == 0xff)
return;
if (alpha == 0)
{
setComponent (indexB, 0);
setComponent (indexG, 0);
setComponent (indexR, 0);
}
else
{
setComponent (indexB, (uint8) jmin ((uint32) 0xffu, (getBlue() * 0xffu) / alpha));
setComponent (indexG, (uint8) jmin ((uint32) 0xffu, (getGreen() * 0xffu) / alpha));
setComponent (indexR, (uint8) jmin ((uint32) 0xffu, (getRed() * 0xffu) / alpha));
}
}
forcedinline constexpr void desaturate() noexcept
{
const auto alpha = getAlpha();
const auto red = getRed();
const auto green = getGreen();
const auto blue = getBlue();
if (0 < alpha && alpha < 0xff)
{
const auto newUnpremultipliedLevel = (0xff * ((int) red + (int) green + (int) blue) / (3 * alpha));
const auto newValue = (uint8) ((newUnpremultipliedLevel * alpha + 0x7f) >> 8);
setComponent (indexB, newValue);
setComponent (indexG, newValue);
setComponent (indexR, newValue);
}
else
{
const auto newValue = (uint8) (((int) red + (int) green + (int) blue) / 3);
setComponent (indexB, newValue);
setComponent (indexG, newValue);
setComponent (indexR, newValue);
}
}
//==============================================================================
/** The indexes of the different components in the byte layout of this type of colour. */
#if JUCE_ANDROID
#if JUCE_BIG_ENDIAN
enum { indexA = 0, indexR = 3, indexG = 2, indexB = 1 };
#else
enum { indexA = 3, indexR = 0, indexG = 1, indexB = 2 };
#endif
#else
#if JUCE_BIG_ENDIAN
enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
#else
enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
#endif
#endif
private:
//==============================================================================
static forcedinline constexpr int shift (int index) noexcept
{
#if JUCE_BIG_ENDIAN
return (3 - index) * 8;
#else
return index * 8;
#endif
}
forcedinline constexpr uint8 getComponent (int index) const noexcept
{
return static_cast<uint8> (internal >> shift (index));
}
static forcedinline constexpr uint32 shiftedComponent (int index, uint8 value) noexcept
{
return static_cast<uint32> (value << shift (index));
}
forcedinline constexpr void setComponent (int index, uint8 value) noexcept
{
const auto mask = ~ shiftedComponent (index, 0xff);
internal = (internal & mask) | shiftedComponent (index, value);
}
static forcedinline constexpr uint32 getEvenBytes (uint32 input) noexcept
{
return input & 0x00ff00ff;
}
uint32 internal;
}
/** @cond */
JUCE_PACKED
/** @endcond */
;
//==============================================================================
/**
Represents a 24-bit RGB pixel, and can perform compositing operations on it.
This is used internally by the imaging classes.
@see PixelARGB
@tags{Graphics}
*/
class JUCE_API PixelRGB
{
public:
/** Creates a pixel without defining its colour. */
PixelRGB() noexcept = default;
/** Creates a pixel. */
forcedinline constexpr PixelRGB (uint8 red, uint8 green, uint8 blue) noexcept
:
#if JUCE_MAC || JUCE_IOS
r (red), g (green), b (blue)
#else
b (blue), g (green), r (red)
#endif
{
}
//==============================================================================
/** Returns a uint32 which represents the pixel in a platform dependent format which is compatible
with the native format of a PixelARGB.
@see PixelARGB::getNativeARGB */
forcedinline constexpr uint32 getNativeARGB() const noexcept
{
return PixelARGB { 0xffu, r, g, b }.getNativeARGB();
}
/** Returns a uint32 which will be in argb order as if constructed with the following mask operation
((alpha << 24) | (red << 16) | (green << 8) | blue). */
forcedinline constexpr uint32 getInARGBMaskOrder() const noexcept
{
return PixelARGB { 0xffu, r, g, b }.getInARGBMaskOrder();
}
/** Returns a uint32 which when written to memory, will be in the order a, r, g, b. In other words,
if the return-value is read as a uint8 array then the elements will be in the order of a, r, g, b*/
forcedinline constexpr uint32 getInARGBMemoryOrder() const noexcept
{
return PixelARGB { 0xffu, r, g, b }.getInARGBMemoryOrder();
}
/** Return channels with an even index and insert zero bytes between them. This is useful for blending
operations. The exact channels which are returned is platform dependent but compatible with the
return value of getEvenBytes of the PixelARGB class.
@see PixelARGB::getEvenBytes */
forcedinline constexpr uint32 getEvenBytes() const noexcept
{
#if JUCE_ANDROID
return (uint32) (r | (b << 16));
#else
return (uint32) (b | (r << 16));
#endif
}
/** Return channels with an odd index and insert zero bytes between them. This is useful for blending
operations. The exact channels which are returned is platform dependent but compatible with the
return value of getOddBytes of the PixelARGB class.
@see PixelARGB::getOddBytes */
forcedinline constexpr uint32 getOddBytes() const noexcept { return (uint32) 0xff0000 | g; }
//==============================================================================
forcedinline constexpr uint8 getAlpha() const noexcept { return 0xff; }
forcedinline constexpr uint8 getRed() const noexcept { return r; }
forcedinline constexpr uint8 getGreen() const noexcept { return g; }
forcedinline constexpr uint8 getBlue() const noexcept { return b; }
//==============================================================================
/** Copies another pixel colour over this one.
This doesn't blend it - this colour is simply replaced by the other one.
Because PixelRGB has no alpha channel, any alpha value in the source pixel
is thrown away.
*/
template <class Pixel>
forcedinline constexpr void set (Pixel src) noexcept
{
*this = PixelRGB { src.getRed(), src.getGreen(), src.getBlue() };
}
/** Sets the pixel's colour from individual components. */
forcedinline constexpr void setARGB (uint8, uint8 red, uint8 green, uint8 blue) noexcept
{
*this = PixelRGB { red, green, blue };
}
//==============================================================================
/** Blends another pixel onto this one.
This takes into account the opacity of the pixel being overlaid, and blends
it accordingly.
*/
template <class Pixel>
forcedinline constexpr void blend (Pixel src) noexcept
{
const auto alpha = (uint32) (0x100 - src.getAlpha());
// getEvenBytes returns 0x00rr00bb on non-android
const auto rb = clampPixelComponents (src.getEvenBytes() + maskPixelComponents (getEvenBytes() * alpha));
// getOddBytes returns 0x00aa00gg on non-android
const auto ag = clampPixelComponents (src.getOddBytes() + ((g * alpha) >> 8));
g = (uint8) (ag & 0xff);
#if JUCE_ANDROID
b = (uint8) (rb >> 16);
r = (uint8) (rb & 0xff);
#else
r = (uint8) (rb >> 16);
b = (uint8) (rb & 0xff);
#endif
}
forcedinline constexpr void blend (PixelRGB src) noexcept
{
set (src);
}
/** Blends another pixel onto this one, applying an extra multiplier to its opacity.
The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
being used, so this can blend semi-transparently from a PixelRGB argument.
*/
template <class Pixel>
forcedinline constexpr void blend (Pixel src, uint32 extraAlpha) noexcept
{
auto ag = maskPixelComponents (extraAlpha * src.getOddBytes());
auto rb = maskPixelComponents (extraAlpha * src.getEvenBytes());
const auto alpha = 0x100 - (ag >> 16);
ag = clampPixelComponents (ag + (g * alpha >> 8));
rb = clampPixelComponents (rb + maskPixelComponents (getEvenBytes() * alpha));
g = (uint8) (ag & 0xff);
#if JUCE_ANDROID
b = (uint8) (rb >> 16);
r = (uint8) (rb & 0xff);
#else
r = (uint8) (rb >> 16);
b = (uint8) (rb & 0xff);
#endif
}
/** Blends another pixel onto this one with the specified blend mode and applying an
extra multiplier to its opacity.
The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
being used, so this can blend semi-transparently from a PixelRGB argument.
Scaling with extraAlpha is done using lossy, fixed-point arithmetic, where full opacity
is represented by 256.
*/
template <class Pixel>
forcedinline void blend (const Pixel& src, BlendMode mode, uint32 extraAlpha = 256u) noexcept
{
auto Srb = src.getEvenBytes();
auto Sag = src.getOddBytes();
if (extraAlpha != 256u)
{
Srb = maskPixelComponents (extraAlpha * Srb);
Sag = maskPixelComponents (extraAlpha * Sag);
}
uint32 rb{}, ag{};
switch (mode)
{
case BlendMode::sourceOver:
{
const auto oneMinusSa = 0x100 - (Sag >> 16);
rb = clampPixelComponents (Srb + maskPixelComponents (getEvenBytes() * oneMinusSa));
ag = clampPixelComponents (Sag + maskPixelComponents (getOddBytes() * oneMinusSa));
break;
}
case BlendMode::source:
{
rb = Srb;
ag = Sag;
break;
}
case BlendMode::destinationIn:
{
const auto Sa = (Sag >> 16) + 1;
rb = maskPixelComponents (getEvenBytes() * Sa);
ag = maskPixelComponents (getOddBytes() * Sa);
break;
}
case BlendMode::destinationOut:
{
const auto oneMinusSa = 0x100 - (Sag >> 16);
rb = maskPixelComponents (getEvenBytes() * oneMinusSa);
ag = maskPixelComponents (getOddBytes() * oneMinusSa);
break;
}
}
g = (uint8) (ag & 0xff);
#if JUCE_ANDROID
b = (uint8) (rb >> 16);
r = (uint8) (rb & 0xff);
#else
r = (uint8) (rb >> 16);
b = (uint8) (rb & 0xff);
#endif
}
/** Blends another pixel with this one, creating a colour that is somewhere
between the two, as specified by the amount.
*/
template <class Pixel>
forcedinline constexpr void tween (Pixel src, uint32 amount) noexcept
{
auto dEvenBytes = getEvenBytes();
dEvenBytes += (((src.getEvenBytes() - dEvenBytes) * amount) >> 8);
auto dOddBytes = getOddBytes();
dOddBytes += (((src.getOddBytes() - dOddBytes) * amount) >> 8);
g = (uint8) (dOddBytes & 0xff); // dOddBytes = 0x00aa00gg
#if JUCE_ANDROID
r = (uint8) (dEvenBytes & 0xff); // dEvenBytes = 0x00bb00rr
b = (uint8) (dEvenBytes >> 16);
#else
b = (uint8) (dEvenBytes & 0xff); // dEvenBytes = 0x00rr00bb
r = (uint8) (dEvenBytes >> 16);
#endif
}
//==============================================================================
/** This method is included for compatibility with the PixelARGB class. */
forcedinline constexpr void setAlpha (uint8) noexcept {}
/** Multiplies the colour's alpha value with another one. */
forcedinline constexpr void multiplyAlpha (int) noexcept {}
/** Multiplies the colour's alpha value with another one. */
forcedinline constexpr void multiplyAlpha (float) noexcept {}
/** Premultiplies the pixel's RGB values by its alpha. */
forcedinline constexpr void premultiply() noexcept {}
/** Unpremultiplies the pixel's RGB values. */
forcedinline constexpr void unpremultiply() noexcept {}
forcedinline constexpr void desaturate() noexcept
{
r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
}
//==============================================================================
/** The indexes of the different components in the byte layout of this type of colour. */
#if JUCE_MAC || JUCE_IOS
enum { indexR = 0, indexG = 1, indexB = 2 };
#else
enum { indexR = 2, indexG = 1, indexB = 0 };
#endif
private:
//==============================================================================
#if JUCE_MAC || JUCE_IOS
uint8 r, g, b;
#else
uint8 b, g, r;
#endif
}
/** @cond */
JUCE_PACKED
/** @endcond */
;
forcedinline constexpr void PixelARGB::blend (PixelRGB src) noexcept
{
set (src);
}
//==============================================================================
/**
Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
This is used internally by the imaging classes.
@see PixelARGB, PixelRGB
@tags{Graphics}
*/
class JUCE_API PixelAlpha
{
public:
/** Creates a pixel without defining its colour. */
PixelAlpha() noexcept = default;
/** Creates a pixel. */
forcedinline constexpr PixelAlpha (uint8 alpha) noexcept
: a (alpha)
{
}
//==============================================================================
/** Returns a uint32 which represents the pixel in a platform dependent format which is compatible
with the native format of a PixelARGB.
@see PixelARGB::getNativeARGB */
forcedinline constexpr uint32 getNativeARGB() const noexcept { return (uint32) ((a << 24) | (a << 16) | (a << 8) | a); }
/** Returns a uint32 which will be in argb order as if constructed with the following mask operation
((alpha << 24) | (red << 16) | (green << 8) | blue). */
forcedinline constexpr uint32 getInARGBMaskOrder() const noexcept { return getNativeARGB(); }
/** Returns a uint32 which when written to memory, will be in the order a, r, g, b. In other words,
if the return-value is read as a uint8 array then the elements will be in the order of a, r, g, b*/
forcedinline uint32 constexpr getInARGBMemoryOrder() const noexcept { return getNativeARGB(); }
/** Return channels with an even index and insert zero bytes between them. This is useful for blending
operations. The exact channels which are returned is platform dependent but compatible with the
return value of getEvenBytes of the PixelARGB class.
@see PixelARGB::getEvenBytes */
forcedinline constexpr uint32 getEvenBytes() const noexcept { return (uint32) ((a << 16) | a); }
/** Return channels with an odd index and insert zero bytes between them. This is useful for blending
operations. The exact channels which are returned is platform dependent but compatible with the
return value of getOddBytes of the PixelARGB class.
@see PixelARGB::getOddBytes */
forcedinline constexpr uint32 getOddBytes() const noexcept { return (uint32) ((a << 16) | a); }
//==============================================================================
forcedinline constexpr uint8 getAlpha() const noexcept { return a; }
forcedinline constexpr uint8 getRed() const noexcept { return 0; }
forcedinline constexpr uint8 getGreen() const noexcept { return 0; }
forcedinline constexpr uint8 getBlue() const noexcept { return 0; }
//==============================================================================
/** Copies another pixel colour over this one.
This doesn't blend it - this colour is simply replaced by the other one.
*/
template <class Pixel>
forcedinline constexpr void set (Pixel src) noexcept
{
a = src.getAlpha();
}
/** Sets the pixel's colour from individual components. */
forcedinline constexpr void setARGB (uint8 a_, uint8, uint8, uint8) noexcept
{
a = a_;
}
//==============================================================================
/** Blends another pixel onto this one.
This takes into account the opacity of the pixel being overlaid, and blends
it accordingly.
*/
template <class Pixel>
forcedinline constexpr void blend (Pixel src) noexcept
{
const auto srcA = src.getAlpha();
a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
}
/** Blends another pixel onto this one, applying an extra multiplier to its opacity.
The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
being used, so this can blend semi-transparently from a PixelRGB argument.
*/
template <class Pixel>
forcedinline constexpr void blend (Pixel src, uint32 extraAlpha) noexcept
{
++extraAlpha;
const auto srcAlpha = (int) ((extraAlpha * src.getAlpha()) >> 8);
a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
}
/** Blends another pixel onto this one using the specified blend mode and applying an
extra multiplier to its opacity.
The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
being used, so this can blend semi-transparently from a PixelRGB argument.
Unlike the similar function of the PixelARGB and PixelRGB classes, full opacity
is represented by extraAlpha = 255.
*/
template <class Pixel>
forcedinline void blend (const Pixel& src, BlendMode mode, uint32 extraAlpha = 255u) noexcept
{
auto Sa = (uint32) src.getAlpha();
if (extraAlpha != 255u)
{
++extraAlpha;
Sa = (extraAlpha * Sa) >> 8;
}
auto& Da = a;
switch (mode)
{
case BlendMode::sourceOver:
{
const auto oneMinusSa = 0x100 - Sa;
Da = (uint8) (Sa + ((Da * oneMinusSa) >> 8));
return;
}
case BlendMode::source:
{
Da = (uint8) Sa;
return;
}
case BlendMode::destinationIn:
{
Da = (uint8) ((Da * (Sa + 1)) >> 8);
return;
}
case BlendMode::destinationOut:
{
const auto oneMinusSa = 0x100 - Sa;
Da = (uint8) ((Da * oneMinusSa) >> 8);
return;
}
}
jassertfalse;
}
/** Blends another pixel with this one, creating a colour that is somewhere
between the two, as specified by the amount.
*/
template <class Pixel>
forcedinline constexpr void tween (Pixel src, uint32 amount) noexcept
{
a += (uint8) (((uint32) (src.getAlpha() - a) * amount) >> 8);
}
//==============================================================================
/** Replaces the colour's alpha value with another one. */
forcedinline constexpr void setAlpha (uint8 newAlpha) noexcept
{
a = newAlpha;
}
/** Multiplies the colour's alpha value with another one. */
forcedinline constexpr void multiplyAlpha (int multiplier) noexcept
{
++multiplier;
a = (uint8) ((a * multiplier) >> 8);
}
forcedinline constexpr void multiplyAlpha (float multiplier) noexcept
{
a = (uint8) (a * multiplier);
}
/** Premultiplies the pixel's RGB values by its alpha. */
forcedinline constexpr void premultiply() noexcept {}
/** Unpremultiplies the pixel's RGB values. */
forcedinline constexpr void unpremultiply() noexcept {}
forcedinline constexpr void desaturate() noexcept {}
//==============================================================================
/** The indexes of the different components in the byte layout of this type of colour. */
enum { indexA = 0 };
private:
//==============================================================================
uint8 a;
}
/** @cond */
JUCE_PACKED
/** @endcond */
;
#if JUCE_MSVC
#pragma pack (pop)
#endif
} // namespace juce
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,763 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
A graphics context, used for drawing a component or image.
When a Component needs painting, a Graphics context is passed to its
Component::paint() method, and this you then call methods within this
object to actually draw the component's content.
A Graphics can also be created from an image, to allow drawing directly onto
that image.
@see Component::paint
@tags{Graphics}
*/
class JUCE_API Graphics final
{
public:
//==============================================================================
/** Creates a Graphics object to draw directly onto the given image.
The graphics object that is created will be set up to draw onto the image,
with the context's clipping area being the entire size of the image, and its
origin being the image's origin. To draw into a subsection of an image, use the
reduceClipRegion() and setOrigin() methods.
Obviously you shouldn't delete the image before this context is deleted.
*/
explicit Graphics (const Image& imageToDrawOnto);
//==============================================================================
/** Changes the current drawing colour.
This sets the colour that will now be used for drawing operations - it also
sets the opacity to that of the colour passed-in.
If a brush is being used when this method is called, the brush will be deselected,
and any subsequent drawing will be done with a solid colour brush instead.
@see setOpacity
*/
void setColour (Colour newColour);
/** Changes the opacity to use with the current colour.
If a solid colour is being used for drawing, this changes its opacity
to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
If a gradient is being used, this will have no effect on it.
A value of 0.0 is completely transparent, 1.0 is completely opaque.
*/
void setOpacity (float newOpacity);
/** Changes the blend mode used for drawing images. */
void setImageBlendMode (BlendMode newMode);
/** Sets the context to use a gradient for its fill pattern. */
void setGradientFill (const ColourGradient& gradient);
/** Sets the context to use a gradient for its fill pattern. */
void setGradientFill (ColourGradient&& gradient);
/** Sets the context to use a tiled image pattern for filling.
Make sure that you don't delete this image while it's still being used by
this context!
*/
void setTiledImageFill (const Image& imageToUse,
int anchorX, int anchorY,
float opacity);
/** Changes the current fill settings.
@see setColour, setGradientFill, setTiledImageFill
*/
void setFillType (const FillType& newFill);
//==============================================================================
/** Changes the font to use for subsequent text-drawing functions.
@see drawSingleLineText, drawMultiLineText, drawText, drawFittedText
*/
void setFont (const Font& newFont);
/** Changes the size of the currently-selected font.
This is a convenient shortcut that changes the context's current font to a
different size. The typeface won't be changed.
@see Font
*/
void setFont (float newFontHeight);
/** Returns the currently selected font. */
Font getCurrentFont() const;
/** Draws a one-line text string.
This will use the current colour (or brush) to fill the text. The font is the last
one specified by setFont().
@param text the string to draw
@param startX the position to draw the left-hand edge of the text
@param baselineY the position of the text's baseline
@param justification the horizontal flags indicate which end of the text string is
anchored at the specified point.
@see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
*/
void drawSingleLineText (const String& text,
int startX, int baselineY,
Justification justification = Justification::left) const;
/** Draws text across multiple lines.
This will break the text onto a new line where there's a new-line or
carriage-return character, or at a word-boundary when the text becomes wider
than the size specified by the maximumLineWidth parameter. New-lines
will be vertically separated by the specified leading.
@see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
*/
void drawMultiLineText (const String& text,
int startX, int baselineY,
int maximumLineWidth,
Justification justification = Justification::left,
float leading = 0.0f) const;
/** Draws a line of text within a specified rectangle.
The text will be positioned within the rectangle based on the justification
flags passed-in. If the string is too long to fit inside the rectangle, it will
either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
flag is true).
@see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
*/
void drawText (const String& text,
int x, int y, int width, int height,
Justification justificationType,
bool useEllipsesIfTooBig = true) const;
/** Draws a line of text within a specified rectangle.
The text will be positioned within the rectangle based on the justification
flags passed-in. If the string is too long to fit inside the rectangle, it will
either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
flag is true).
@see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
*/
void drawText (const String& text,
Rectangle<int> area,
Justification justificationType,
bool useEllipsesIfTooBig = true) const;
/** Draws a line of text within a specified rectangle.
The text will be positioned within the rectangle based on the justification
flags passed-in. If the string is too long to fit inside the rectangle, it will
either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
flag is true).
@see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
*/
void drawText (const String& text,
Rectangle<float> area,
Justification justificationType,
bool useEllipsesIfTooBig = true) const;
/** Tries to draw a text string inside a given space.
This does its best to make the given text readable within the specified rectangle,
so it's useful for labelling things.
If the text is too big, it'll be squashed horizontally or broken over multiple lines
if the maximumLinesToUse value allows this. If the text just won't fit into the space,
it'll cram as much as possible in there, and put some ellipsis at the end to show that
it's been truncated.
A Justification parameter lets you specify how the text is laid out within the rectangle,
both horizontally and vertically.
The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
can set this value to 1.0f. Pass 0 if you want it to use a default value.
@see GlyphArrangement::addFittedText
*/
void drawFittedText (const String& text,
int x, int y, int width, int height,
Justification justificationFlags,
int maximumNumberOfLines,
float minimumHorizontalScale = 0.0f,
GlyphArrangementOptions options = {}) const;
/** Tries to draw a text string inside a given space.
This does its best to make the given text readable within the specified rectangle,
so it's useful for labelling things.
If the text is too big, it'll be squashed horizontally or broken over multiple lines
if the maximumLinesToUse value allows this. If the text just won't fit into the space,
it'll cram as much as possible in there, and put some ellipsis at the end to show that
it's been truncated.
A Justification parameter lets you specify how the text is laid out within the rectangle,
both horizontally and vertically.
The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
can set this value to 1.0f. Pass 0 if you want it to use a default value.
@see GlyphArrangement::addFittedText
*/
void drawFittedText (const String& text,
Rectangle<int> area,
Justification justificationFlags,
int maximumNumberOfLines,
float minimumHorizontalScale = 0.0f,
GlyphArrangementOptions options = {}) const;
//==============================================================================
/** Fills the context's entire clip region with the current colour or brush.
(See also the fillAll (Colour) method which is a quick way of filling
it with a given colour).
*/
void fillAll() const;
/** Fills the context's entire clip region with a given colour.
This leaves the context's current colour and brush unchanged, it just
uses the specified colour temporarily.
*/
void fillAll (Colour colourToUse) const;
//==============================================================================
/** Fills a rectangle with the current colour or brush.
@see drawRect, fillRoundedRectangle
*/
void fillRect (Rectangle<int> rectangle) const;
/** Fills a rectangle with the current colour or brush.
@see drawRect, fillRoundedRectangle
*/
void fillRect (Rectangle<float> rectangle) const;
/** Fills a rectangle with the current colour or brush.
@see drawRect, fillRoundedRectangle
*/
void fillRect (int x, int y, int width, int height) const;
/** Fills a rectangle with the current colour or brush.
@see drawRect, fillRoundedRectangle
*/
void fillRect (float x, float y, float width, float height) const;
/** Fills a set of rectangles using the current colour or brush.
If you have a lot of rectangles to draw, it may be more efficient
to create a RectangleList and use this method than to call fillRect()
multiple times.
*/
void fillRectList (const RectangleList<float>& rectangles) const;
/** Fills a set of rectangles using the current colour or brush.
If you have a lot of rectangles to draw, it may be more efficient
to create a RectangleList and use this method than to call fillRect()
multiple times.
*/
void fillRectList (const RectangleList<int>& rectangles) const;
/** Uses the current colour or brush to fill a rectangle with rounded corners.
@see drawRoundedRectangle, Path::addRoundedRectangle
*/
void fillRoundedRectangle (float x, float y, float width, float height,
float cornerSize) const;
/** Uses the current colour or brush to fill a rectangle with rounded corners.
@see drawRoundedRectangle, Path::addRoundedRectangle
*/
void fillRoundedRectangle (Rectangle<float> rectangle,
float cornerSize) const;
/** Fills a rectangle with a checkerboard pattern, alternating between two colours. */
void fillCheckerBoard (Rectangle<float> area,
float checkWidth, float checkHeight,
Colour colour1, Colour colour2) const;
/** Draws a rectangular outline, using the current colour or brush.
The lines are drawn inside the given rectangle, and greater line thicknesses extend inwards.
@see fillRect
*/
void drawRect (int x, int y, int width, int height, int lineThickness = 1) const;
/** Draws a rectangular outline, using the current colour or brush.
The lines are drawn inside the given rectangle, and greater line thicknesses extend inwards.
@see fillRect
*/
void drawRect (float x, float y, float width, float height, float lineThickness = 1.0f) const;
/** Draws a rectangular outline, using the current colour or brush.
The lines are drawn inside the given rectangle, and greater line thicknesses extend inwards.
@see fillRect
*/
void drawRect (Rectangle<int> rectangle, int lineThickness = 1) const;
/** Draws a rectangular outline, using the current colour or brush.
The lines are drawn inside the given rectangle, and greater line thicknesses extend inwards.
@see fillRect
*/
void drawRect (Rectangle<float> rectangle, float lineThickness = 1.0f) const;
/** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
@see fillRoundedRectangle, Path::addRoundedRectangle
*/
void drawRoundedRectangle (float x, float y, float width, float height,
float cornerSize, float lineThickness) const;
/** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
@see fillRoundedRectangle, Path::addRoundedRectangle
*/
void drawRoundedRectangle (Rectangle<float> rectangle,
float cornerSize, float lineThickness) const;
//==============================================================================
/** Fills an ellipse with the current colour or brush.
The ellipse is drawn to fit inside the given rectangle.
@see drawEllipse, Path::addEllipse
*/
void fillEllipse (float x, float y, float width, float height) const;
/** Fills an ellipse with the current colour or brush.
The ellipse is drawn to fit inside the given rectangle.
@see drawEllipse, Path::addEllipse
*/
void fillEllipse (Rectangle<float> area) const;
/** Draws an elliptical stroke using the current colour or brush.
@see fillEllipse, Path::addEllipse
*/
void drawEllipse (float x, float y, float width, float height,
float lineThickness) const;
/** Draws an elliptical stroke using the current colour or brush.
@see fillEllipse, Path::addEllipse
*/
void drawEllipse (Rectangle<float> area, float lineThickness) const;
//==============================================================================
/** Draws a line between two points.
The line is 1 pixel wide and drawn with the current colour or brush.
TIP: If you're trying to draw horizontal or vertical lines, don't use this -
it's better to use fillRect() instead unless you really need an angled line.
*/
void drawLine (float startX, float startY, float endX, float endY) const;
/** Draws a line between two points with a given thickness.
TIP: If you're trying to draw horizontal or vertical lines, don't use this -
it's better to use fillRect() instead unless you really need an angled line.
@see Path::addLineSegment
*/
void drawLine (float startX, float startY, float endX, float endY, float lineThickness) const;
/** Draws a line between two points.
The line is 1 pixel wide and drawn with the current colour or brush.
TIP: If you're trying to draw horizontal or vertical lines, don't use this -
it's better to use fillRect() instead unless you really need an angled line.
*/
void drawLine (Line<float> line) const;
/** Draws a line between two points with a given thickness.
@see Path::addLineSegment
TIP: If you're trying to draw horizontal or vertical lines, don't use this -
it's better to use fillRect() instead unless you really need an angled line.
*/
void drawLine (Line<float> line, float lineThickness) const;
/** Draws a dashed line using a custom set of dash-lengths.
@param line the line to draw
@param dashLengths a series of lengths to specify the on/off lengths - e.g.
{ 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
draw 6 pixels, skip 7 pixels, and then repeat.
@param numDashLengths the number of elements in the array (this must be an even number).
@param lineThickness the thickness of the line to draw
@param dashIndexToStartFrom the index in the dash-length array to use for the first segment
@see PathStrokeType::createDashedStroke
*/
void drawDashedLine (Line<float> line,
const float* dashLengths, int numDashLengths,
float lineThickness = 1.0f,
int dashIndexToStartFrom = 0) const;
/** Draws a vertical line of pixels at a given x position.
The x position is an integer, but the top and bottom of the line can be sub-pixel
positions, and these will be anti-aliased if necessary.
The bottom parameter must be greater than or equal to the top parameter.
*/
void drawVerticalLine (int x, float top, float bottom) const;
/** Draws a horizontal line of pixels at a given y position.
The y position is an integer, but the left and right ends of the line can be sub-pixel
positions, and these will be anti-aliased if necessary.
The right parameter must be greater than or equal to the left parameter.
*/
void drawHorizontalLine (int y, float left, float right) const;
//==============================================================================
/** Fills a path using the currently selected colour or brush. */
void fillPath (const Path& path) const;
/** Fills a path using the currently selected colour or brush, and adds a transform. */
void fillPath (const Path& path, const AffineTransform& transform) const;
/** Draws a path's outline using the currently selected colour or brush. */
void strokePath (const Path& path,
const PathStrokeType& strokeType,
const AffineTransform& transform = {}) const;
/** Draws a line with an arrowhead at its end.
@param line the line to draw
@param lineThickness the thickness of the line
@param arrowheadWidth the width of the arrow head (perpendicular to the line)
@param arrowheadLength the length of the arrow head (along the length of the line)
*/
void drawArrow (Line<float> line,
float lineThickness,
float arrowheadWidth,
float arrowheadLength) const;
//==============================================================================
/** Types of rendering quality that can be specified when drawing images.
@see Graphics::setImageResamplingQuality
*/
enum ResamplingQuality
{
lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
highResamplingQuality = 2, /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
};
/** Changes the quality that will be used when resampling images.
By default a Graphics object will be set to mediumRenderingQuality.
@see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
*/
void setImageResamplingQuality (ResamplingQuality newQuality);
/** Draws an image.
This will draw the whole of an image, positioning its top-left corner at the
given coordinates, and keeping its size the same. This is the simplest image
drawing method - the others give more control over the scaling and clipping
of the images.
Images are composited using the context's current opacity, so if you
don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
(or setColour() with an opaque colour) before drawing images.
*/
void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
bool fillAlphaChannelWithCurrentBrush = false) const;
/** Draws part of an image, rescaling it to fit in a given target region.
The specified area of the source image is rescaled and drawn to fill the
specified destination rectangle.
Images are composited using the context's current opacity, so if you
don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
(or setColour() with an opaque colour) before drawing images.
@param imageToDraw the image to overlay
@param destX the left of the destination rectangle
@param destY the top of the destination rectangle
@param destWidth the width of the destination rectangle
@param destHeight the height of the destination rectangle
@param sourceX the left of the rectangle to copy from the source image
@param sourceY the top of the rectangle to copy from the source image
@param sourceWidth the width of the rectangle to copy from the source image
@param sourceHeight the height of the rectangle to copy from the source image
@param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
the source image's alpha channel is used as a mask with
which to fill the destination using the current colour
or brush. (If the source is has no alpha channel, then
it will just fill the target with a solid rectangle)
@see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
*/
void drawImage (const Image& imageToDraw,
int destX, int destY, int destWidth, int destHeight,
int sourceX, int sourceY, int sourceWidth, int sourceHeight,
bool fillAlphaChannelWithCurrentBrush = false) const;
/** Draws an image, having applied an affine transform to it.
This lets you throw the image around in some wacky ways, rotate it, shear,
scale it, etc.
Images are composited using the context's current opacity, so if you
don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
(or setColour() with an opaque colour) before drawing images.
If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
are ignored and it is filled with the current brush, masked by its alpha channel.
If you want to render only a subsection of an image, use Image::getClippedImage() to
create the section that you need.
@see setImageResamplingQuality, drawImage
*/
void drawImageTransformed (const Image& imageToDraw,
const AffineTransform& transform,
bool fillAlphaChannelWithCurrentBrush = false) const;
/** Draws an image to fit within a designated rectangle.
@param imageToDraw the source image to draw
@param targetArea the target rectangle to fit it into
@param placementWithinTarget this specifies how the image should be positioned
within the target rectangle - see the RectanglePlacement
class for more details about this.
@param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
alpha channel will be used as a mask with which to
draw with the current brush or colour. This is
similar to fillAlphaMap(), and see also drawImage()
@see drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
*/
void drawImage (const Image& imageToDraw, Rectangle<float> targetArea,
RectanglePlacement placementWithinTarget = RectanglePlacement::stretchToFit,
bool fillAlphaChannelWithCurrentBrush = false) const;
/** Draws an image to fit within a designated rectangle.
If the image is too big or too small for the space, it will be rescaled
to fit as nicely as it can do without affecting its aspect ratio. It will
then be placed within the target rectangle according to the justification flags
specified.
@param imageToDraw the source image to draw
@param destX top-left of the target rectangle to fit it into
@param destY top-left of the target rectangle to fit it into
@param destWidth size of the target rectangle to fit the image into
@param destHeight size of the target rectangle to fit the image into
@param placementWithinTarget this specifies how the image should be positioned
within the target rectangle - see the RectanglePlacement
class for more details about this.
@param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
alpha channel will be used as a mask with which to
draw with the current brush or colour. This is
similar to fillAlphaMap(), and see also drawImage()
@see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
*/
void drawImageWithin (const Image& imageToDraw,
int destX, int destY, int destWidth, int destHeight,
RectanglePlacement placementWithinTarget,
bool fillAlphaChannelWithCurrentBrush = false) const;
//==============================================================================
/** Returns the position of the bounding box for the current clipping region.
@see clipRegionIntersects
*/
Rectangle<int> getClipBounds() const;
/** Checks whether a rectangle overlaps the context's clipping region.
If this returns false, no part of the given area can be drawn onto, so this
method can be used to optimise a component's paint() method, by letting it
avoid drawing complex objects that aren't within the region being repainted.
*/
bool clipRegionIntersects (Rectangle<int> area) const;
/** Intersects the current clipping region with another region.
@returns true if the resulting clipping region is non-zero in size
@see setOrigin, clipRegionIntersects
*/
bool reduceClipRegion (int x, int y, int width, int height);
/** Intersects the current clipping region with another region.
@returns true if the resulting clipping region is non-zero in size
@see setOrigin, clipRegionIntersects
*/
bool reduceClipRegion (Rectangle<int> area);
/** Intersects the current clipping region with a rectangle list region.
@returns true if the resulting clipping region is non-zero in size
@see setOrigin, clipRegionIntersects
*/
bool reduceClipRegion (const RectangleList<int>& clipRegion);
/** Intersects the current clipping region with a path.
@returns true if the resulting clipping region is non-zero in size
@see reduceClipRegion
*/
bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform());
/** Intersects the current clipping region with an image's alpha-channel.
The current clipping path is intersected with the area covered by this image's
alpha-channel, after the image has been transformed by the specified matrix.
@param image the image whose alpha-channel should be used. If the image doesn't
have an alpha-channel, it is treated as entirely opaque.
@param transform a matrix to apply to the image
@returns true if the resulting clipping region is non-zero in size
@see reduceClipRegion
*/
bool reduceClipRegion (const Image& image, const AffineTransform& transform);
/** Excludes a rectangle to stop it being drawn into. */
void excludeClipRegion (Rectangle<int> rectangleToExclude);
/** Returns true if no drawing can be done because the clip region is zero. */
bool isClipEmpty() const;
//==============================================================================
/** Saves the current graphics state on an internal stack.
To restore the state, use restoreState().
@see ScopedSaveState
*/
void saveState();
/** Restores a graphics state that was previously saved with saveState().
@see ScopedSaveState
*/
void restoreState();
/** Uses RAII to save and restore the state of a graphics context.
On construction, this calls Graphics::saveState(), and on destruction it calls
Graphics::restoreState() on the Graphics object that you supply.
*/
class JUCE_API ScopedSaveState
{
public:
ScopedSaveState (Graphics&);
~ScopedSaveState();
private:
Graphics& context;
JUCE_DECLARE_NON_COPYABLE (ScopedSaveState)
};
//==============================================================================
/** Begins rendering to an off-screen bitmap which will later be flattened onto the current
context with the given opacity.
The context uses an internal stack of temporary image layers to do this. When you've
finished drawing to the layer, call endTransparencyLayer() to complete the operation and
composite the finished layer. Every call to beginTransparencyLayer() MUST be matched
by a corresponding call to endTransparencyLayer()!
This call also saves the current state, and endTransparencyLayer() restores it.
*/
void beginTransparencyLayer (float layerOpacity);
/** Completes a drawing operation to a temporary semi-transparent buffer.
See beginTransparencyLayer() for more details.
*/
void endTransparencyLayer();
/** Moves the position of the context's origin.
This changes the position that the context considers to be (0, 0) to
the specified position.
So if you call setOrigin with (100, 100), then the position that was previously
referred to as (100, 100) will subsequently be considered to be (0, 0).
@see reduceClipRegion, addTransform
*/
void setOrigin (Point<int> newOrigin);
/** Moves the position of the context's origin.
This changes the position that the context considers to be (0, 0) to
the specified position.
So if you call setOrigin (100, 100), then the position that was previously
referred to as (100, 100) will subsequently be considered to be (0, 0).
@see reduceClipRegion, addTransform
*/
void setOrigin (int newOriginX, int newOriginY);
/** Adds a transformation which will be performed on all the graphics operations that
the context subsequently performs.
After calling this, all the coordinates that are passed into the context will be
transformed by this matrix.
@see setOrigin
*/
void addTransform (const AffineTransform& transform);
/** Resets the current colour, brush, and font to default settings. */
void resetToDefaultState();
/** Returns true if this context is drawing to a vector-based device, such as a printer. */
bool isVectorDevice() const;
//==============================================================================
/** Create a graphics that draws with a given low-level renderer.
This method is intended for use only by people who know what they're doing.
Note that the LowLevelGraphicsContext will NOT be deleted by this object.
*/
Graphics (LowLevelGraphicsContext&) noexcept;
/** @internal */
LowLevelGraphicsContext& getInternalContext() const noexcept { return context; }
private:
//==============================================================================
std::unique_ptr<LowLevelGraphicsContext> contextHolder;
LowLevelGraphicsContext& context;
bool saveStatePending = false;
void saveStateIfPending();
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Graphics)
};
} // namespace juce
@@ -0,0 +1,197 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
Interface class for graphics context objects, used internally by the Graphics class.
Users are not supposed to create instances of this class directly - do your drawing
via the Graphics object instead.
It's a base class for different types of graphics context, that may perform software-based
or OS-accelerated rendering.
E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
context.
@tags{Graphics}
*/
class JUCE_API LowLevelGraphicsContext
{
protected:
//==============================================================================
LowLevelGraphicsContext() = default;
public:
virtual ~LowLevelGraphicsContext() = default;
/** Returns true if this device is vector-based, e.g. a printer. */
virtual bool isVectorDevice() const = 0;
//==============================================================================
/** Moves the origin to a new position.
The coordinates are relative to the current origin, and indicate the new position
of (0, 0).
*/
virtual void setOrigin (Point<int>) = 0;
virtual void addTransform (const AffineTransform&) = 0;
virtual float getPhysicalPixelScaleFactor() const = 0;
virtual bool clipToRectangle (const Rectangle<int>&) = 0;
virtual bool clipToRectangleList (const RectangleList<int>&) = 0;
virtual void excludeClipRectangle (const Rectangle<int>&) = 0;
virtual void clipToPath (const Path&, const AffineTransform&) = 0;
virtual void clipToImageAlpha (const Image&, const AffineTransform&) = 0;
virtual bool clipRegionIntersects (const Rectangle<int>&) = 0;
virtual Rectangle<int> getClipBounds() const = 0;
virtual bool isClipEmpty() const = 0;
virtual void saveState() = 0;
virtual void restoreState() = 0;
virtual void beginTransparencyLayer (float opacity) = 0;
virtual void endTransparencyLayer() = 0;
//==============================================================================
virtual void setFill (const FillType&) = 0;
virtual void setOpacity (float) = 0;
virtual void setImageBlendMode (BlendMode) = 0;
virtual void setInterpolationQuality (Graphics::ResamplingQuality) = 0;
//==============================================================================
virtual void fillAll() { fillRect (getClipBounds(), false); }
virtual void fillRect (const Rectangle<int>&, bool replaceExistingContents) = 0;
virtual void fillRect (const Rectangle<float>&) = 0;
virtual void fillRectList (const RectangleList<float>&) = 0;
virtual void fillPath (const Path&, const AffineTransform&) = 0;
virtual void drawRect (const Rectangle<float>& rect, float lineThickness)
{
auto r = rect;
RectangleList<float> rects;
rects.addWithoutMerging (r.removeFromTop (lineThickness));
rects.addWithoutMerging (r.removeFromBottom (lineThickness));
rects.addWithoutMerging (r.removeFromLeft (lineThickness));
rects.addWithoutMerging (r.removeFromRight (lineThickness));
fillRectList (rects);
}
virtual void strokePath (const Path& path, const PathStrokeType& strokeType, const AffineTransform& transform)
{
Path stroke;
strokeType.createStrokedPath (stroke, path, transform, getPhysicalPixelScaleFactor());
fillPath (stroke, {});
}
virtual void drawImage (const Image&, const AffineTransform&) = 0;
virtual void drawLine (const Line<float>&) = 0;
virtual void drawLineWithThickness (const Line<float>& line, float lineThickness)
{
Path p;
p.addLineSegment (line, lineThickness);
fillPath (p, {});
}
virtual void setFont (const Font&) = 0;
virtual const Font& getFont() = 0;
/** Uses the current font to draw the provided glyph numbers. */
virtual void drawGlyphs (Span<const uint16_t>,
Span<const Point<float>>,
const AffineTransform&) = 0;
/** Returns the optimal ImageType for creating temporary images in this GraphicsContext.
While this typically matches the GraphicsContext's native ImageType, certain scenarios
may benefit from using a different format for temporary operations (e.g., for
performance, memory efficiency, or specific rendering requirements).
@return A unique_ptr to the recommended ImageType instance for temporary images
*/
virtual std::unique_ptr<ImageType> getPreferredImageTypeForTemporaryImages() const = 0;
virtual void drawRoundedRectangle (const Rectangle<float>& r, float cornerSize, float lineThickness)
{
Path p;
p.addRoundedRectangle (r, cornerSize);
strokePath (p, PathStrokeType (lineThickness), {});
}
virtual void fillRoundedRectangle (const Rectangle<float>& r, float cornerSize)
{
Path p;
p.addRoundedRectangle (r, cornerSize);
fillPath (p, {});
}
virtual void drawEllipse (const Rectangle<float>& area, float lineThickness)
{
Path p;
if (approximatelyEqual (area.getWidth(), area.getHeight()))
{
// For a circle, we can avoid having to generate a stroke
p.addEllipse (area.expanded (lineThickness * 0.5f));
p.addEllipse (area.reduced (lineThickness * 0.5f));
p.setUsingNonZeroWinding (false);
fillPath (p, {});
}
else
{
p.addEllipse (area);
strokePath (p, PathStrokeType (lineThickness), {});
}
}
virtual void fillEllipse (const Rectangle<float>& area)
{
Path p;
p.addEllipse (area);
fillPath (p, {});
}
/** Returns an integer that uniquely identifies the current frame.
Useful for debugging/logging.
*/
virtual uint64_t getFrameId() const = 0;
};
} // namespace juce
@@ -0,0 +1,223 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
class LowLevelGraphicsSoftwareRenderer::Impl : public RenderingHelpers::StackBasedLowLevelGraphicsContext<RenderingHelpers::SoftwareRendererSavedState>
{
public:
using SavedStateType = RenderingHelpers::SoftwareRendererSavedState;
using StackBasedLowLevelGraphicsContext::StackBasedLowLevelGraphicsContext;
std::unique_ptr<ImageType> getPreferredImageTypeForTemporaryImages() const override
{
jassertfalse;
return {};
}
};
LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image)
: impl (std::make_unique<Impl> (std::make_unique<Impl::SavedStateType> (image, image.getBounds())))
{
JUCE_TRACE_LOG_PAINT_CALL (etw::startGDIImage, getFrameId());
}
LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image, Point<int> origin,
const RectangleList<int>& initialClip)
: impl (std::make_unique<Impl> (std::make_unique<Impl::SavedStateType> (image, initialClip, origin)))
{
JUCE_TRACE_EVENT_INT_RECT_LIST (etw::startGDIFrame, etw::softwareRendererKeyword, getFrameId(), initialClip);
}
LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
{
JUCE_TRACE_LOG_PAINT_CALL (etw::endGDIFrame, getFrameId());
}
bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
{
return impl->isVectorDevice();
}
Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
{
return impl->getClipBounds();
}
bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
{
return impl->isClipEmpty();
}
void LowLevelGraphicsSoftwareRenderer::setOrigin (Point<int> o)
{
impl->setOrigin (o);
}
void LowLevelGraphicsSoftwareRenderer::addTransform (const AffineTransform& t)
{
impl->addTransform (t);
}
float LowLevelGraphicsSoftwareRenderer::getPhysicalPixelScaleFactor() const
{
return impl->getPhysicalPixelScaleFactor();
}
bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
{
return impl->clipRegionIntersects (r);
}
bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
{
return impl->clipToRectangle (r);
}
bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList<int>& r)
{
return impl->clipToRectangleList (r);
}
void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
{
impl->excludeClipRectangle (r);
}
void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& t)
{
impl->clipToPath (path, t);
}
void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& im, const AffineTransform& t)
{
impl->clipToImageAlpha (im, t);
}
void LowLevelGraphicsSoftwareRenderer::saveState()
{
impl->saveState();
}
void LowLevelGraphicsSoftwareRenderer::restoreState()
{
impl->restoreState();
}
void LowLevelGraphicsSoftwareRenderer::beginTransparencyLayer (float opacity)
{
impl->beginTransparencyLayer (opacity);
}
void LowLevelGraphicsSoftwareRenderer::endTransparencyLayer()
{
impl->endTransparencyLayer();
}
void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
{
impl->setFill (fillType);
}
void LowLevelGraphicsSoftwareRenderer::setImageBlendMode (BlendMode blendMode)
{
impl->setImageBlendMode (blendMode);
}
void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
{
impl->setOpacity (newOpacity);
}
void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
{
impl->setInterpolationQuality (quality);
}
void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, bool replace)
{
impl->fillRect (r, replace);
}
void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<float>& r)
{
impl->fillRect (r);
}
void LowLevelGraphicsSoftwareRenderer::fillRectList (const RectangleList<float>& list)
{
impl->fillRectList (list);
}
void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& t)
{
impl->fillPath (path, t);
}
void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& im, const AffineTransform& t)
{
impl->drawImage (im, t);
}
void LowLevelGraphicsSoftwareRenderer::drawLine (const Line<float>& line)
{
impl->drawLine (line);
}
void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
{
impl->setFont (newFont);
}
const Font& LowLevelGraphicsSoftwareRenderer::getFont()
{
return impl->getFont();
}
uint64_t LowLevelGraphicsSoftwareRenderer::getFrameId() const
{
return impl->getFrameId();
}
void LowLevelGraphicsSoftwareRenderer::drawGlyphs (Span<const uint16_t> glyphs,
Span<const Point<float>> positions,
const AffineTransform& t)
{
return impl->drawGlyphs (glyphs, positions, t);
}
} // namespace juce
@@ -0,0 +1,109 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
its rendering in memory.
User code is not supposed to create instances of this class directly - do all your
rendering via the Graphics class instead.
@tags{Graphics}
*/
class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
{
public:
//==============================================================================
/** Creates a context to render into an image. */
LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOnto);
/** Creates a context to render into a clipped subsection of an image. */
LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOnto, Point<int> origin,
const RectangleList<int>& initialClip);
/** Destructor. */
~LowLevelGraphicsSoftwareRenderer() override;
std::unique_ptr<ImageType> getPreferredImageTypeForTemporaryImages() const override
{
return std::make_unique<SoftwareImageType>();
}
bool isVectorDevice() const override;
Rectangle<int> getClipBounds() const override;
bool isClipEmpty() const override;
void setOrigin (Point<int> o) override;
void addTransform (const AffineTransform& t) override;
float getPhysicalPixelScaleFactor() const override;
bool clipRegionIntersects (const Rectangle<int>& r) override;
bool clipToRectangle (const Rectangle<int>& r) override;
bool clipToRectangleList (const RectangleList<int>& r) override;
void excludeClipRectangle (const Rectangle<int>& r) override;
void clipToPath (const Path& path, const AffineTransform& t) override;
void clipToImageAlpha (const Image& im, const AffineTransform& t) override;
void saveState() override;
void restoreState() override;
void beginTransparencyLayer (float opacity) override;
void endTransparencyLayer() override;
void setFill (const FillType& fillType) override;
void setImageBlendMode (BlendMode blendMode) override;
void setOpacity (float newOpacity) override;
void setInterpolationQuality (Graphics::ResamplingQuality quality) override;
void fillRect (const Rectangle<int>& r, bool replace) override;
void fillRect (const Rectangle<float>& r) override;
void fillRectList (const RectangleList<float>& list) override;
void fillPath (const Path& path, const AffineTransform& t) override;
void drawImage (const Image& im, const AffineTransform& t) override;
void drawLine (const Line<float>& line) override;
void setFont (const Font& newFont) override;
const Font& getFont() override;
uint64_t getFrameId() const override;
void drawGlyphs (Span<const uint16_t> glyphs,
Span<const Point<float>> positions,
const AffineTransform& t) override;
private:
class Impl;
std::unique_ptr<Impl> impl;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LowLevelGraphicsSoftwareRenderer)
};
} // namespace juce
@@ -0,0 +1,150 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
ScopedBlendContext::ScopedBlendContext (Graphics& g, const Options& optionsIn)
: parent (g),
options (optionsIn)
{
const auto clip = std::invoke ([&]
{
const auto parentClip = parent.getClipBounds();
if (! options.getScopeClip().has_value() || options.getScopeClip()->isEmpty())
return parentClip;
return options.getScopeClip()->getIntersection (parentClip);
});
auto imageType = std::invoke ([&]() -> std::unique_ptr<ImageType>
{
auto t = parent.getInternalContext().getPreferredImageTypeForTemporaryImages();
if (t->getTypeID() == 3)
return std::make_unique<SoftwareImageType>();
return t;
});
const auto sourceOnlyBlendMode = options.getBlendMode() == BlendMode::sourceOver
|| options.getBlendMode() == BlendMode::source;
// If the blending mode only affects the source area, we can restrict the final image blend to
// the current the clip bounds. If, however, we're doing something more sophisticated, all
// pixels outside the currently drawn bounds need to be treated as transparent black, and
// blended with all pixels of the parent image.
const auto clipToUse = sourceOnlyBlendMode ? clip : parent.getClipBounds();
clipIsEmpty = clipToUse.isEmpty();
const auto blendContextScale = parent.getInternalContext().getPhysicalPixelScaleFactor();
const auto scaledClip = clipToUse * blendContextScale;
buffer = { Image::ARGB,
std::max (1, scaledClip.getWidth()),
std::max (1, scaledClip.getHeight()),
true,
*imageType };
blendContext.emplace (buffer);
blendContextTransform = AffineTransform::scale (blendContextScale).translated ((float) -scaledClip.getX(),
(float) -scaledClip.getY());
blendContext->addTransform (blendContextTransform);
}
ScopedBlendContext::~ScopedBlendContext()
{
blendContext.reset();
if (clipIsEmpty)
return;
if (options.isLuminanceMask())
convertLuminanceToAlpha (buffer);
const Graphics::ScopedSaveState s { parent };
parent.setImageBlendMode (options.getBlendMode());
parent.setOpacity (options.getOpacity());
parent.addTransform (blendContextTransform.inverted());
parent.drawImage (buffer,
bufferPosition.getX(),
bufferPosition.getY(),
buffer.getWidth(),
buffer.getHeight(),
0,
0,
buffer.getWidth(),
buffer.getHeight());
}
void ScopedBlendContext::convertLuminanceToAlpha (Image& image)
{
if (! image.isARGB())
{
jassertfalse;
return;
}
Image::BitmapData data (image, Image::BitmapData::readWrite);
for (int y = 0; y < data.height; ++y)
{
auto* line = data.getLinePointer (y);
for (int x = 0; x < data.width; ++x)
{
auto* p = reinterpret_cast<PixelARGB*> (line);
const auto a = (int) p->getAlpha();
auto r = (int) p->getRed();
auto g = (int) p->getGreen();
auto b = (int) p->getBlue();
if (a > 0)
{
r = (r * 255) / a;
g = (g * 255) / a;
b = (b * 255) / a;
}
auto l = (r * 0.2125 + g * 0.7154 + b * 0.0721) * (a / 255.0);
*p = PixelARGB { (uint8) l, (uint8) 0, (uint8) 0, (uint8) 0 };
line += data.pixelStride;
}
}
}
} // namespace juce
@@ -0,0 +1,164 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
class JUCE_API ScopedBlendContextOptions
{
public:
ScopedBlendContextOptions() = default;
/** Creates an object using the provided blend mode. */
explicit ScopedBlendContextOptions (BlendMode mode)
: blendMode (mode)
{}
/** Specifies the blend mode to be applied when blending the backing buffer into the parent
buffer.
@see BlendMode
*/
[[nodiscard]] ScopedBlendContextOptions withBlendMode (BlendMode x) const
{
return withMember (*this, &ScopedBlendContextOptions::blendMode, x);
}
/** When this option is set, the backing buffer's luminosity is converted to alpha values prior
to blending it into the parent buffer.
After conversion, the RGB components are zero, and the A component is calculated using the
equation in the SVG specification A = ((0.2125 * R) + (0.7154 * G) + (0.0721 * B)) * A.
*/
[[nodiscard]] ScopedBlendContextOptions withLuminanceMaskSet (bool x = true) const
{
return withMember (*this, &ScopedBlendContextOptions::luminanceMask, x);
}
/** Allows specifying an additional clip for the blend context, reducing the necessary size of
the backing buffer.
By default the backing buffer will be the same size as the parent context's clip region.
Even if this value is provided, it is ignored for certain blending modes such as
destinationIn and destinationOut.
*/
[[nodiscard]] ScopedBlendContextOptions withScopeClip (Rectangle<int> x) const
{
return withMember (*this, &ScopedBlendContextOptions::scopeClip, x);
}
/** Allows specifying an additional opacity value that is applied prior to blending the buffer
into the parent.
*/
[[nodiscard]] ScopedBlendContextOptions withOpacity (float x) const
{
return withMember (*this, &ScopedBlendContextOptions::opacity, x);
}
/** @see withBlendMode() */
const auto& getBlendMode() const { return blendMode; }
/** @see withLuminanceMaskSet() */
const auto& isLuminanceMask() const { return luminanceMask; }
/** @see withScopeClip() */
const auto& getScopeClip() const { return scopeClip; }
/** @see withOpacity() */
const auto& getOpacity() const { return opacity; }
private:
BlendMode blendMode = BlendMode::sourceOver;
bool luminanceMask = false;
std::optional<Rectangle<int>> scopeClip;
float opacity = 1.0f;
};
//==============================================================================
/** Uses RAII to create a temporary image that is blended into the parent context
when this object goes out of scope.
*/
class JUCE_API ScopedBlendContext
{
public:
using Options = ScopedBlendContextOptions;
/** Constructor.
The image drawn into the context returned by getContext() will be blended into the context
passed in here when this object is destroyed.
@see ScopedBlendContextOptions
*/
ScopedBlendContext (Graphics& g, const Options& options);
/** Returns the context for drawing the image that will be blended into the parent context. */
Graphics& getContext()
{
return *blendContext;
}
/** Returns true if the clip region for this context is empty. This allows the call site to
omit draw calls that wouldn't have a visible effect anyway.
*/
bool isClipEmpty() const
{
return clipIsEmpty;
}
/** Destructor */
~ScopedBlendContext();
private:
/* Implements https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Attribute/mask-type#luminance
*/
static void convertLuminanceToAlpha (Image& image);
Graphics createBlendContext();
Graphics& parent;
Options options;
Image buffer;
Point<int> bufferPosition;
bool clipIsEmpty = false;
// This object needs to be destroyed before we blend its buffer into the parent in the destructor.
std::optional<Graphics> blendContext;
AffineTransform blendContextTransform;
};
} // namespace juce
@@ -0,0 +1,621 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce::detail
{
void drawJustifiedText (const JustifiedText& text, const Graphics& g, AffineTransform);
//==============================================================================
static constexpr auto maxWidthTolerance = 0.005f;
static int64 getNumLeadingWhitespaces (Span<const ShapedGlyph> glyphs)
{
const auto it = std::find_if_not (glyphs.begin(),
glyphs.end(),
[&] (const auto& g) { return g.isWhitespace(); });
return (int64) std::distance (glyphs.begin(), it);
}
static int64 getNumTrailingWhitespaces (Span<const ShapedGlyph> glyphs)
{
if (glyphs.empty())
return 0;
int64 trailingWhitespaces = 0;
for (auto it = glyphs.end(); --it >= glyphs.begin() && it->isWhitespace();)
++trailingWhitespaces;
return trailingWhitespaces;
}
struct NumWhitespaces
{
int64 total{}, leading{}, trailing{};
};
static NumWhitespaces getNumWhitespaces (Span<const ShapedGlyph> glyphs)
{
const auto total = std::count_if (glyphs.begin(),
glyphs.end(),
[] (const auto& g) { return g.isWhitespace(); });
return { total, getNumLeadingWhitespaces (glyphs), getNumTrailingWhitespaces (glyphs) };
}
struct LineLength
{
float total{}, withoutTrailingWhitespaces{};
};
static LineLength getMainAxisLineLength (Span<const ShapedGlyph> glyphs)
{
const auto total = std::accumulate (glyphs.begin(),
glyphs.end(),
0.0f,
[] (auto acc, const auto& g) { return acc + g.advance.getX(); });
auto trailingWhitespacesLength = 0.0f;
if (glyphs.empty())
return {};
for (auto it = glyphs.end(); --it >= glyphs.begin() && it->isWhitespace();)
trailingWhitespacesLength += it->advance.getX();
return { total, total - trailingWhitespacesLength };
}
static float getMainAxisLineLength (Span<const ShapedGlyph> glyphs, bool trailingWhitespacesShouldFit)
{
const auto lengths = getMainAxisLineLength (glyphs);
return trailingWhitespacesShouldFit ? lengths.total : lengths.withoutTrailingWhitespaces;
}
struct MainAxisLineAlignment
{
float anchor{}, extraWhitespaceAdvance{}, effectiveLineLength{};
Range<int64> stretchableWhitespaces;
};
static MainAxisLineAlignment getMainAxisLineAlignment (Justification justification,
Span<const ShapedGlyph> glyphs,
LineLength lineLength,
std::optional<float> maxWidthOpt,
std::optional<float> alignmentWidthOpt,
bool trailingWhitespacesShouldFit)
{
const auto effectiveLineLength = (trailingWhitespacesShouldFit ? lineLength.total
: lineLength.withoutTrailingWhitespaces);
const auto alignmentWidth = alignmentWidthOpt.value_or (maxWidthOpt.value_or (0.0f));
const auto tooLong = alignmentWidth + maxWidthTolerance < effectiveLineLength;
MainAxisLineAlignment result;
result.effectiveLineLength = effectiveLineLength;
// The alignment width opt is supporting the TextEditor use-case where all text remains visible
// with scrolling, even if longer than the alignment width. We don't need to worry about the
// front of and RTL text being visually truncated, because nothing is truncated.
if (tooLong && alignmentWidthOpt.has_value())
return result;
const auto mainAxisLineOffset = [&]
{
if (tooLong)
{
const auto approximateIsLeftToRight = [&]
{
if (glyphs.empty())
return true;
return glyphs.front().cluster <= glyphs.back().cluster;
}();
// We don't have to align LTR text, but we need to ensure that it's the logical back of
// RTL text that falls outside the bounds.
if (approximateIsLeftToRight)
return 0.0f;
return alignmentWidth - effectiveLineLength;
}
if (justification.testFlags (Justification::horizontallyCentred))
{
return (alignmentWidth - lineLength.withoutTrailingWhitespaces) / 2.0f;
}
if (justification.testFlags (Justification::right))
return alignmentWidth - effectiveLineLength;
return 0.0f;
}();
const auto numWhitespaces = getNumWhitespaces (glyphs);
const auto stretchableWhitespaces = [&]() -> Range<int64>
{
if (! justification.testFlags (Justification::horizontallyJustified) || tooLong)
return {};
return { numWhitespaces.leading, (int64) glyphs.size() - numWhitespaces.trailing };
}();
const auto extraWhitespaceAdvance = [&]
{
if (! justification.testFlags (Justification::horizontallyJustified) || tooLong)
return 0.0f;
const auto numWhitespacesBetweenWords = numWhitespaces.total
- numWhitespaces.leading
- numWhitespaces.trailing;
return numWhitespacesBetweenWords > 0 ? (alignmentWidth - effectiveLineLength) / (float) numWhitespacesBetweenWords
: 0.0f;
}();
return { mainAxisLineOffset, extraWhitespaceAdvance, effectiveLineLength, stretchableWhitespaces };
}
struct LineInfo
{
float lineHeight{}, maxAscent{};
MainAxisLineAlignment mainAxisLineAlignment;
};
static float getCrossAxisStartingAnchor (Justification justification,
Span<const LineInfo> lineInfos,
std::optional<float> height,
float leading)
{
if (lineInfos.empty())
return 0.0f;
const auto minimumTop = lineInfos.front().maxAscent * leading;
if (! height.has_value())
return minimumTop;
const auto textHeight = std::accumulate (lineInfos.begin(),
lineInfos.end(),
0.0f,
[leading] (auto acc, const auto info) { return acc + info.lineHeight * leading; });
if (justification.testFlags (Justification::verticallyCentred))
return (*height - textHeight) / 2.0f + lineInfos.front().maxAscent;
if (justification.testFlags (Justification::bottom))
{
return *height - textHeight + lineInfos.front().maxAscent * leading;
}
return minimumTop;
}
JustifiedText::JustifiedText (const SimpleShapedText* t, const ShapedTextOptions& options)
: shapedText (*t)
{
std::vector<LineInfo> lineInfos;
for (const auto [range, lineNumber] : shapedText.getLineNumbersForGlyphRanges())
{
// This is guaranteed by the RangedValues implementation. You can't assign a value to an
// empty range.
jassert (! range.isEmpty());
const auto fonts = shapedText.getResolvedFonts().getIntersectionsWith (range);
const auto lineHeight = std::accumulate (fonts.begin(),
fonts.end(),
0.0f,
[] (auto acc, const auto& rangedFont)
{ return std::max (acc, rangedFont.value.getHeight()); });
const auto maxAscent = std::accumulate (fonts.begin(),
fonts.end(),
0.0f,
[] (auto acc, const auto& rangedFont)
{ return std::max (acc, rangedFont.value.getAscent()); });
const auto glyphs = shapedText.getGlyphs (range);
const auto lineLength = getMainAxisLineLength (glyphs);
auto m = [&]
{
return getMainAxisLineAlignment (options.getJustification(),
glyphs,
lineLength,
options.getWordWrapWidth(),
options.getAlignmentWidth(),
options.getTrailingWhitespacesShouldFit());
}();
const auto containsHardBreak = shapedText.getCodepoint (range.getEnd() - 1) == 0xa
|| shapedText.getCodepoint (range.getStart()) == 0xa;
if (containsHardBreak || lineNumber == shapedText.getLineNumbersForGlyphRanges().back().value)
{
m.extraWhitespaceAdvance = {};
m.stretchableWhitespaces = {};
}
lineInfos.push_back ({ lineHeight, maxAscent, std::move (m) });
minimumRequiredWidthsForLine.push_back (options.getTrailingWhitespacesShouldFit() ? lineLength.total
: lineLength.withoutTrailingWhitespaces);
}
auto baseline = options.isBaselineAtZero() ? 0.0f
: getCrossAxisStartingAnchor (options.getJustification(),
lineInfos,
options.getHeight(),
options.getLeading());
detail::Ranges::Operations ops;
std::optional<float> top;
for (const auto [lineIndex, lineInfo] : enumerate (lineInfos))
{
const auto lineNumber = shapedText.getLineNumbersForGlyphRanges().getItem ((size_t) lineIndex);
const auto range = lineNumber.range;
const auto maxDescent = lineInfo.lineHeight - lineInfo.maxAscent;
const auto nextLineTop = baseline + options.getLeading() * maxDescent + options.getAdditiveLineSpacing();
if (! top.has_value())
top = baseline - options.getLeading() * lineInfo.maxAscent;
lineMetricsForGlyphRange.set (range,
{ lineNumber.value,
{ lineInfo.mainAxisLineAlignment.anchor, baseline },
lineInfo.maxAscent * options.getLeading(),
(lineInfo.lineHeight - lineInfo.maxAscent) * options.getLeading(),
lineInfo.mainAxisLineAlignment.effectiveLineLength
+ lineInfo.mainAxisLineAlignment.extraWhitespaceAdvance,
*top,
nextLineTop },
ops,
MergeEqualItemsNo{});
whitespaceStretch.set (range, 0.0f, ops);
const auto stretchRange = lineInfo.mainAxisLineAlignment.stretchableWhitespaces + range.getStart();
whitespaceStretch.set (stretchRange,
lineInfo.mainAxisLineAlignment.extraWhitespaceAdvance,
ops);
ops.clear();
const auto nextLineMaxAscent = lineIndex < (int) lineInfos.size() - 1 ? lineInfos[(size_t) lineIndex + 1].maxAscent : 0.0f;
baseline = nextLineTop + options.getLeading() * nextLineMaxAscent;
top = nextLineTop;
}
rangesToDraw.set ({ 0, (int64) shapedText.getGlyphs().size() }, DrawType::normal, ops);
if (options.getDrawLinesInFull())
return;
//==============================================================================
// Everything above this line should work well given none of the lines were too
// long. When Options::getMaxNumLines() == 0 this is guaranteed by SimpleShapedText.
// The remaining logic below is for supporting
// GlyphArrangement::addFittedText() when the maximum number of lines is
// constrained.
if (lineMetricsForGlyphRange.isEmpty())
return;
const auto lastLineMetrics = lineMetricsForGlyphRange.back();
const auto lastLineGlyphRange = lastLineMetrics.range;
const auto lastLineGlyphs = shapedText.getGlyphs (lastLineGlyphRange);
const auto lastLineLengths = getMainAxisLineLength (lastLineGlyphs);
const auto effectiveLength = options.getTrailingWhitespacesShouldFit() ? lastLineLengths.total
: lastLineLengths.withoutTrailingWhitespaces;
if (! options.getWordWrapWidth().has_value()
|| effectiveLength <= *options.getWordWrapWidth() + maxWidthTolerance)
return;
const auto cutoffAtFront = lastLineMetrics.value.anchor.getX() < 0.0f - maxWidthTolerance;
const auto getLastLineVisibleRange = [&] (float ellipsisLength)
{
const auto r = [&]() -> Range<int64>
{
if (cutoffAtFront)
{
auto length = lastLineLengths.total;
for (auto it = lastLineGlyphs.begin(); it < lastLineGlyphs.end(); ++it)
{
length -= it->advance.getX();
if (! options.getWordWrapWidth().has_value()
|| *options.getWordWrapWidth() >= ellipsisLength + length)
{
return { (int64) std::distance (lastLineGlyphs.begin(), it) + 1,
(int64) lastLineGlyphs.size() };
}
}
}
else
{
auto length = lastLineLengths.total;
for (auto it = lastLineGlyphs.end() - 1; it >= lastLineGlyphs.begin(); --it)
{
length -= it->advance.getX();
if (! options.getWordWrapWidth().has_value()
|| *options.getWordWrapWidth() >= ellipsisLength + length)
{
return { 0, (int64) std::distance (lastLineGlyphs.begin(), it) };
}
}
}
return {};
}();
return r.movedToStartAt (r.getStart() + lastLineGlyphRange.getStart());
};
const auto lastLineVisibleRangeWithoutEllipsis = getLastLineVisibleRange (0.0f);
const auto eraseLastLineFromRangesToDraw = [&]
{
rangesToDraw.eraseFrom (lastLineGlyphRange.getStart(), ops);
ops.clear();
};
eraseLastLineFromRangesToDraw();
rangesToDraw.set (lastLineVisibleRangeWithoutEllipsis, DrawType::normal, ops);
ops.clear();
if (options.getEllipsis().isEmpty())
{
return;
}
//==============================================================================
// More logic supporting using ellipses
const auto fontForEllipsis = [&]
{
const auto lastLineFonts = shapedText.getResolvedFonts().getIntersectionsWith (lastLineGlyphRange);
if (cutoffAtFront)
return lastLineFonts.front().value;
return lastLineFonts.back().value;
}();
ellipsis.emplace (&options.getEllipsis(), ShapedTextOptions {}.withFont (fontForEllipsis));
const auto lastLineVisibleRange = getLastLineVisibleRange (getMainAxisLineLength (ellipsis->getGlyphs(),
options.getTrailingWhitespacesShouldFit()));
eraseLastLineFromRangesToDraw();
rangesToDraw.set (lastLineVisibleRange, DrawType::normal, ops);
ops.clear();
if (cutoffAtFront)
rangesToDraw.set (Range<int64>::withStartAndLength (lastLineVisibleRange.getStart() - 1, 1), DrawType::ellipsis, ops);
else
rangesToDraw.set (Range<int64>::withStartAndLength (lastLineVisibleRange.getEnd(), 1), DrawType::ellipsis, ops);
ops.clear();
const auto lineWithEllipsisGlyphs = [&]
{
std::vector<ShapedGlyph> result;
const auto pushEllipsisGlyphs = [&]
{
const auto& range = ellipsis->getGlyphs();
result.insert (result.begin(), range.begin(), range.end());
};
if (cutoffAtFront)
pushEllipsisGlyphs();
const auto& range = shapedText.getGlyphs (lastLineVisibleRange);
result.insert (result.end(), range.begin(), range.end());
if (! cutoffAtFront)
pushEllipsisGlyphs();
return result;
}();
const auto realign = [&]
{
return getMainAxisLineAlignment (options.getJustification(),
lineWithEllipsisGlyphs,
getMainAxisLineLength (lineWithEllipsisGlyphs),
options.getWordWrapWidth(),
options.getAlignmentWidth(),
options.getTrailingWhitespacesShouldFit());
}();
lastLineMetrics.value.anchor.setX (realign.anchor);
whitespaceStretch.set (lastLineGlyphRange, 0.0f, ops);
whitespaceStretch.set (realign.stretchableWhitespaces + lastLineVisibleRange.getStart(),
realign.extraWhitespaceAdvance, ops);
}
int64 JustifiedText::getGlyphIndexToTheRightOf (Point<float> p) const
{
auto lineIt = lineMetricsForGlyphRange.begin();
float lineTop = 0.0f;
while (lineIt != lineMetricsForGlyphRange.end())
{
const auto nextLineTop = lineIt->value.nextLineTop;
if (lineTop <= p.getY() && p.getY() < nextLineTop)
break;
lineTop = nextLineTop;
++lineIt;
}
if (lineIt == lineMetricsForGlyphRange.end())
return 0;
const auto glyphsInLine = shapedText.getGlyphs (lineIt->range);
auto glyphX = lineIt->value.anchor.getX();
for (const auto [glyphIndex, glyph] : enumerate (glyphsInLine, lineIt->range.getStart()))
{
if (p.getX() < glyphX + glyph.advance.getX() / 2.0f || glyph.isNewline())
return glyphIndex;
glyphX += glyph.advance.getX();
}
return lineIt->range.getEnd();
}
GlyphAnchorResult JustifiedText::getGlyphAnchor (int64 index) const
{
jassert (index >= 0);
if (lineMetricsForGlyphRange.isEmpty())
return {};
const auto lineItem = lineMetricsForGlyphRange.getItemWithEnclosingRange (index)
.value_or (lineMetricsForGlyphRange.back());
const auto indexInLine = index - lineItem.range.getStart();
GlyphAnchorResult anchor { lineItem.value.anchor, lineItem.value.maxAscent, lineItem.value.maxDescent };
for (auto [i, glyph] : enumerate (shapedText.getGlyphs (lineItem.range), int64{}))
{
if (i == indexInLine)
{
anchor.anchor += glyph.offset;
return anchor;
}
anchor.anchor += glyph.advance;
}
return anchor;
}
RectangleList<float> JustifiedText::getGlyphsBounds (Range<int64> glyphRange) const
{
RectangleList<float> bounds;
if (lineMetricsForGlyphRange.isEmpty())
return bounds;
const auto getBounds = [&] (const LineMetrics& line, int64 lineStart, int64 boundsStart, int64 boundsEnd) -> Rectangle<float>
{
const auto glyphsBefore = shapedText.getGlyphs ({ lineStart, boundsStart });
const auto xStart = std::accumulate (glyphsBefore.begin(),
glyphsBefore.end(),
line.anchor.getX(),
[] (auto sum, auto glyph)
{
return sum + glyph.advance.getX();
});
const auto glyphs = shapedText.getGlyphs ({ boundsStart, boundsEnd });
const auto xEnd = std::accumulate (glyphs.begin(),
glyphs.end(),
xStart,
[&] (auto sum, auto glyph)
{
return sum + glyph.advance.getX();
});
return { { xStart, line.top }, { xEnd, line.nextLineTop } };
};
for (auto consumeFrom = glyphRange.getStart(); consumeFrom < glyphRange.getEnd();)
{
const auto lineItem = lineMetricsForGlyphRange.getItemWithEnclosingRange (consumeFrom);
if (! lineItem.has_value())
break;
const auto consumeTo = std::min (glyphRange.getEnd(), lineItem->range.getEnd());
bounds.add (getBounds (lineItem->value, lineItem->range.getStart(), consumeFrom, consumeTo));
consumeFrom = consumeTo;
}
return bounds;
}
float JustifiedText::getHeight() const
{
if (lineMetricsForGlyphRange.isEmpty())
return 0.0f;
return lineMetricsForGlyphRange.back().value.nextLineTop;
}
void drawJustifiedText (const JustifiedText& text, const Graphics& g, AffineTransform transform)
{
auto& context = g.getInternalContext();
context.saveState();
const ScopeGuard restoreGraphicsContext { [&context] { context.restoreState(); } };
text.accessTogetherWith ([&] (auto glyphs, auto positions, auto font, auto, auto)
{
if (context.getFont() != font)
context.setFont (font);
std::vector<uint16_t> glyphIds (glyphs.size());
std::transform (glyphs.begin(),
glyphs.end(),
glyphIds.begin(),
[] (auto& glyph) { return (uint16_t) glyph.glyphId; });
context.drawGlyphs (glyphIds, positions, transform);
});
}
} // namespace juce::detail
@@ -0,0 +1,233 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce::detail
{
template <size_t StartingAt, typename Tuple, size_t... Is>
constexpr auto partiallyUnpackImpl (Tuple&& tuple, std::index_sequence<Is...>)
{
return std::tie (std::get<StartingAt + Is> (tuple)...);
}
template <size_t StartingAt, size_t NumElems, typename Tuple>
constexpr auto partiallyUnpack (Tuple&& tuple)
{
return partiallyUnpackImpl<StartingAt> (std::forward<Tuple> (tuple), std::make_index_sequence<NumElems>{});
}
//==============================================================================
struct LineMetrics
{
int64 lineNumber;
Point<float> anchor;
float maxAscent;
float maxDescent;
/* Effective suggests the length of trailing whitespaces will be included or not depending on
ShapedTextOptions::getTrailingWhitespacesShouldFit().
*/
float effectiveLineLength;
/* These values seem redundant given the relation between the baseline, ascent and top, but
we want to ensure exactlyEquals (top, nextLineTop) for subsequent lines.
*/
float top;
/* This will be below the current line's visual bottom if non-default leading or additive
line spacing is used.
*/
float nextLineTop;
};
struct GlyphAnchorResult
{
Point<float> anchor;
float maxAscent{};
float maxDescent{};
};
//==============================================================================
class JustifiedText
{
private:
enum class DrawType
{
normal,
ellipsis
};
public:
JustifiedText (const SimpleShapedText* t, const ShapedTextOptions& options);
/* Provides access to the data stored in the ShapedText.
The provided callable will be called multiple times for "uniform glyph runs", for which all
callback parameters are the same.
Between each subsequent callback at least one of the provided parameters will be different.
The callbacks happen in visual order i.e. left to right, which is irrespective of the
underlying text's writing direction.
The callback parameters in order are:
- the glyphs
- the positions for each glyph in the previous parameter
- the Font with which these glyphs should be rendered
- the range in all glyphs this ShapedText object holds, that correspond to the current glyphs
- a line number which increases by one for each new line
- followed by any number of ValueType parameters for the supplied RangedValues<ValueType> arguments
*/
template <typename Callable, typename... RangedValues>
void accessTogetherWith (Callable&& callback, RangedValues&&... rangedValues) const
{
std::optional<int64> lastLine;
int64 lastGlyph = 0;
Point<float> anchor {};
for (const auto item : makeIntersectingRangedValues (&shapedText.getResolvedFonts(),
&lineMetricsForGlyphRange,
&rangesToDraw,
&whitespaceStretch,
(&rangedValues)...))
{
const auto& [range, font, lineMetrics, drawType, stretch] = partiallyUnpack<0, 5> (item);
const auto& rest = partiallyUnpack<5, std::tuple_size_v<decltype (item)> - 5> (item);
if (std::exchange (lastLine, lineMetrics.lineNumber) != lineMetrics.lineNumber)
anchor = lineMetrics.anchor;
if (range.getStart() != lastGlyph && drawType != DrawType::ellipsis)
{
detail::RangedValues<int8_t> glyphMask;
Ranges::Operations ops;
const auto firstGlyphInCurrentLine = shapedText.getLineNumbersForGlyphRanges().getItem ((size_t) lineMetrics.lineNumber)
.range
.getStart();
glyphMask.set ({ std::max (lastGlyph, firstGlyphInCurrentLine), range.getStart() }, 1, ops);
for (const auto [skippedRange, skippedStretch, _] : makeIntersectingRangedValues (&whitespaceStretch,
&glyphMask))
{
ignoreUnused (_);
for (const auto& skippedGlyph : shapedText.getGlyphs (skippedRange))
{
anchor += skippedGlyph.advance;
if (skippedGlyph.isWhitespace())
anchor.addXY (skippedStretch, 0.0f);
}
}
}
lastGlyph = range.getEnd();
const auto glyphs = [this, r = range, dt = drawType]() -> Span<const ShapedGlyph>
{
if (dt == DrawType::ellipsis)
return ellipsis->getGlyphs();
return shapedText.getGlyphs (r);
}();
std::vector<Point<float>> positions (glyphs.size());
std::transform (glyphs.begin(),
glyphs.end(),
positions.begin(),
[&anchor, &s = stretch] (auto& glyph)
{
auto result = anchor + glyph.offset;
anchor += glyph.advance;
if (glyph.isWhitespace())
anchor.addXY (s, 0.0f);
return result;
});
const auto callbackFont =
drawType == DrawType::ellipsis ? ellipsis->getResolvedFonts().front().value : font;
const auto callbackParameters =
std::tuple_cat (std::tie (glyphs, positions, callbackFont, range, lineMetrics), rest);
const auto invokeNullChecked = [&] (auto&... params)
{ NullCheckedInvocation::invoke (callback, params...); };
std::apply (invokeNullChecked, callbackParameters);
}
}
/* This is how much cumulative widths glyphs take up in each line. Whether the trailing
whitespace is included depends on the ShapedTextOptions::getWhitespaceShouldFitInLine()
setting.
*/
auto& getMinimumRequiredWidthForLines() const { return minimumRequiredWidthsForLine; }
int64 getGlyphIndexToTheRightOf (Point<float> p) const;
/* If the passed in index parameter is greater than the index of the last contained glyph,
then the returned anchor specifies the location where the next glyph would have to be
placed i.e. lastGlyphAnchor + lastGlyphAdvance.
*/
GlyphAnchorResult getGlyphAnchor (int64 glyphIndex) const;
RectangleList<float> getGlyphsBounds (Range<int64> glyphRange) const;
/* Returns the vertical distance from the baseline of the first line to the bottom of the last
plus any additional line spacing that follows from the leading and additiveLineSpacing
members of the ShapedTextOptions object.
This guarantees that if ShapedText object1 is drawn at y = 0 and object2 is drawn at
y = object1.getHeight(), then the two texts will be spaced exactly as if they were a single
ShapedText object containing both texts.
*/
float getHeight() const;
const auto& getLineMetricsForGlyphRange() const { return lineMetricsForGlyphRange; }
private:
const SimpleShapedText& shapedText;
detail::RangedValues<LineMetrics> lineMetricsForGlyphRange;
std::optional<SimpleShapedText> ellipsis;
detail::RangedValues<DrawType> rangesToDraw;
detail::RangedValues<float> whitespaceStretch;
std::vector<float> minimumRequiredWidthsForLine;
};
} // namespace juce::detail
@@ -0,0 +1,175 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce::detail
{
/* Very nearly a drop in replacement for lunasvg::Font. This allows us to bypass lunasvg's Font
rendering and plug in JUCE's Font related functionality.
*/
class LunaSvgFontReplacement
{
public:
LunaSvgFontReplacement() = default;
LunaSvgFontReplacement (float size, const std::string& family, bool bold, bool italic)
{
const auto getStyleFlags = [] (const bool b, const bool i) noexcept
{
int flags{};
if (b) flags |= Font::bold;
if (i) flags |= Font::italic;
return flags;
};
font = std::invoke (
[&]
{
juce::StringArray tokens;
tokens.addTokens (family, ",", "");
std::vector<String> fallbacks ((size_t) tokens.size());
std::transform (tokens.begin(),
tokens.end(),
fallbacks.begin(),
[] (const String& s) { return s.trim(); });
auto options = FontOptions{}.withPointHeight (size)
.withFallbacks (fallbacks)
.withStyleFlags (getStyleFlags (bold, italic));
if (! fallbacks.empty())
options = options.withName (fallbacks[0]);
return Font { options };
});
GlyphArrangement arr;
arr.addLineOfText (*font, "x", 0.0f, 0.0f);
fontXHeight = std::invoke ([&]
{
if (arr.getNumGlyphs() == 0)
return font->getHeight();
auto typefacePtr = font->getTypefacePtr();
if (typefacePtr == nullptr)
return 0.0f;
const auto xBoundsNormalised = typefacePtr->getGlyphBounds (arr.getGlyph (0).getGlyphIndex());
return xBoundsNormalised.getHeight() * font->getHeightInPoints();
});
}
float ascent() const
{
if (! font.has_value())
return 0.0f;
return font->getAscentInPoints();
}
float descent() const
{
if (! font.has_value())
return 0.0f;
return font->getDescentInPoints();
}
float height() const
{
if (! font.has_value())
return 0.0f;
// This is a little strange. Checking the numerical values inside lunasvg, we need to return
// the font height, NOT the point height. But fontXHeight needs to be calculated using the
// point height. This way we get the same text layout as in lunasvg. But the mix of the two
// values is perplexing.
return font->getHeight();
}
float lineGap() const
{
if (! font.has_value())
return 0.0f;
return font->getLineGapInPoints();
}
float xHeight() const
{
return fontXHeight;
}
float measureText (const std::u32string_view& text) const
{
if (! font.has_value())
return 0.0f;
const auto s = juce::String { juce::CharPointer_UTF32 (reinterpret_cast<const CharPointer_UTF32::CharType*> (text.data())),
text.length() };
return GlyphArrangement::getStringWidth (*font, s);
}
float size() const
{
if (! font.has_value())
return 0.0f;
return font->getHeightInPoints();
}
bool isNull() const
{
if (! font.has_value())
return 0.0f;
return ! font.has_value();
}
const Font& getFont() const
{
return *font;
}
private:
std::optional<Font> font;
float fontXHeight = 0.0f;
};
} // namespace juce::detail
@@ -0,0 +1,871 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce::detail
{
#if JUCE_UNIT_TESTS
template <typename T, typename = void>
constexpr auto hasGetStartFunction = false;
template <typename T>
constexpr auto hasGetStartFunction<T, std::void_t<decltype (std::declval<T>().getStart())>> = true;
template <typename RangeType, typename std::enable_if<hasGetStartFunction<RangeType>, int>::type = 0>
std::ostream& operator<< (std::ostream& os, const RangeType& range)
{
os << "[" << range.getStart() << ", " << range.getEnd() << ")";
return os;
}
static String& operator<< (String& s, Range<int64> r)
{
return s += "[" + String { r.getStart() } + ", " + String { r.getEnd() } + ")";
}
template <typename ValueType>
static auto getCumulativeRangeLengths (const RangedValues<ValueType>& rv)
{
int64 totalLength{};
for (size_t i = 0; i < rv.size(); ++i)
totalLength += rv.getItem (i).range.getLength();
return totalLength;
}
template <typename ValueType>
static auto toString (const RangedValues<ValueType>& rv)
{
String s {};
for (size_t i = 0; i < rv.size(); ++i)
{
auto item = rv.getItem (i);
s << item.range << ": " << item.value << "\n";
}
return s;
}
class RangesTestsBase : public UnitTest
{
public:
using UnitTest::UnitTest;
void expectRange (Range<int64> actual, Range<int64> expected)
{
String failureMessage { "range " };
failureMessage << actual << " did not equal expected range " << expected;
expect (actual == expected, failureMessage);
}
};
class RangesTests : public RangesTestsBase
{
public:
RangesTests() : RangesTestsBase ("Ranges", UnitTestCategories::containers) {}
void runTest() override
{
Ranges::Operations ops;
beginTest ("Ranges::set() - basics");
{
Ranges ranges;
ranges.set ({ -3, 14 }, ops);
expectRange (ranges.get (0), { -3, 14 });
ranges.set ({ 7, 20 }, ops);
expectRange (ranges.get (0), { -3, 7 });
expectRange (ranges.get (1), { 7, 20 });
}
beginTest ("Ranges::set() - neighbouring ranges extents are modified");
{
Ranges ranges;
ranges.set ({ -3, 14 }, ops);
ranges.set ({ 19, 30 }, ops);
ranges.set ({ 10, 25 }, ops);
// size_t doesn't always map to an existing overload for String::operator<< on all platforms
expectEquals ((int64) ranges.size(), (int64) 3);
expectRange (ranges.get (0), { -3, 10 });
expectRange (ranges.get (1), { 10, 25 });
expectRange (ranges.get (2), { 25, 30 });
}
beginTest ("Ranges::set() - setting a range inside another one splits that range");
{
Ranges ranges;
ranges.set ({ -3, 14 }, ops);
expectEquals ((int64) ranges.size(), (int64) 1);
//==============================================================================
ranges.set ({ 3, 7 }, ops);
expectEquals ((int64) ranges.size(), (int64) 3);
expectRange (ranges.get (0), { -3, 3 });
expectRange (ranges.get (1), { 3, 7 });
expectRange (ranges.get (2), { 7, 14 });
}
beginTest ("Ranges::set() - old ranges falling within the bounds of a newly set are erased");
{
Ranges ranges;
ranges.set ({ 0, 5 }, ops);
ranges.set ({ 5, 10 }, ops);
ranges.set ({ 15, 20 }, ops);
ranges.set ({ 25, 30 }, ops);
ranges.set ({ 35, 50 }, ops);
expectEquals ((int64) ranges.size(), (int64) 5);
//==============================================================================
ranges.set ({ 4, 36 }, ops);
expectEquals ((int64) ranges.size(), (int64) 3);
expectRange (ranges.get (0), { 0, 4 });
expectRange (ranges.get (1), { 4, 36 });
expectRange (ranges.get (2), { 36, 50 });
}
beginTest ("Ranges::set() - setting an empty range should be a no-op");
{
Ranges ranges;
ops.clear();
ranges.set ({ 0, 0 }, ops);
expect (ranges.isEmpty());
expect (ops.empty());
}
beginTest ("Ranges::set() - setting a range inside another range");
{
Ranges ranges;
ranges.set ({ 0, 48 }, ops);
ranges.set ({ 48, 127 }, ops);
ranges.set ({ 49, 94 }, ops);
expectEquals ((int64) ranges.size(), (int64) 4, "");
expectRange (ranges.get (0), { 0, 48 });
expectRange (ranges.get (1), { 48, 49 });
expectRange (ranges.get (2), { 49, 94 });
expectRange (ranges.get (3), { 94, 127 });
}
beginTest ("Ranges::split()");
{
Ranges ranges;
ranges.set ({ 0, 48 }, ops);
ranges.set ({ 48, 127 }, ops);
ops.clear();
ranges.split (47, ops);
expectEquals ((int64) ops.size(), (int64) 1, "");
const auto op0 = std::get_if<Ranges::Ops::Split> (&ops[0]);
expect (op0 != nullptr);
if (op0 != nullptr)
expectEquals ((int) op0->index, 0, "The 0th element should be split");
expectEquals ((int64) ranges.size(), (int64) 3, "");
expectRange (ranges.get (0), { 0, 47 });
expectRange (ranges.get (1), { 47, 48 });
expectRange (ranges.get (2), { 48, 127 });
}
beginTest ("Ranges::split() - splitting has no effect when no range begins before and ends after the location");
{
Ranges ranges;
ranges.set ({ 0, 48 }, ops);
ranges.set ({ 48, 127 }, ops);
ops.clear();
ranges.split (48, ops);
expectEquals ((int64) ops.size(), (int64) 0, "");
expectEquals ((int64) ranges.size(), (int64) 2, "");
expectRange (ranges.get (0), { 0, 48 });
expectRange (ranges.get (1), { 48, 127 });
}
beginTest ("Ranges::insert() - basics");
{
Ranges ranges;
ranges.insert ({ -3, 14 }, ops);
expectRange (ranges.get (0), { -3, 14 });
ranges.insert ({ 7, 20 }, ops);
expectRange (ranges.get (0), { -3, 7 });
expectRange (ranges.get (1), { 7, 20 });
expectRange (ranges.get (2), { 20, 27 });
}
beginTest ("Ranges::insert() - inserting shifts all following ranges");
{
Ranges ranges;
ranges.insert ({ 10, 11 }, ops);
ranges.insert ({ 0, 1 }, ops);
expectRange (ranges.get (0), { 0, 1 });
expectRange (ranges.get (1), { 11, 12 });
}
beginTest ("Ranges::insert() - inserting an empty range should be a no-op");
{
Ranges ranges;
ops.clear();
ranges.insert ({ 0, 0 }, ops);
expect (ranges.isEmpty());
expect (ops.empty());
}
const auto getTestRanges = [&ops]
{
Ranges ranges;
ranges.set ({ 0, 48 }, ops);
ranges.set ({ 48, 49 }, ops);
ranges.set ({ 55, 94 }, ops);
ranges.set ({ 94, 127 }, ops);
return ranges;
};
beginTest ("Ranges::eraseFrom() - erasing beyond all ranges has no effect");
{
auto ranges = getTestRanges();
ranges.eraseFrom (ranges.get (ranges.size() - 1).getEnd() + 5, ops);
expectEquals ((int64) ranges.size(), (int64) 4, "");
expectRange (ranges.get (0), { 0, 48 });
expectRange (ranges.get (1), { 48, 49 });
expectRange (ranges.get (2), { 55, 94 });
expectRange (ranges.get (3), { 94, 127 });
}
beginTest ("Ranges::eraseFrom() - erasing modifies the range that encloses the starting index");
{
auto ranges = getTestRanges();
ranges.eraseFrom (122, ops);
expectEquals ((int64) ranges.size(), (int64) 4, "");
expectRange (ranges.get (0), { 0, 48 });
expectRange (ranges.get (1), { 48, 49 });
expectRange (ranges.get (2), { 55, 94 });
expectRange (ranges.get (3), { 94, 122 });
}
beginTest ("Ranges::eraseFrom() - ranges starting after the erased index are deleted entirely");
{
auto ranges = getTestRanges();
ranges.eraseFrom (60, ops);
expectEquals ((int64) ranges.size(), (int64) 3, "");
expectRange (ranges.get (0), { 0, 48 });
expectRange (ranges.get (1), { 48, 49 });
expectRange (ranges.get (2), { 55, 60 });
}
beginTest ("Ranges::eraseFrom() - erasing from a location outside any ranges will still drop subsequent ranges");
{
auto ranges = getTestRanges();
ranges.eraseFrom (51, ops);
expectEquals ((int64) ranges.size(), (int64) 2, "");
expectRange (ranges.get (0), { 0, 48 });
expectRange (ranges.get (1), { 48, 49 });
}
beginTest ("Ranges::erase() - erasing a zero length range has no effect");
{
auto ranges = getTestRanges();
ranges.erase ({ 30, 30 }, ops);
expectEquals ((int64) ranges.size(), (int64) 4, "");
expectRange (ranges.get (0), { 0, 48 });
expectRange (ranges.get (1), { 48, 49 });
expectRange (ranges.get (2), { 55, 94 });
expectRange (ranges.get (3), { 94, 127 });
}
beginTest ("Ranges::erase() - erasing inside a range splits that range");
{
auto ranges = getTestRanges();
ranges.erase ({ 30, 31 }, ops);
expectEquals ((int64) ranges.size(), (int64) 5, "");
expectRange (ranges.get (0), { 0, 30 });
expectRange (ranges.get (1), { 31, 48 });
expectRange (ranges.get (2), { 48, 49 });
expectRange (ranges.get (3), { 55, 94 });
expectRange (ranges.get (4), { 94, 127 });
}
beginTest ("Ranges::erase() - erasing a range that completely overlaps existing ranges erases those");
{
auto ranges = getTestRanges();
ranges.erase ({ 30, 70 }, ops);
expectEquals ((int64) ranges.size(), (int64) 3, "");
expectRange (ranges.get (0), { 0, 30 });
expectRange (ranges.get (1), { 70, 94 });
expectRange (ranges.get (2), { 94, 127 });
}
beginTest ("Ranges::erase() - erasing a range that no previous ranges covered has no effect");
{
auto ranges = getTestRanges();
ranges.erase ({ 51, 53 }, ops);
expectEquals ((int64) ranges.size(), (int64) 4, "");
expectRange (ranges.get (0), { 0, 48 });
expectRange (ranges.get (1), { 48, 49 });
expectRange (ranges.get (2), { 55, 94 });
expectRange (ranges.get (3), { 94, 127 });
}
beginTest ("Ranges::erase() - erasing over a range beyond all limits clears all ranges");
{
auto ranges = getTestRanges();
ranges.erase ({ -1000, 1000 }, ops);
expect (ranges.isEmpty());
}
beginTest ("Ranges::drop() - dropping a range shifts all following ranges downward");
{
auto ranges = getTestRanges();
ranges.drop ({ 48, 49 }, ops);
expectEquals ((int64) ranges.size(), (int64) 3, "");
expectRange (ranges.get (0), { 0, 48 });
expectRange (ranges.get (1), { 54, 93 });
expectRange (ranges.get (2), { 93, 126 });
}
beginTest ("Ranges::drop() - dropping a range shifts all following ranges downward even if no range covered the dropped range previously");
{
auto ranges = getTestRanges();
ranges.drop ({ 51, 53 }, ops);
expectEquals ((int64) ranges.size(), (int64) 4, "");
expectRange (ranges.get (0), { 0, 48 });
expectRange (ranges.get (1), { 48, 49 });
expectRange (ranges.get (2), { 53, 92 });
expectRange (ranges.get (3), { 92, 125 });
}
beginTest ("Ranges::drop() - dropping a range covering all other ranges empties the collection");
{
auto ranges = getTestRanges();
ranges.drop ({ -1000, 1000 }, ops);
expect (ranges.isEmpty());
}
beginTest ("Ranges::covers()");
{
Ranges ranges;
ranges.set ({ 0, 48 }, ops);
ranges.set ({ 48, 49 }, ops);
ranges.set ({ 55, 94 }, ops);
ranges.set ({ 94, 127 }, ops);
ranges.set ({ 127, 150 }, ops);
expect (ranges.covers ({ 0, 48 }));
expect (ranges.covers ({ 0, 20 }));
expect (ranges.covers ({ 10, 30 }));
expect (ranges.covers ({ 30, 48 }));
expect (ranges.covers ({ 30, 49 }));
expect (ranges.covers ({ 55, 150 }));
expect (ranges.covers ({ 60, 145 }));
expect (! ranges.covers ({ -1, 10 }));
expect (! ranges.covers ({ 1, 50 }));
expect (! ranges.covers ({ 50, 140 }));
expect (! ranges.covers ({ 149, 151 }));
expect (ranges.covers ({ 10, 10 }));
expect (! ranges.covers ({ 151, 151 }));
}
}
};
class RangedValuesTests : public UnitTest
{
public:
RangedValuesTests() : UnitTest ("RangedValues", UnitTestCategories::containers) {}
template <typename ItemType>
void expectRangedValuesItem (ItemType item, Range<int64> range, char value)
{
{
String failureMessage { "range " };
failureMessage << item.range << " did not equal expected range " << range;
expect (item.range == range, failureMessage);
}
{
String failureMessage { "value '" };
failureMessage << item.value << "' in range " << range << " did not equal expected value '" << value << "'";
expect (item.value == value, failureMessage);
}
}
void runTest() override
{
auto random = getRandom();
Ranges::Operations ops;
const auto createRangedValuesObject = [&]
{
RangedValues<char> rangedValues;
rangedValues.set ({ 0, 10 }, 'a', ops);
rangedValues.set ({ 11, 20 }, 'b', ops);
rangedValues.set ({ 23, 30 }, 'c', ops);
return rangedValues;
};
beginTest ("RangedValues::set() with distinct value overlapping other ranges");
{
auto rangedValues = createRangedValuesObject();
rangedValues.set ({ 5, 15 }, 'd', ops);
expect (! rangedValues.isEmpty());
expectRangedValuesItem (rangedValues.getItem (0), { 0, 5 }, 'a');
expectRangedValuesItem (rangedValues.getItem (1), { 5, 15 }, 'd');
expectRangedValuesItem (rangedValues.getItem (2), { 15, 20 }, 'b');
expectRangedValuesItem (rangedValues.getItem (3), { 23, 30 }, 'c');
rangedValues.set ({ 19, 24 }, 'e', ops);
expectRangedValuesItem (rangedValues.getItem (2), { 15, 19 }, 'b');
expectRangedValuesItem (rangedValues.getItem (3), { 19, 24 }, 'e');
expectRangedValuesItem (rangedValues.getItem (4), { 24, 30 }, 'c');
}
beginTest ("RangedValues::set() with distinct value in corner cases");
{
auto rangedValues = createRangedValuesObject();
rangedValues.set ({ -1, 0 }, 'd', ops);
expectRangedValuesItem (rangedValues.getItem (0), { -1, 0 }, 'd');
expectRangedValuesItem (rangedValues.getItem (1), { 0, 10 }, 'a');
}
beginTest ("RangedValues::set() with same value with merging disallowed");
{
auto rangedValues = createRangedValuesObject();
rangedValues.set ({ 5, 15 }, 'b', ops, MergeEqualItemsNo{});
expectRangedValuesItem (rangedValues.getItem (0), { 0, 5 }, 'a');
expectRangedValuesItem (rangedValues.getItem (1), { 5, 15 }, 'b');
expectRangedValuesItem (rangedValues.getItem (2), { 15, 20 }, 'b');
expectRangedValuesItem (rangedValues.getItem (3), { 23, 30 }, 'c');
}
beginTest ("RangedValues::set() with same value with merging allowed");
{
auto rangedValues = createRangedValuesObject();
rangedValues.set ({ 5, 15 }, 'b', ops, MergeEqualItemsYes{});
expectRangedValuesItem (rangedValues.getItem (0), { 0, 5 }, 'a');
expectRangedValuesItem (rangedValues.getItem (1), { 5, 20 }, 'b');
expectRangedValuesItem (rangedValues.getItem (2), { 23, 30 }, 'c');
}
beginTest ("RangedValues::set() - setting an empty Range should be a no-op");
{
RangedValues<char> rangedValues;
ops.clear();
rangedValues.set ({ 0, 0 }, 'a', ops);
expect (rangedValues.isEmpty());
expect (ops.empty());
}
beginTest ("RangedValues::set() - setting a range inside another range");
{
RangedValues<char> rangedValues;
rangedValues.set ({ 0, 48 }, 'a', ops);
rangedValues.set ({ 48, 127 }, 'b', ops);
rangedValues.set ({ 49, 94 }, 'c', ops);
expectEquals ((int64) rangedValues.size(), (int64) 4, "");
expectRangedValuesItem (rangedValues.getItem (0), { 0, 48 }, 'a');
expectRangedValuesItem (rangedValues.getItem (1), { 48, 49 }, 'b');
expectRangedValuesItem (rangedValues.getItem (2), { 49, 94 }, 'c');
expectRangedValuesItem (rangedValues.getItem (3), { 94, 127 }, 'b');
}
beginTest ("RangedValues::getIntersectionsWith()");
{
auto rangedValues = createRangedValuesObject();
{
const auto intersections = rangedValues.getIntersectionsWith ({ 5, 43 });
expectRangedValuesItem (intersections.getItem (0), { 5, 10 }, 'a');
expectRangedValuesItem (intersections.getItem (1), { 11, 20 }, 'b');
expectRangedValuesItem (intersections.getItem (2), { 23, 30 }, 'c');
}
{
const auto intersections = rangedValues.getIntersectionsWith ({ -10, 3 });
expectRangedValuesItem (intersections.getItem (0), { 0, 3 }, 'a');
}
}
beginTest ("RangedValues::insert() fuzzing - insert always increases the total covered range");
{
for (auto i = 0; i != 100; ++i)
{
auto rangedValuesNotMerged = createRangedValuesObject();
auto rangedValuesMerged = createRangedValuesObject();
const auto totalLengthBeforeInsert = getCumulativeRangeLengths (rangedValuesNotMerged);
const auto beginInsertionAt = (int64) random.nextInt (100) - 50;
const auto numElemsToInsert = (int64) random.nextInt (1000);
rangedValuesNotMerged.insert ({ Range<int64>::withStartAndLength (beginInsertionAt, numElemsToInsert) },
'a' + (char) random.nextInt (25),
ops,
MergeEqualItemsNo{});
expectEquals (getCumulativeRangeLengths (rangedValuesNotMerged) - totalLengthBeforeInsert, numElemsToInsert);
rangedValuesMerged.insert ({ Range<int64>::withStartAndLength (beginInsertionAt, numElemsToInsert) },
'a' + (char) random.nextInt (25),
ops,
MergeEqualItemsYes{});
expectEquals (getCumulativeRangeLengths (rangedValuesMerged) - totalLengthBeforeInsert, numElemsToInsert);
}
}
beginTest ("RangedValues::insert() with distinct value inside another range");
{
auto rangedValues = createRangedValuesObject();
expectEquals ((int64) rangedValues.size(), (int64) 3);
rangedValues.insert ({ 2, 4 }, 'd', ops);
expectEquals ((int64) rangedValues.size(), (int64) 5);
expectRangedValuesItem (rangedValues.getItem (0), { 0, 2 }, 'a');
expectRangedValuesItem (rangedValues.getItem (1), { 2, 4 }, 'd');
expectRangedValuesItem (rangedValues.getItem (2), { 4, 12 }, 'a');
expectRangedValuesItem (rangedValues.getItem (3), { 13, 22 }, 'b');
expectRangedValuesItem (rangedValues.getItem (4), { 25, 32 }, 'c');
}
beginTest ("RangedValues::insert() with same value inside another range");
{
{
auto rangedValues = createRangedValuesObject();
expectEquals ((int64) rangedValues.size(), (int64) 3);
rangedValues.insert ({ 2, 4 }, 'a', ops, MergeEqualItemsYes{});
expectEquals ((int64) rangedValues.size(), (int64) 3);
expectRangedValuesItem (rangedValues.getItem (0), { 0, 12 }, 'a');
expectRangedValuesItem (rangedValues.getItem (1), { 13, 22 }, 'b');
expectRangedValuesItem (rangedValues.getItem (2), { 25, 32 }, 'c');
}
{
auto rangedValues = createRangedValuesObject();
expectEquals ((int64) rangedValues.size(), (int64) 3);
rangedValues.insert ({ 2, 4 }, 'a', ops, MergeEqualItemsNo{});
expectEquals ((int64) rangedValues.size(), (int64) 5);
expectRangedValuesItem (rangedValues.getItem (0), { 0, 2 }, 'a');
expectRangedValuesItem (rangedValues.getItem (1), { 2, 4 }, 'a');
expectRangedValuesItem (rangedValues.getItem (2), { 4, 12 }, 'a');
expectRangedValuesItem (rangedValues.getItem (3), { 13, 22 }, 'b');
expectRangedValuesItem (rangedValues.getItem (4), { 25, 32 }, 'c');
}
}
beginTest ("RangedValues::insert() - inserting an empty Range should be a no-op");
{
{
RangedValues<char> emptyRangedValues;
ops.clear();
emptyRangedValues.insert ({ 0, 0 }, 'a', ops);
expect (emptyRangedValues.isEmpty());
expect (ops.empty());
}
{
RangedValues<char> rangedValues;
rangedValues.set ({ 0, 10 }, 'a', ops);
ops.clear();
rangedValues.insert ({ 0, 0 }, 'a', ops);
expect (ops.empty());
expectEquals ((int64) rangedValues.size(), (int64) 1);
expectRangedValuesItem (rangedValues.getItem (0), { 0, 10 }, 'a');
}
}
const auto createRangedValuesObjectForErase = [&]
{
RangedValues<char> rangedValues;
rangedValues.set ({ 0, 10 }, 'a', ops);
rangedValues.set ({ 11, 20 }, 'b', ops);
rangedValues.set ({ 23, 30 }, 'c', ops);
rangedValues.set ({ 35, 45 }, 'c', ops);
rangedValues.set ({ 45, 60 }, 'd', ops);
return rangedValues;
};
beginTest ("RangedValues::erase() - erase will not shift subsequent ranges downward");
{
auto rangedValues = createRangedValuesObjectForErase();
rangedValues.erase ({ 15, 16 }, ops);
expectRangedValuesItem (rangedValues.getItem (0), { 0, 10 }, 'a');
expectRangedValuesItem (rangedValues.getItem (1), { 11, 15 }, 'b');
expectRangedValuesItem (rangedValues.getItem (2), { 16, 20 }, 'b');
expectRangedValuesItem (rangedValues.getItem (3), { 23, 30 }, 'c');
expectRangedValuesItem (rangedValues.getItem (4), { 35, 45 }, 'c');
expectRangedValuesItem (rangedValues.getItem (5), { 45, 60 }, 'd');
}
beginTest ("RangedValues::eraseUpTo() - erasing before all ranges has no effect");
{
auto rangedValues = createRangedValuesObjectForErase();
rangedValues.eraseUpTo (rangedValues.getRanges().get (0).getStart(), ops);
expectRangedValuesItem (rangedValues.getItem (0), { 0, 10 }, 'a');
expectRangedValuesItem (rangedValues.getItem (1), { 11, 20 }, 'b');
expectRangedValuesItem (rangedValues.getItem (2), { 23, 30 }, 'c');
expectRangedValuesItem (rangedValues.getItem (3), { 35, 45 }, 'c');
expectRangedValuesItem (rangedValues.getItem (4), { 45, 60 }, 'd');
}
beginTest ("RangedValues::eraseUpTo() - erasing values up to, not including 15");
{
auto rangedValues = createRangedValuesObjectForErase();
rangedValues.eraseUpTo (15, ops);
expectRangedValuesItem (rangedValues.getItem (0), { 15, 20 }, 'b');
expectRangedValuesItem (rangedValues.getItem (1), { 23, 30 }, 'c');
expectRangedValuesItem (rangedValues.getItem (2), { 35, 45 }, 'c');
expectRangedValuesItem (rangedValues.getItem (3), { 45, 60 }, 'd');
}
beginTest ("RangedValues::eraseUpTo() - erasing up to the end of all ranges clears the container");
{
auto rangedValues = createRangedValuesObjectForErase();
const auto ranges = rangedValues.getRanges();
rangedValues.eraseUpTo (ranges.get (ranges.size() - 1).getEnd(), ops);
expect (rangedValues.isEmpty());
}
beginTest ("RangedValues::drop() - drop shifts ranges downward on the right side");
{
auto rangedValues = createRangedValuesObjectForErase();
rangedValues.drop ({ 15, 16 }, ops, MergeEqualItemsNo{});
expectRangedValuesItem (rangedValues.getItem (0), { 0, 10 }, 'a');
expectRangedValuesItem (rangedValues.getItem (1), { 11, 15 }, 'b');
expectRangedValuesItem (rangedValues.getItem (2), { 15, 19 }, 'b');
expectRangedValuesItem (rangedValues.getItem (3), { 22, 29 }, 'c');
expectRangedValuesItem (rangedValues.getItem (4), { 34, 44 }, 'c');
expectRangedValuesItem (rangedValues.getItem (5), { 44, 59 }, 'd');
}
beginTest ("RangedValues::drop() - drop can be used to merge equal values");
{
auto rangedValues = createRangedValuesObjectForErase();
rangedValues.drop ({ 15, 16 }, ops, MergeEqualItemsYes{});
expectRangedValuesItem (rangedValues.getItem (0), { 0, 10 }, 'a');
expectRangedValuesItem (rangedValues.getItem (1), { 11, 19 }, 'b');
expectRangedValuesItem (rangedValues.getItem (2), { 22, 29 }, 'c');
expectRangedValuesItem (rangedValues.getItem (3), { 34, 44 }, 'c');
expectRangedValuesItem (rangedValues.getItem (4), { 44, 59 }, 'd');
}
beginTest ("RangedValues::drop() - the merge happens at the seam caused by the drop and does not extend beyond");
{
auto rangedValues = createRangedValuesObjectForErase();
rangedValues.set ({ 20, 30 }, 'b', ops, MergeEqualItemsNo{});
rangedValues.drop ({ 15, 16 }, ops, MergeEqualItemsYes{});
expectRangedValuesItem (rangedValues.getItem (0), { 0, 10 }, 'a');
// These two items are not merged, even though they form a contiguous range, because
// they were disjoint before the drop and they don't touch each other at the drop
// seam of 15.
expectRangedValuesItem (rangedValues.getItem (1), { 11, 19 }, 'b');
expectRangedValuesItem (rangedValues.getItem (2), { 19, 29 }, 'b');
expectRangedValuesItem (rangedValues.getItem (3), { 34, 44 }, 'c');
expectRangedValuesItem (rangedValues.getItem (4), { 44, 59 }, 'd');
}
}
};
class IntersectingRangedValuesTests : public RangesTestsBase
{
public:
IntersectingRangedValuesTests() : RangesTestsBase ("IntersectingRangedValues", UnitTestCategories::containers) {}
void runTest() override
{
Ranges::Operations ops;
beginTest ("IntersectingRangedValuesTests - iterating over multiple RangedValues");
{
RangedValues<int> rv1;
rv1.set ({ 3, 8}, 1, ops);
rv1.set ({ 9, 16}, 2, ops);
rv1.set ({ 30, 40}, 3, ops);
RangedValues<int> rv2;
rv2.set ({ 0, 4}, 7, ops);
rv2.set ({ 4, 6}, 11, ops);
rv2.set ({ 6, 25}, 13, ops);
rv2.set ({ 27, 55}, 17, ops);
RangedValues<int> rv3;
rv3.set ({ -2, 10}, -1, ops);
rv3.set ({ 15, 19}, -2, ops);
rv3.set ({ 22, 36}, -3, ops);
int iteration = 0;
for (const auto [range, v1, v2, v3] : makeIntersectingRangedValues (&rv1, &rv2, &rv3))
{
if (iteration == 0)
{
expectRange (range, Range<int64> { 3, 4 });
expect (v1 == 1 && v2 == 7 && v3 == -1);
}
if (iteration == 1)
{
expectRange (range, Range<int64> { 4, 6 });
expect (v1 == 1 && v2 == 11 && v3 == -1);
}
if (iteration == 2)
{
expectRange (range, Range<int64> { 6, 8 });
expect (v1 == 1 && v2 == 13 && v3 == -1);
}
if (iteration == 3)
{
expectRange (range, Range<int64> { 9, 10 });
expect (v1 == 2 && v2 == 13 && v3 == -1);
}
if (iteration == 4)
{
expectRange (range, Range<int64> { 15, 16 });
expect (v1 == 2 && v2 == 13 && v3 == -2);
}
if (iteration == 5)
{
expectRange (range, Range<int64> { 30, 36 });
expect (v1 == 3 && v2 == 17 && v3 == -3);
}
++iteration;
}
expectEquals (iteration, 6);
}
}
};
static RangesTests rangesTests;
static RangedValuesTests rangedValuesTests;
static IntersectingRangedValuesTests intersectingRangedValuesTests;
#endif
} // namespace juce::detail
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,232 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce::detail
{
class ShapedText::Impl
{
public:
Impl (String textIn, Options optionsIn)
: options { std::move (optionsIn) },
text { std::move (textIn) }
{
}
void draw (const Graphics& g, AffineTransform transform) const
{
drawJustifiedText (justifiedText, g, transform);
}
float getHeight() const
{
return justifiedText.getHeight();
}
int64 getNumGlyphs() const
{
return simpleShapedText.getNumGlyphs();
}
const detail::RangedValues<LineMetrics>& getLineMetricsForGlyphRange() const
{
return justifiedText.getLineMetricsForGlyphRange();
}
const detail::Ranges& getLineTextRanges() const
{
return simpleShapedText.getLineTextRanges();
}
auto& getText() const
{
return text;
}
auto getTextRange (int64 glyphIndex) const
{
return simpleShapedText.getTextRange (glyphIndex);
}
auto isLtr (int64 glyphIndex) const
{
return simpleShapedText.isLtr (glyphIndex);
}
int64 getTextIndexForCaret (Point<float> p) const
{
const auto getGlyph = [&] (int64 i)
{
return simpleShapedText.getGlyphs()[(size_t) i];
};
if (getNumGlyphs() == 0)
return 0;
const auto glyphOnTheRight = justifiedText.getGlyphIndexToTheRightOf (p);
if (glyphOnTheRight >= getNumGlyphs())
{
const auto glyphOnTheLeft = glyphOnTheRight - 1;
const auto ltr = simpleShapedText.getGlyphLookup().find (getGlyph (glyphOnTheLeft).cluster)->value.ltr;
if (ltr)
return simpleShapedText.getTextIndexAfterGlyph (glyphOnTheLeft);
return simpleShapedText.getGlyphs()[(size_t) glyphOnTheLeft].cluster;
}
const auto ltr = simpleShapedText.getGlyphLookup().find (getGlyph (glyphOnTheRight).cluster)->value.ltr;
if (ltr)
return simpleShapedText.getGlyphs()[(size_t) glyphOnTheRight].cluster;
return simpleShapedText.getTextIndexAfterGlyph (glyphOnTheRight);
}
void getGlyphRanges (Range<int64> textRange, std::vector<Range<int64>>& outRanges) const
{
simpleShapedText.getGlyphRanges (textRange, outRanges);
}
RectangleList<float> getGlyphsBounds (Range<int64> glyphRange) const
{
return justifiedText.getGlyphsBounds (glyphRange);
}
auto getGlyphAnchor (int64 index) const
{
return justifiedText.getGlyphAnchor (index);
}
Span<const float> getMinimumRequiredWidthForLines() const
{
return justifiedText.getMinimumRequiredWidthForLines();
}
//==============================================================================
auto& getSimpleShapedText() const { return simpleShapedText; }
auto& getJustifiedText() const { return justifiedText; }
private:
ShapedTextOptions options;
String text;
SimpleShapedText simpleShapedText { &text, options };
JustifiedText justifiedText { &simpleShapedText, options };
};
ShapedText::ShapedText() : ShapedText ("", {})
{
}
ShapedText::ShapedText (String text) : ShapedText (std::move (text), {})
{
}
ShapedText::ShapedText (String text, Options options)
{
impl = std::make_shared<Impl> (std::move (text), std::move (options));
}
void ShapedText::draw (const Graphics& g, AffineTransform transform) const
{
impl->draw (g, transform);
}
float ShapedText::getHeight() const
{
return impl->getHeight();
}
int64 ShapedText::getNumGlyphs() const
{
return impl->getNumGlyphs();
}
const detail::RangedValues<LineMetrics>& ShapedText::getLineMetricsForGlyphRange() const
{
return impl->getLineMetricsForGlyphRange();
}
const detail::Ranges& ShapedText::getLineTextRanges() const
{
return impl->getLineTextRanges();
}
const String& ShapedText::getText() const
{
return impl->getText();
}
Range<int64> ShapedText::getTextRange (int64 glyphIndex) const
{
return impl->getTextRange (glyphIndex);
}
bool ShapedText::isLtr (int64 glyphIndex) const
{
return impl->isLtr (glyphIndex);
}
int64 ShapedText::getTextIndexForCaret (Point<float> p) const
{
return impl->getTextIndexForCaret (p);
}
void ShapedText::getGlyphRanges (Range<int64> textRange, std::vector<Range<int64>>& outRanges) const
{
return impl->getGlyphRanges (textRange, outRanges);
}
RectangleList<float> ShapedText::getGlyphsBounds (Range<int64> glyphRange) const
{
return impl->getGlyphsBounds (glyphRange);
}
GlyphAnchorResult ShapedText::getGlyphAnchor (int64 index) const
{
return impl->getGlyphAnchor (index);
}
Span<const float> ShapedText::getMinimumRequiredWidthForLines() const
{
return impl->getMinimumRequiredWidthForLines();
}
const JustifiedText& ShapedText::getJustifiedText() const { return impl->getJustifiedText(); }
const SimpleShapedText& ShapedText::getSimpleShapedText() const { return impl->getSimpleShapedText(); }
} // namespace juce::detail
@@ -0,0 +1,116 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce::detail
{
/* Class that can visually shape a Unicode string provided a list of Fonts corresponding to
sub-ranges of the string.
*/
class JUCE_API ShapedText
{
public:
using Options = ShapedTextOptions;
ShapedText();
explicit ShapedText (String text);
ShapedText (String text, Options options);
/* Returns the text which was used to construct this object. */
const String& getText() const;
Span<const ShapedGlyph> getGlyphs() const;
/* Returns the text's codepoint range, to which the glyph under the provided index belongs.
This range will have a length of at least one, and potentially more than one if ligatures
are enabled.
*/
Range<int64> getTextRange (int64 glyphIndex) const;
bool isLtr (int64 glyphIndex) const;
int64 getTextIndexForCaret (Point<float> p) const;
void getGlyphRanges (Range<int64> textRange, std::vector<Range<int64>>& outRanges) const;
RectangleList<float> getGlyphsBounds (Range<int64> glyphRange) const;
/* @see JustifiedText::getGlyphAnchor() */
GlyphAnchorResult getGlyphAnchor (int64 index) const;
/* Returns the widths for each line, that the glyphs would require to be rendered without being
truncated. This will or will not include the space required by trailing whitespaces in the
line based on the ShapedTextOptions::withTrailingWhitespacesShouldFit() value.
This value isn't affected by the Justification parameter, it just reports the amount of
width that would be required to avoid truncation.
*/
Span<const float> getMinimumRequiredWidthForLines() const;
/* @see JustifiedText::accessTogetherWith */
template <typename Callable, typename... RangedValues>
void accessTogetherWith (Callable&& callback, RangedValues&&... rangedValues) const
{
getJustifiedText().accessTogetherWith (std::forward<Callable> (callback),
std::forward<RangedValues> (rangedValues)...);
}
/* Draws the text. */
void draw (const Graphics& g, AffineTransform transform) const;
/* @see JustifiedText::getHeight
*/
float getHeight() const;
int64 getNumGlyphs() const;
const detail::RangedValues<LineMetrics>& getLineMetricsForGlyphRange() const;
const detail::Ranges& getLineTextRanges() const;
/* @internal */
const JustifiedText& getJustifiedText() const;
/* @internal */
const SimpleShapedText& getSimpleShapedText() const;
private:
class Impl;
std::shared_ptr<Impl> impl;
};
} // namespace juce::detail
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,335 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce::detail
{
/** Types of text direction. This may also be applied to characters. */
enum class TextDirection
{
ltr, // This text reads left to right.
rtl // This text reads right to left.
};
class ShapedTextOptions
{
private:
auto tie() const;
public:
bool operator== (const ShapedTextOptions& other) const;
bool operator!= (const ShapedTextOptions& other) const;
//==============================================================================
[[nodiscard]] ShapedTextOptions withJustification (Justification x) const
{
return withMember (*this, &ShapedTextOptions::justification, x);
}
/* This option will use soft wrapping for lines that are longer than the specified value,
and it will also align each line to this width, using the Justification provided in
withJustification.
The alignment width can be overriden using withAlignmentWidth, but currently we only need
to do this for the TextEditor.
*/
[[nodiscard]] ShapedTextOptions withWordWrapWidth (float x) const
{
return withMember (*this, &ShapedTextOptions::wordWrapWidth, x);
}
/* With this option each line will be aligned only if it's shorter or equal to the alignment
width. Otherwise, the line's x anchor will be 0.0f. This is in contrast to using
withWordWrapWidth only, which will modify the x anchor of RTL lines that are too long, to ensure
that it's the logical end of the text that falls outside the visible bounds.
The alignment width is also a distinct value from the value used for soft wrapping which is
specified using withWordWrapWidth.
This option is specifically meant to support an existing TextEditor behaviour, where text
can be aligned even when word wrapping is off. You probably don't need to use this function,
unless you want to reproduce the particular behaviour seen in the TextEditor, and should
only use withWordWrapWidth, if alignment is required.
With this option off, text is either not aligned, or aligned to the width specified using
withWordWrapWidth.
When this option is in use, it overrides the width specified in withWordWrapWidth for alignment
purposes, but not for line wrapping purposes.
It also accommodates the fact that the TextEditor has a scrolling feature and text never
becomes unreachable, even if the lines are longer than the viewport's width.
*/
[[nodiscard]] ShapedTextOptions withAlignmentWidth (float x) const
{
return withMember (*this, &ShapedTextOptions::alignmentWidth, x);
}
[[nodiscard]] ShapedTextOptions withHeight (float x) const
{
return withMember (*this, &ShapedTextOptions::height, x);
}
[[nodiscard]] ShapedTextOptions withFont (Font x) const
{
RangedValues<Font> fonts;
detail::Ranges::Operations ops;
fonts.set ({ 0, std::numeric_limits<int64>::max() }, x, ops);
return withMember (*this, &ShapedTextOptions::fontsForRange, std::move (fonts));
}
[[nodiscard]] ShapedTextOptions withFonts (const detail::RangedValues<Font>& x) const
{
return withMember (*this, &ShapedTextOptions::fontsForRange, x);
}
[[nodiscard]] ShapedTextOptions withFirstLineIndent (float x) const
{
return withMember (*this, &ShapedTextOptions::firstLineIndent, x);
}
/* This controls the space between lines using a proportional value, with a default of 1.0,
meaning single line spacing i.e. the descender of the current line + ascender of the next
line. This value is multiplied by the leading provided here.
*/
[[nodiscard]] ShapedTextOptions withLeading (float x) const
{
return withMember (*this, &ShapedTextOptions::leading, x);
}
/* This controls the space between lines using an additive absolute value, with a default of 0.0.
This value is added to the spacing between each two lines.
*/
[[nodiscard]] ShapedTextOptions withAdditiveLineSpacing (float x) const
{
return withMember (*this, &ShapedTextOptions::additiveLineSpacing, x);
}
[[nodiscard]] ShapedTextOptions withBaselineAtZero (bool x = true) const
{
return withMember (*this, &ShapedTextOptions::baselineAtZero, x);
}
[[nodiscard]] ShapedTextOptions withTrailingWhitespacesShouldFit (bool x = true) const
{
return withMember (*this, &ShapedTextOptions::trailingWhitespacesShouldFit, x);
}
[[nodiscard]] ShapedTextOptions withMaxNumLines (int64 x) const
{
return withMember (*this, &ShapedTextOptions::maxNumLines, x);
}
[[nodiscard]] ShapedTextOptions withEllipsis (String x = String::charToString ((juce_wchar) 0x2026)) const
{
return withMember (*this, &ShapedTextOptions::ellipsis, std::move (x));
}
/* Draw each line in its entirety even if it goes beyond wordWrapWidth. This means that even
if configured, an ellipsis will never be inserted.
This is used by the TextEditor where the Viewport guarantees that all text will be viewable
even beyond the word wrap width.
*/
[[nodiscard]] ShapedTextOptions withDrawLinesInFull (bool x = true) const
{
return withMember (*this, &ShapedTextOptions::drawLinesInFull, std::move (x));
}
[[nodiscard]] ShapedTextOptions withReadingDirection (std::optional<TextDirection> x) const
{
return withMember (*this, &ShapedTextOptions::readingDir, x);
}
[[nodiscard]] ShapedTextOptions withAllowBreakingInsideWord (bool x = true) const
{
return withMember (*this, &ShapedTextOptions::allowBreakingInsideWord, x);
}
const auto& getReadingDirection() const { return readingDir; }
const auto& getJustification() const { return justification; }
const auto& getWordWrapWidth() const { return wordWrapWidth; }
const auto& getAlignmentWidth() const { return alignmentWidth; }
const auto& getHeight() const { return height; }
const auto& getFontsForRange() const { return fontsForRange; }
const auto& getFirstLineIndent() const { return firstLineIndent; }
const auto& getLeading() const { return leading; }
const auto& getAdditiveLineSpacing() const { return additiveLineSpacing; }
const auto& isBaselineAtZero() const { return baselineAtZero; }
const auto& getTrailingWhitespacesShouldFit() const { return trailingWhitespacesShouldFit; }
const auto& getMaxNumLines() const { return maxNumLines; }
const auto& getEllipsis() const { return ellipsis; }
const auto& getDrawLinesInFull() const { return drawLinesInFull; }
const auto& getAllowBreakingInsideWord() const { return allowBreakingInsideWord; }
private:
Justification justification { Justification::topLeft };
std::optional<TextDirection> readingDir;
std::optional<float> wordWrapWidth;
std::optional<float> alignmentWidth;
std::optional<float> height;
detail::RangedValues<Font> fontsForRange = std::invoke ([&]
{
detail::RangedValues<Font> result;
detail::Ranges::Operations ops;
result.set ({ 0, std::numeric_limits<int64>::max() }, FontOptions { 15.0f }, ops);
return result;
});
float firstLineIndent = 0.0f;
float leading = 1.0f;
float additiveLineSpacing = 0.0f;
bool baselineAtZero = false;
bool allowBreakingInsideWord = false;
bool trailingWhitespacesShouldFit = true;
bool drawLinesInFull = false;
int64 maxNumLines = std::numeric_limits<int64>::max();
String ellipsis;
};
struct ShapedGlyph
{
ShapedGlyph (uint32_t glyphIdIn,
int64 clusterIn,
bool unsafeToBreakIn,
bool whitespaceIn,
bool newlineIn,
int8_t distanceFromLigatureIn,
Point<float> advanceIn,
Point<float> offsetIn)
: advance (advanceIn),
offset (offsetIn),
cluster (clusterIn),
glyphId (glyphIdIn),
unsafeToBreak (unsafeToBreakIn),
whitespace (whitespaceIn),
newline (newlineIn),
distanceFromLigature (distanceFromLigatureIn) {}
bool isUnsafeToBreak() const { return unsafeToBreak; }
bool isWhitespace() const { return whitespace; }
bool isNewline() const { return newline; }
bool isNonLigature() const { return distanceFromLigature == 0; }
bool isLigature() const { return distanceFromLigature < 0; }
bool isPlaceholderForLigature() const { return distanceFromLigature > 0; }
int8_t getDistanceFromLigature() const { return distanceFromLigature; }
int8_t getNumTrailingLigaturePlaceholders() const { return (int8_t) -distanceFromLigature; }
Point<float> advance;
Point<float> offset;
int64 cluster;
uint32_t glyphId;
private:
// These are effectively bools, pack into a single int once we have more than four flags.
int8_t unsafeToBreak;
int8_t whitespace;
int8_t newline;
int8_t distanceFromLigature;
};
struct GlyphLookupEntry
{
Range<int64> glyphRange;
bool ltr = true;
};
class SimpleShapedText
{
public:
/* Shapes and lays out the first contiguous sequence of ranges specified in the fonts
parameter.
*/
SimpleShapedText (const String* data,
const ShapedTextOptions& options);
const auto& getLineNumbersForGlyphRanges() const { return lineNumbersForGlyphRanges; }
const auto& getLineTextRanges() const { return lineTextRanges; }
const auto& getResolvedFonts() const { return resolvedFonts; }
Range<int64> getTextRange (int64 glyphIndex) const;
/* Returns true if the specified glyph is inside to an LTR run.
*/
bool isLtr (int64 glyphIndex) const;
/* This function may fail to return an out range, even if the provided textRange falls inside
the string range used for the creation of the ShapedText object.
This is because the shaping process could fail due to insufficient glyph resolution to the
point, where it will produce zero glyphs for the provided string.
*/
void getGlyphRanges (Range<int64> textRange, std::vector<Range<int64>>& outRanges) const;
/* Returns the input codepoint index that follows the glyph in a logical sense. So for LTR text
this is the cluster number of the glyph to the right. For RTL text it's the one on the left.
If there is no subsequent glyph, the returned number is the first Unicode codepoint index
that isn't covered by the cluster to which the selected glyph belongs, so for the glyph 'o'
in "hello" this would be 5, given there are no ligatures in use.
*/
int64 getTextIndexAfterGlyph (int64 glyphIndex) const;
int64 getNumLines() const { return (int64) lineNumbersForGlyphRanges.getRanges().size(); }
int64 getNumGlyphs() const { return (int64) glyphsInVisualOrder.size(); }
juce_wchar getCodepoint (int64 glyphIndex) const;
Span<const ShapedGlyph> getGlyphs (Range<int64> glyphRange) const;
Span<const ShapedGlyph> getGlyphs() const;
const auto& getGlyphLookup() const { return glyphLookup; }
private:
void shape (const String& data,
const ShapedTextOptions& options);
const String& string;
std::vector<ShapedGlyph> glyphsInVisualOrder;
detail::RangedValues<int64> lineNumbersForGlyphRanges;
detail::Ranges lineTextRanges;
detail::RangedValues<Font> resolvedFonts;
detail::RangedValues<GlyphLookupEntry> glyphLookup;
JUCE_LEAK_DETECTOR (SimpleShapedText)
};
} // namespace juce::detail
@@ -0,0 +1,287 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce::detail
{
GradientCircle GradientCircle::transformedBy (const AffineTransform& t) const
{
// Necessary condition for maintaining a circular shape
jassert (exactlyEqual (t.mat00, t.mat11));
GradientCircle result;
result.c = c.transformedBy (t);
const auto scaleFactor = std::sqrt (std::abs (t.getDeterminant()));
result.r = r * scaleFactor;
return result;
}
//==============================================================================
GradientCircle RadialGradientView::getEndCircle() const
{
return GradientCircle { isLegacy() ? gradient.point1 : gradient.point2,
isLegacy() ? gradient.point1.getDistanceFrom (gradient.point2)
: gradient.endRadius };
}
GradientCircle RadialGradientView::getStartCircle() const
{
return GradientCircle { gradient.point1, gradient.startRadius };
}
bool RadialGradientView::isLegacy() const noexcept
{
return gradient.endRadius < 0.0f;
}
//==============================================================================
std::optional<TwoPointConicalGradient> TwoPointConicalGradient::create (const ColourGradient& gradient)
{
jassert (gradient.isRadial);
RadialGradientView rg { &gradient };
const auto s = rg.getStartCircle();
const auto e = rg.getEndCircle();
if (! isConicalGradientApplicable (s, e))
return std::nullopt;
return TwoPointConicalGradient { s, e };
}
TwoPointConicalGradient::TwoPointConicalGradient (GradientCircle startCircle, GradientCircle endCircle)
: swapped { approximatelyEqual (endCircle.r, 0.0f) },
c0 { swapped ? endCircle : startCircle },
c1 { swapped ? startCircle : endCircle }
{
jassert (! approximatelyEqual (c0.r, c1.r, inputTolerance));
f = c0.r / (c0.r - c1.r);
const auto focalPoint = (1.0f - f) * c0.c + f * c1.c;
const auto c1FocalSegment = c1.c - focalPoint;
// We need a transform that moves the focal point to (0, 0) and c1 to (1, 0), and scales
// uniformly on the two axes.
const auto angleWithAxisX = std::atan2 (c1FocalSegment.y, c1FocalSegment.x);
regularisationTransform = AffineTransform::translation (-focalPoint.x,
-focalPoint.y).rotated (-angleWithAxisX);
const auto distToFocalPoint = c1FocalSegment.getDistanceFromOrigin();
// Gradients where the start and end circles are concentric are dispatched to the old gradient
jassert (! approximatelyEqual (distToFocalPoint, 0.0f, inputTolerance));
regularisationTransform = regularisationTransform.scaled (1.0f / distToFocalPoint);
// The math only works if the circles aren't transformed into ellipses
jassert (exactlyEqual (regularisationTransform.mat00, regularisationTransform.mat11));
c0 = c0.transformedBy (regularisationTransform);
c1 = c1.transformedBy (regularisationTransform);
f = c0.r / (c0.r - c1.r);
}
std::optional<float> TwoPointConicalGradient::calculateWeight (Point<float> p) const
{
p = p.transformedBy (regularisationTransform);
// Geometric meaning: the focus point sits on r1's circumference. The start end and end
// circles are touching.
//
// As r1 approaches 1.0f the accuracy of the solutions visibly deteriorates. We want to
// switch over to the more stable formula, that assumes r = 1, as soon as possible.
// At the same time we want the centre positioning error caused by this switch to be << 1px.
const auto closeToSingular = approximatelyEqual (c1.r, 1.0f, regularisationTolerance);
static constexpr auto squared = [] (float x) noexcept { return x * x; };
const auto x_prime = std::invoke (
[&]
{
if (closeToSingular)
return p.x / 2.0f;
return c1.r / (squared (c1.r) - 1.0f) * p.x;
});
const auto y_prime = std::invoke (
[&]
{
if (closeToSingular)
return p.y / 2.0f;
return std::sqrt (std::abs (squared (c1.r) - 1.0f)) / (squared (c1.r) - 1.0f) * p.y;
});
const auto x_hat = std::abs (1.0f - f) * x_prime;
const auto y_hat = std::abs (1.0f - f) * y_prime;
bool invalid = false;
const auto x_hat_t = std::invoke (
[&]
{
if (closeToSingular)
return (squared (x_hat) + squared (y_hat)) / x_hat;
if (c1.r < 1.0f)
{
// Geometric meaning: the start circle is outside the end circle, and we're
// looking for a solution that's outside the cone defined by them.
if (squared (x_hat) - squared (y_hat) < 0.0f)
{
invalid = true;
return 0.0f;
};
if (swapped || (1.0f - f) < 0.0f)
return -std::sqrt (squared (x_hat) - squared (y_hat)) - x_hat / c1.r;
return std::sqrt (squared (x_hat) - squared (y_hat)) - x_hat / c1.r;
}
// c1.r > 1.0f
return std::sqrt (squared (x_hat) + squared (y_hat)) - x_hat / c1.r;
});
if (invalid)
return std::nullopt;
if (x_hat_t < 0.0f)
return std::nullopt;
constexpr auto signum = [] (float v) { return (v > 0.0f) ? 1.0f : ((v < 0.0f) ? -1.0f : 0.0f); };
const auto t = f + signum (1.0f - f) * x_hat_t;
if (swapped)
return 1.0f - t;
return t;
}
bool TwoPointConicalGradient::isConicalGradientApplicable (const GradientCircle& s,
const GradientCircle& e)
{
if (approximatelyEqual (s.c.getDistanceFrom (e.c), 0.0f, inputTolerance))
return false;
if (approximatelyEqual (s.r, e.r, inputTolerance))
return false;
return true;
}
//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS
struct TwoPointConicalGradientTest final : public UnitTest
{
TwoPointConicalGradientTest() : UnitTest ("TwoPointConicalGradientTest", UnitTestCategories::graphics)
{
}
static constexpr auto magnitude = 200.0f;
static constexpr auto safetyFactor = 1.1f;
// TwoPointConicalGradient::regularisationTolerance is used by the
// TwoPointConicalGradient class in relation to the internal, normalised space,
// where the end circle's distance from the focal point is 1.0f.
inline static const auto tolerance = TwoPointConicalGradient::regularisationTolerance.getAbsolute()
* magnitude
* safetyFactor;
static Point<float> makeRandomPoint (Random& random)
{
return { -magnitude / 2.0f + random.nextFloat() * magnitude,
-magnitude / 2.0f + random.nextFloat() * magnitude };
}
void runTest() override
{
Random random = getRandom();
beginTest ("Start circle lies completely inside the end circle");
{
for (int i = 0; i < 1000; ++i)
{
GradientCircle end { makeRandomPoint (random),
std::max (3.0f * tolerance, random.nextFloat() * (magnitude / 2.0f)) };
const auto startDistanceFromEnd = tolerance + std::max (end.r - 2.0f * tolerance, 0.0f) * random.nextFloat();
const auto startRadius = (end.r - startDistanceFromEnd - tolerance) * random.nextFloat();
const auto startAngle = MathConstants<float>::twoPi * random.nextFloat();
const auto startCentre = Point<float> { end.c.x + std::cos (startAngle) * startDistanceFromEnd,
end.c.y + std::sin (startAngle) * startDistanceFromEnd };
GradientCircle start { startCentre, startRadius };
ColourGradient cg { Colours::red, start.c.x, start.c.y, Colours::blue, end.c.x, end.c.y, true };
cg.startRadius = start.r;
cg.endRadius = end.r;
const auto gradient = TwoPointConicalGradient::create (cg);
expect (gradient.has_value(),
"TwoPointConicalGradient should be appropriate for safely constructed arguments");
for (int j = 0; j < 100; ++j)
{
const auto p = makeRandomPoint (random);
const auto t = gradient->calculateWeight (p);
expect (t.has_value(),
"TwoPointConicalGradient with a start circle completely inside the end circle "
"should be able to calculate a weight for any point");
if (t.has_value())
{
const auto f = *t;
const auto pointToCenter = p.getDistanceFrom ((1.0f - f) * start.c + f * end.c);
const auto solutionRadius = std::abs ((1.0f - f) * start.r + f * end.r);
expect (approximatelyEqual (pointToCenter, solutionRadius, relativeTolerance (0.002f)),
"The solution should specify a circle that passes through the rendered pixel");
}
}
}
}
}
};
static TwoPointConicalGradientTest twoPointConicalGradientTest;
#endif
} // namespace juce::detail
@@ -0,0 +1,150 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce::detail
{
/* The two-point conical gradient is defined by two circles. */
struct GradientCircle
{
Point<float> c;
float r{};
GradientCircle transformedBy (const AffineTransform& t) const;
};
/* Helper class to correctly interpret the parameters of a radial gradient. */
struct RadialGradientView
{
RadialGradientView (const ColourGradient* gradientIn)
: gradient (*gradientIn)
{
jassert (gradientIn != nullptr);
jassert (gradient.isRadial);
}
/* The end circle. This defines the outline of the gradient.
This corresponds to the 'cx', 'cy' and 'r' SVG parameters.
*/
GradientCircle getEndCircle() const;
/* The start/focus circle.
This corresponds to the 'fx', 'fy' and 'fr' SVG parameters.
*/
GradientCircle getStartCircle() const;
private:
bool isLegacy() const noexcept;
const ColourGradient& gradient;
};
struct SpreadMethods
{
SpreadMethods() = delete;
static constexpr float pad (float t) noexcept
{
return std::clamp (t, 0.0f, 1.0f);
}
static float reflect (float t) noexcept
{
float integral{};
const auto fractional = std::modf (std::max (0.0f, t), &integral);
return (((int) integral) % 2 == 0) ? fractional : (1.0f - fractional);
}
static float repeat (float t) noexcept
{
float integral{};
return std::modf (std::max (0.0f, t), &integral);
}
static auto* getFunction (ColourGradient::SpreadMethod method) noexcept
{
switch (method)
{
case ColourGradient::SpreadMethod::pad: return &pad;
case ColourGradient::SpreadMethod::reflect: return &reflect;
case ColourGradient::SpreadMethod::repeat: return &repeat;
}
jassertfalse;
return &pad;
}
};
/* Helper class for implementing https://skia.org/docs/dev/design/conical/
Variable naming follows the notations used in the article whenever makes sense.
---
https://www.w3.org/TR/2015/WD-SVG2-20150915/pservers.html#RadialGradients
*/
class TwoPointConicalGradient
{
public:
static inline const auto regularisationTolerance = absoluteTolerance (0.001f);
static inline const auto inputTolerance = relativeTolerance (0.001f);
/* Returns an object if this class can compute the provided gradient object.
Returns std::nullopt, if the provided parameters would be a degenerate case for the
two-point conical equations.
*/
static std::optional<TwoPointConicalGradient> create (const ColourGradient& gradient);
/* Returns std::nullopt if the point is outside the calculable range.
This happens if the start circle touches, or falls outside the end circle, and the point is
outside the cone.
*/
std::optional<float> calculateWeight (Point<float> p) const;
private:
TwoPointConicalGradient (GradientCircle startCircle, GradientCircle endCircle);
static bool isConicalGradientApplicable (const GradientCircle& s, const GradientCircle& e);
bool swapped = false;
GradientCircle c0, c1;
float f {};
AffineTransform regularisationTransform;
};
} // namespace juce::detail
@@ -0,0 +1,45 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce::detail
{
struct UnicodeHelpers
{
UnicodeHelpers() = delete;
static std::vector<int> getLineBreaks (const String& data);
};
} // namespace juce::detail
@@ -0,0 +1,172 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
Drawable::Drawable (const Drawable& other)
: transform (other.transform),
clipPath (other.clipPath != nullptr ? other.clipPath->createCopy() : nullptr),
name (other.name),
visible (other.visible)
{
}
void Drawable::applyDrawableClipPath (Graphics& g) const
{
if (auto* drawable = clipPath.get())
{
auto path = drawable->getOutlineAsPath();
if (! path.isEmpty())
g.getInternalContext().clipToPath (path, {});
}
}
//==============================================================================
void Drawable::draw (Graphics& g, float opacity, const AffineTransform& drawTransform) const
{
Graphics::ScopedSaveState ss (g);
g.addTransform (getTransform().followedBy (drawTransform));
applyDrawableClipPath (g);
if (! g.isClipEmpty())
{
if (opacity < 1.0f)
{
g.beginTransparencyLayer (opacity);
paint (g);
g.endTransparencyLayer();
}
else
{
paint (g);
}
}
}
void Drawable::drawAt (Graphics& g, float x, float y, float opacity) const
{
draw (g, opacity, AffineTransform::translation (x, y));
}
void Drawable::drawWithin (Graphics& g, Rectangle<float> destArea,
RectanglePlacement placement, float opacity) const
{
draw (g, opacity, placement.getTransformToFit (getDrawableBounds(), destArea));
}
//==============================================================================
void Drawable::setClipPath (std::unique_ptr<Drawable> clipPathIn)
{
clipPath = std::move (clipPathIn);
}
//==============================================================================
bool Drawable::replaceColour (Colour, Colour)
{
return false;
}
void Drawable::setDrawableTransform (const AffineTransform& newTransform)
{
transform = newTransform;
}
void Drawable::setDrawableTransformToFit (const Rectangle<float>& area, RectanglePlacement placement)
{
if (! area.isEmpty())
setDrawableTransform (placement.getTransformToFit (getDrawableBoundsUntransformed(), area));
}
AffineTransform Drawable::getDrawableTransform() const
{
return transform;
}
AffineTransform Drawable::getTransform() const
{
return transform;
}
//==============================================================================
std::unique_ptr<Drawable> Drawable::createFromImageData (const void* data, const size_t numBytes)
{
auto image = ImageFileFormat::loadFrom (data, numBytes);
if (image.isValid())
return std::make_unique<DrawableImage> (image);
if (const auto s = String::createStringFromData (data, (int) numBytes); s.contains ("<svg"))
return Drawable::createFromSVGString (s);
return {};
}
std::unique_ptr<Drawable> Drawable::createFromImageDataStream (InputStream& dataSource)
{
MemoryOutputStream mo;
mo << dataSource;
return createFromImageData (mo.getData(), mo.getDataSize());
}
std::unique_ptr<Drawable> Drawable::createFromImageFile (const File& file)
{
FileInputStream fin (file);
if (fin.openedOk())
return createFromImageDataStream (fin);
return {};
}
Rectangle<float> Drawable::getDrawableBounds() const
{
return getDrawableBoundsUntransformed().transformedBy (getDrawableTransform());
}
Rectangle<float> Drawable::getContentBounds() const
{
return getContentBoundsUntransformed().transformedBy (getDrawableTransform());
}
Rectangle<float> Drawable::getContentBoundsUntransformed() const
{
return getDrawableBoundsUntransformed();
}
} // namespace juce
@@ -0,0 +1,329 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
class DrawableComposite;
//==============================================================================
/**
The base class for objects which can draw themselves, e.g. polygons, images, etc.
@see DrawableComposite, DrawableImage, DrawablePath, DrawableText
@tags{GUI}
*/
class JUCE_API Drawable
{
public:
/** @internal */
class JUCE_API Listener
{
public:
virtual ~Listener() = default;
virtual void drawableBoundsChanged (Drawable*) = 0;
};
/** Constructor. */
Drawable() = default;
/** Copy constructor. */
Drawable (const Drawable& other);
/** Destructor. */
virtual ~Drawable() = default;
//==============================================================================
/** Creates a deep copy of this Drawable object.
Use this to create a new copy of this and any sub-objects in the tree.
*/
virtual std::unique_ptr<Drawable> createCopy() const = 0;
/** Creates a path that describes the outline of this drawable. */
virtual Path getOutlineAsPath() const = 0;
//==============================================================================
/** Renders this Drawable object.
@see drawWithin
*/
void draw (Graphics& g, float opacity,
const AffineTransform& transform = AffineTransform()) const;
/** Renders the Drawable at a given offset within the Graphics context.
The coordinates passed-in are used to translate the object relative to its own
origin before drawing it - this is basically a quick way of saying:
@code
draw (g, AffineTransform::translation (x, y)).
@endcode
Note that the preferred way to render a drawable in future is by using it
as a component and adding it to a parent, so you might want to consider that
before using this method.
*/
void drawAt (Graphics& g, float x, float y, float opacity) const;
/** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
changing its aspect-ratio.
The object can placed arbitrarily within the rectangle based on a Justification type,
and can either be made as big as possible, or just reduced to fit.
Note that the preferred way to render a drawable in future is by using it
as a component and adding it to a parent, so you might want to consider that
before using this method.
@param g the graphics context to render onto
@param destArea the target rectangle to fit the drawable into
@param placement defines the alignment and rescaling to use to fit
this object within the target rectangle.
@param opacity the opacity to use, in the range 0 to 1.0
*/
void drawWithin (Graphics& g,
Rectangle<float> destArea,
RectanglePlacement placement,
float opacity) const;
//==============================================================================
/** Sets a the clipping region of this drawable using another drawable.
The drawable passed in will be deleted when no longer needed.
*/
void setClipPath (std::unique_ptr<Drawable> drawableClipPath);
/** Tests whether a given point is inside the Drawable. */
virtual bool hitTest (Point<float>) const = 0;
//==============================================================================
/** Tries to turn some kind of image file into a drawable.
The data could be an image that the ImageFileFormat class understands, or it
could be SVG.
*/
static std::unique_ptr<Drawable> createFromImageData (const void* data, size_t numBytes);
/** Tries to turn a stream containing some kind of image data into a drawable.
The data could be an image that the ImageFileFormat class understands, or it
could be SVG.
*/
static std::unique_ptr<Drawable> createFromImageDataStream (InputStream& dataSource);
/** Tries to turn a file containing some kind of image data into a drawable.
The data could be an image that the ImageFileFormat class understands, or it
could be SVG.
*/
static std::unique_ptr<Drawable> createFromImageFile (const File& file);
/** Attempts to parse an SVG (Scalable Vector Graphics) document from a file,
and to turn this into a Drawable tree.
If something goes wrong while parsing, it may return nullptr.
SVG is a pretty large and complex spec, and this doesn't aim to be a full
implementation, but it can return the basic vector objects.
Any references to references to external image files will be relative to
the parent directory of the file passed.
*/
static std::unique_ptr<Drawable> createFromSVGFile (const File& svgFile);
/** Attempts to parse an SVG (Scalable Vector Graphics) document from a string,
and to turn this into a Drawable tree.
*/
static std::unique_ptr<DrawableComposite> createFromSVGString (const String& svgString);
/** Parses an SVG path string and returns it. */
static Path parseSVGPath (const String& svgPath);
//==============================================================================
/** Returns the area that this drawable covers. These bounds are affected by the transform
passed to setDrawableTransform(). To get the original, untransformed bounds use
getDrawableBoundsUntransformed().
*/
Rectangle<float> getDrawableBounds() const;
/** Returns the area that this drawable covers in its original coordinate system.
These bounds are not affected by setDrawableTransform().
@see getDrawableBounds
*/
virtual Rectangle<float> getDrawableBoundsUntransformed() const = 0;
/** Returns the bounds that this drawable is intended to occupy. These bounds are affected by
the transform passed to setDrawableTransform().
A DrawableComposite will return the value of getContentArea(), while the base implementation
will return the value of getDrawableBounds().
Consequently, a Drawable parsed from an SVG file will return the SVG viewBox from this
function.
*/
Rectangle<float> getContentBounds() const;
/** Returns the area that this drawable is intended to occupy in its original coordinate
system. These bounds are not affected by setDrawableTransform().
A DrawableComposite will return the value of getContentArea(), while the base implementation
will return the value of getDrawableBounds().
Consequently, a Drawable parsed from an SVG file will return the SVG viewBox from this
function.
@see getContentBounds
*/
virtual Rectangle<float> getContentBoundsUntransformed() const;
/** Returns the width of the drawable bounds rounded up to the nearest integer.
@see getDrawableBounds
*/
int getWidth() const
{
return getDrawableBounds().toNearestInt().getWidth();
}
/** Returns the height of the drawable bounds rounded up to the nearest integer.
@see getDrawableBounds
*/
int getHeight() const
{
return getDrawableBounds().toNearestInt().getHeight();
}
/** Recursively replaces a colour that might be used for filling or stroking.
return true if any instances of this colour were found.
*/
virtual bool replaceColour (Colour originalColour, Colour replacementColour);
/** Sets a transformation that applies to the same coordinate system in which the rest of the
draw calls are made. You almost certainly want to call this function when working with
Drawables as opposed to Component::setTransform().
The reason for this is that the origin of a Drawable is not the same as the point returned
by Component::getPosition() but has an additional offset internal to the Drawable class.
Using setDrawableTransform() will take this internal offset into account when applying the
transform to the Component base.
You can only use Drawable::setDrawableTransform() or Component::setTransform() for a given
object. Using both will lead to unpredictable behaviour.
*/
void setDrawableTransform (const AffineTransform& transform);
/** Calls setDrawableTransform() with a transform that will position this Drawable within the
specified area in the untransformed coordinate system of the Drawable.
*/
void setDrawableTransformToFit (const Rectangle<float>& area, RectanglePlacement placement);
/** Returns the transform that is currently being applied to this drawable.
@see setTransform
*/
AffineTransform getDrawableTransform() const;
/** Returns the name of this Drawable object.
The SVG parser attempts to set this value to the id attribute of the corresponding SVG
element. However, since it's possible to reference and draw a single SVG element multiple
times, this value is not guaranteed to be unique.
@see setName
*/
const String& getName() const
{
return name;
}
/** Sets the name of this drawable object.
@see getName
*/
void setName (const String& newName)
{
name = newName;
}
/** Adds a listener. */
void addListener (Listener* newListener)
{
listeners.add (newListener);
}
/** Removes a listener. */
void removeListener (Listener* listenerToRemove)
{
listeners.remove (listenerToRemove);
}
/** @internal */
virtual bool isImage() const { return false; }
/** @internal */
virtual std::optional<String> getContainedText() const { return std::nullopt; }
/** @internal */
virtual bool requiresBlendBuffer() const { return false; }
protected:
//==============================================================================
virtual void paint (Graphics& g) const = 0;
// Overridden only by DrawableText to support setBoundingBox(). No easy workaround.
virtual AffineTransform getTransform() const;
void callListeners()
{
listeners.call (&Listener::drawableBoundsChanged, this);
}
private:
void applyDrawableClipPath (Graphics&) const;
AffineTransform transform;
std::unique_ptr<Drawable> clipPath;
String name;
bool visible = true;
ListenerList<Listener> listeners;
JUCE_LEAK_DETECTOR (Drawable)
};
} // namespace juce
@@ -0,0 +1,189 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
DrawableComposite::DrawableComposite (const DrawableComposite& other)
: Drawable (other),
contentArea (other.contentArea),
bounds (other.bounds),
blendMode (other.blendMode),
luminanceMask (other.luminanceMask),
opacity (other.opacity)
{
for (const auto& child : other.children)
children.push_back (child->createCopy());
}
std::unique_ptr<Drawable> DrawableComposite::createCopy() const
{
return std::make_unique<DrawableComposite> (*this);
}
//==============================================================================
Rectangle<float> DrawableComposite::getDrawableBoundsUntransformed() const
{
Rectangle<float> r;
for (const auto& child : children)
r = r.getUnion (child->getDrawableBounds());
return r;
}
Rectangle<float> DrawableComposite::getContentBoundsUntransformed() const
{
return contentArea;
}
void DrawableComposite::setContentArea (Rectangle<float> newArea)
{
contentArea = newArea;
}
void DrawableComposite::setBoundingBox (Rectangle<float> newBounds)
{
setBoundingBox (Parallelogram<float> (newBounds));
}
void DrawableComposite::setBoundingBox (Parallelogram<float> newBounds)
{
if (bounds != newBounds)
{
bounds = newBounds;
auto t = AffineTransform::fromTargetPoints (contentArea.getTopLeft(),
bounds.topLeft,
contentArea.getTopRight(),
bounds.topRight,
contentArea.getBottomLeft(),
bounds.bottomLeft);
if (t.isSingularity())
t = {};
setDrawableTransform (t);
}
}
void DrawableComposite::resetBoundingBoxToContentArea()
{
setBoundingBox (contentArea);
}
void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
{
setContentArea (getDrawableBounds());
resetBoundingBoxToContentArea();
}
void DrawableComposite::addChild (std::unique_ptr<Drawable> newChild)
{
if (newChild == nullptr)
{
jassertfalse;
return;
}
children.emplace_back (std::move (newChild));
callListeners();
}
bool DrawableComposite::replaceColour (Colour originalColour, Colour replacementColour)
{
bool changed = false;
for (const auto& child : children)
changed |= child->replaceColour (originalColour, replacementColour);
return changed;
}
bool DrawableComposite::hitTest (Point<float> p) const
{
return std::any_of (children.begin(), children.end(), [&] (const auto& child)
{
return child->hitTest (p);
});
}
//==============================================================================
Path DrawableComposite::getOutlineAsPath() const
{
Path p;
for (auto& c : children)
p.addPath (c->getOutlineAsPath());
p.applyTransform (getDrawableTransform());
return p;
}
void DrawableComposite::paint (Graphics& g) const
{
const Graphics::ScopedSaveState ss (g);
if (! requiresBlendBuffer())
{
for (const auto& child : children)
child->draw (g, opacity);
return;
}
ScopedBlendContext blend { g,
ScopedBlendContext::Options { blendMode }
.withLuminanceMaskSet (luminanceMask)
.withScopeClip (getDrawableBounds().getSmallestIntegerContainer()) };
if (blend.isClipEmpty())
return;
for (const auto& child : children)
child->draw (blend.getContext(), opacity);
}
bool DrawableComposite::requiresBlendBuffer() const
{
if (blendMode != BlendMode::sourceOver || luminanceMask)
return true;
return std::any_of (children.begin(), children.end(), [] (const auto& child)
{
return child->requiresBlendBuffer();
});
}
} // namespace juce
@@ -0,0 +1,166 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
A drawable object which acts as a container for a set of other Drawables.
Note that although this is a Component, it takes ownership of its child components
and will delete them, so that you can use it as a self-contained graphic object.
The intention is that you should not add your own components to it, only add other
Drawable objects.
@see Drawable
@tags{GUI}
*/
class JUCE_API DrawableComposite : public Drawable
{
public:
//==============================================================================
/** Creates a composite Drawable. */
DrawableComposite() = default;
/** Creates a copy of a DrawableComposite. */
DrawableComposite (const DrawableComposite&);
//==============================================================================
/** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
@see setContentArea
*/
void setBoundingBox (Parallelogram<float> newBoundingBox);
/** Sets the rectangle that defines the target position of the content rectangle when the drawable is rendered.
@see setContentArea
*/
void setBoundingBox (Rectangle<float> newBoundingBox);
/** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
@see setBoundingBox
*/
Parallelogram<float> getBoundingBox() const noexcept { return bounds; }
/** Changes the bounding box transform to match the content area, so that any sub-items will
be drawn at their untransformed positions.
*/
void resetBoundingBoxToContentArea();
/** Returns the main content rectangle.
@see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
*/
Rectangle<float> getContentArea() const noexcept { return contentArea; }
/** Changes the main content area.
@see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
*/
void setContentArea (Rectangle<float> newArea);
/** Resets the content area and the bounding transform to fit around the area occupied
by the child components.
*/
void resetContentAreaAndBoundingBoxToFitChildren();
bool replaceColour (Colour originalColour, Colour replacementColour) override;
bool hitTest (Point<float> p) const override;
/** Adds a child Drawable to this one. */
void addChild (std::unique_ptr<Drawable> newChild);
/** Returns the number of child Drawables that this composite contains.
*/
int getNumChildren() const
{
return static_cast<int> (children.size());
}
Drawable& getChild (int index)
{
jassert (isPositiveAndBelow (index, children.size()));
return *children[(size_t) index];
}
/** Returns a child Drawable by its index.
*/
const Drawable& getChild (int index) const
{
jassert (isPositiveAndBelow (index, children.size()));
return *children[(size_t) index];
}
void setBlendMode (BlendMode newBlendMode)
{
blendMode = newBlendMode;
}
void setLuminanceMask (bool isMask)
{
luminanceMask = isMask;
}
void setOpacity (float newOpacity)
{
opacity = newOpacity;
}
//==============================================================================
/** @internal */
std::unique_ptr<Drawable> createCopy() const override;
/** @internal */
Rectangle<float> getDrawableBoundsUntransformed() const override;
/** @internal */
Rectangle<float> getContentBoundsUntransformed() const override;
/** @internal */
Path getOutlineAsPath() const override;
private:
void paint (Graphics& g) const override;
bool requiresBlendBuffer() const override;
//==============================================================================
std::vector<std::unique_ptr<Drawable>> children;
Rectangle<float> contentArea { 0.0f, 0.0f, 100.0f, 100.0f };
Parallelogram<float> bounds { contentArea };
BlendMode blendMode = BlendMode::sourceOver;
bool luminanceMask = false;
float opacity = 1.0f;
JUCE_LEAK_DETECTOR (DrawableComposite)
};
} // namespace juce
@@ -0,0 +1,186 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
DrawableImage::DrawableImage (const Image& imageToUse)
{
setImageInternal (imageToUse);
}
DrawableImage::DrawableImage (const Image& imageIn,
Rectangle<int> destinationBoundsIn,
Rectangle<int> sourceBoundsIn)
: image (imageIn),
destinationBounds (destinationBoundsIn),
sourceBounds (sourceBoundsIn)
{
}
std::unique_ptr<Drawable> DrawableImage::createCopy() const
{
return std::make_unique<DrawableImage> (*this);
}
//==============================================================================
void DrawableImage::setImage (const Image& imageToUse)
{
if (setImageInternal (imageToUse))
callListeners();
}
void DrawableImage::setOpacity (const float newOpacity)
{
opacity = newOpacity;
}
void DrawableImage::setOverlayColour (Colour newOverlayColour)
{
overlayColour = newOverlayColour;
}
void DrawableImage::setBoundingBox (Rectangle<float> newBounds)
{
setBoundingBox (Parallelogram<float> (newBounds));
}
void DrawableImage::setBoundingBox (Parallelogram<float> newBounds)
{
if (bounds != newBounds)
{
bounds = newBounds;
if (image.isValid())
{
auto tr = bounds.topLeft + (bounds.topRight - bounds.topLeft) / (float) image.getWidth();
auto bl = bounds.topLeft + (bounds.bottomLeft - bounds.topLeft) / (float) image.getHeight();
auto t = AffineTransform::fromTargetPoints (
bounds.topLeft.x, bounds.topLeft.y, tr.x, tr.y, bl.x, bl.y);
if (t.isSingularity())
t = {};
setDrawableTransform (t);
}
}
}
//==============================================================================
void DrawableImage::paint (Graphics& g) const
{
const Graphics::ScopedSaveState ss (g);
if (! image.isValid())
return;
g.setImageResamplingQuality (resamplingQuality);
const auto dst = destinationBounds.isEmpty() ? image.getBounds() : destinationBounds;
const auto src = sourceBounds.isEmpty() ? image.getBounds() : sourceBounds;
if (opacity > 0.0f && ! overlayColour.isOpaque())
{
g.setOpacity (opacity);
g.drawImage (image,
dst.getX(),
dst.getY(),
dst.getWidth(),
dst.getHeight(),
src.getX(),
src.getY(),
src.getWidth(),
src.getHeight(),
false);
}
if (! overlayColour.isTransparent())
{
g.setColour (overlayColour.withMultipliedAlpha (opacity));
g.drawImage (image,
dst.getX(),
dst.getY(),
dst.getWidth(),
dst.getHeight(),
src.getX(),
src.getY(),
src.getWidth(),
src.getHeight(),
true);
}
}
Rectangle<float> DrawableImage::getDrawableBoundsUntransformed() const
{
return image.getBounds().toFloat();
}
bool DrawableImage::hitTest (Point<float> p) const
{
const auto pInt = p.roundToInt();
return image.isValid() && image.getPixelAt (pInt.x, pInt.y).getAlpha() >= 127;
}
Path DrawableImage::getOutlineAsPath() const
{
return {}; // not applicable for images
}
bool DrawableImage::isImage() const
{
return true;
}
void DrawableImage::setImageResamplingQuality (Graphics::ResamplingQuality newQuality)
{
resamplingQuality = newQuality;
}
//==============================================================================
bool DrawableImage::setImageInternal (const Image& imageToUse)
{
if (image != imageToUse)
{
image = imageToUse;
setBoundingBox (image.getBounds().toFloat());
return true;
}
return false;
}
} // namespace juce
@@ -0,0 +1,141 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
A drawable object which is a bitmap image.
@see Drawable
@tags{GUI}
*/
class JUCE_API DrawableImage : public Drawable
{
public:
//==============================================================================
DrawableImage() = default;
DrawableImage (const DrawableImage&) = default;
/** Sets the image that this drawable will render. */
explicit DrawableImage (const Image& imageToUse);
/** Sets the image that this drawable will render. Only the part specified by sourceBounds will
be drawn in the area specified by destinationBounds.
*/
DrawableImage (const Image& image,
Rectangle<int> destinationBounds,
Rectangle<int> sourceBounds);
//==============================================================================
/** Sets the image that this drawable will render. */
void setImage (const Image& imageToUse);
/** Returns the current image. */
const Image& getImage() const noexcept { return image; }
/** Sets the opacity to use when drawing the image. */
void setOpacity (float newOpacity);
/** Returns the image's opacity. */
float getOpacity() const noexcept { return opacity; }
/** Sets a colour to draw over the image's alpha channel.
By default this is transparent so isn't drawn, but if you set a non-transparent
colour here, then it will be overlaid on the image, using the image's alpha
channel as a mask.
This is handy for doing things like darkening or lightening an image by overlaying
it with semi-transparent black or white.
*/
void setOverlayColour (Colour newOverlayColour);
/** Returns the overlay colour. */
Colour getOverlayColour() const noexcept { return overlayColour; }
/** Sets the bounding box within which the image should be displayed. */
void setBoundingBox (Parallelogram<float> newBounds);
/** Sets the bounding box within which the image should be displayed. */
void setBoundingBox (Rectangle<float> newBounds);
/** Returns the position to which the image's top-left corner should be remapped in the target
coordinate space when rendering this object.
@see setTransform
*/
Parallelogram<float> getBoundingBox() const noexcept { return bounds; }
/** Sets the resampling quality to use when drawing the image.
This will have the most noticeable effect when the DrawableImage size does not match the
image size.
Defaults to highResamplingQuality.
*/
void setImageResamplingQuality (Graphics::ResamplingQuality newQuality);
//==============================================================================
/** @internal */
bool hitTest (Point<float>) const override;
/** @internal */
std::unique_ptr<Drawable> createCopy() const override;
/** @internal */
Rectangle<float> getDrawableBoundsUntransformed() const override;
/** @internal */
Path getOutlineAsPath() const override;
/** @internal */
bool isImage() const override;
/** @internal */
void paint (Graphics& g) const override;
private:
//==============================================================================
bool setImageInternal (const Image&);
//==============================================================================
Image image;
Rectangle<int> destinationBounds;
Rectangle<int> sourceBounds;
float opacity = 1.0f;
Colour overlayColour { 0 };
Parallelogram<float> bounds { { 0.0f, 0.0f, 1.0f, 1.0f } };
Graphics::ResamplingQuality resamplingQuality = Graphics::ResamplingQuality::highResamplingQuality;
JUCE_LEAK_DETECTOR (DrawableImage)
};
} // namespace juce
@@ -0,0 +1,58 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
std::unique_ptr<Drawable> DrawablePath::createCopy() const
{
return std::make_unique<DrawablePath> (*this);
}
void DrawablePath::setPath (const Path& newPath)
{
path = newPath;
pathChanged();
}
void DrawablePath::setPath (Path&& newPath)
{
path = std::move (newPath);
pathChanged();
}
const Path& DrawablePath::getPath() const { return path; }
const Path& DrawablePath::getStrokePath() const { return strokePath; }
} // namespace juce
@@ -0,0 +1,82 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
A drawable object which renders a filled or outlined shape.
For details on how to change the fill and stroke, see the DrawableShape class.
@see Drawable, DrawableShape
@tags{GUI}
*/
class JUCE_API DrawablePath : public DrawableShape
{
public:
//==============================================================================
/** Creates a DrawablePath. */
DrawablePath() = default;
DrawablePath (const DrawablePath&) = default;
//==============================================================================
/** Changes the path that will be drawn.
@see setFill, setStrokeType
*/
void setPath (const Path& newPath);
/** Changes the path that will be drawn.
@see setFill, setStrokeType
*/
void setPath (Path&& newPath);
/** Returns the current path. */
const Path& getPath() const;
/** Returns the current path for the outline. */
const Path& getStrokePath() const;
//==============================================================================
/** @internal */
std::unique_ptr<Drawable> createCopy() const override;
private:
//==============================================================================
JUCE_LEAK_DETECTOR (DrawablePath)
};
} // namespace juce
@@ -0,0 +1,82 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
std::unique_ptr<Drawable> DrawableRectangle::createCopy() const
{
return std::make_unique<DrawableRectangle> (*this);
}
//==============================================================================
void DrawableRectangle::setRectangle (Parallelogram<float> newBounds)
{
if (std::exchange (bounds, newBounds) != newBounds)
rebuildPath();
}
void DrawableRectangle::setCornerSize (Point<float> newSize)
{
if (std::exchange (cornerSize, newSize) != newSize)
rebuildPath();
}
void DrawableRectangle::rebuildPath()
{
auto w = bounds.getWidth();
auto h = bounds.getHeight();
Path newPath;
if (cornerSize.x > 0 && cornerSize.y > 0)
newPath.addRoundedRectangle (0, 0, w, h, cornerSize.x, cornerSize.y);
else
newPath.addRectangle (0, 0, w, h);
newPath.applyTransform (AffineTransform::fromTargetPoints (Point<float>(),
bounds.topLeft,
Point<float> (w, 0),
bounds.topRight,
Point<float> (0, h),
bounds.bottomLeft));
if (path != newPath)
{
path.swapWithPath (newPath);
pathChanged();
}
}
} // namespace juce
@@ -0,0 +1,80 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
A Drawable object which draws a rectangle.
For details on how to change the fill and stroke, see the DrawableShape class.
@see Drawable, DrawableShape
@tags{GUI}
*/
class JUCE_API DrawableRectangle : public DrawableShape
{
public:
//==============================================================================
DrawableRectangle() = default;
//==============================================================================
/** Sets the rectangle's bounds. */
void setRectangle (Parallelogram<float> newBounds);
/** Returns the rectangle's bounds. */
Parallelogram<float> getRectangle() const noexcept { return bounds; }
/** Returns the corner size to be used. */
Point<float> getCornerSize() const noexcept { return cornerSize; }
/** Sets a new corner size for the rectangle */
void setCornerSize (Point<float> newSize);
//==============================================================================
/** @internal */
std::unique_ptr<Drawable> createCopy() const override;
private:
Parallelogram<float> bounds;
Point<float> cornerSize;
void rebuildPath();
JUCE_LEAK_DETECTOR (DrawableRectangle)
};
} // namespace juce
@@ -0,0 +1,176 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
void DrawableShape::setFill (const FillType& newFill)
{
if (std::exchange (mainFill, newFill) != newFill)
callListeners();
}
void DrawableShape::setStrokeFill (const FillType& newStrokeFill)
{
if (std::exchange (strokeFill, newStrokeFill) != newStrokeFill)
strokeChanged();
}
void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
{
const auto newStrokeAttributes = strokeOptions.withWidth (newStrokeType.getStrokeThickness())
.withLineJoin (newStrokeType.getJointStyle())
.withLineCap (newStrokeType.getEndStyle())
.withMiterLimit (newStrokeType.getMiterLimit());
if (std::exchange (strokeOptions, newStrokeAttributes) != newStrokeAttributes)
strokeChanged();
}
void DrawableShape::setDashLengths (Span<const float> newDashLengths)
{
const auto newStrokeAttributes = strokeOptions.withDashArray (newDashLengths);
if (std::exchange (strokeOptions, newStrokeAttributes) != newStrokeAttributes)
strokeChanged();
}
void DrawableShape::setDashOffset (float dashOffset)
{
const auto newStrokeAttributes = strokeOptions.withDashOffset (dashOffset);
if (std::exchange (strokeOptions, newStrokeAttributes) != newStrokeAttributes)
strokeChanged();
}
void DrawableShape::setStrokeThickness (const float newThickness)
{
const auto newStrokeAttributes = strokeOptions.withWidth (newThickness);
if (std::exchange (strokeOptions, newStrokeAttributes) != newStrokeAttributes)
strokeChanged();
}
bool DrawableShape::isStrokeVisible() const noexcept
{
return strokeOptions.createStrokeType().getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
}
//==============================================================================
void DrawableShape::paint (Graphics& g) const
{
g.setFillType (mainFill);
g.fillPath (path);
if (isStrokeVisible())
{
g.setFillType (strokeFill);
g.fillPath (strokePath);
}
}
void DrawableShape::pathChanged()
{
strokeChanged();
}
void DrawableShape::strokeChanged()
{
strokePath.clear();
static constexpr float extraAccuracy = 4.0f;
const auto strokeType = strokeOptions.createStrokeType();
if (strokeOptions.getDashArray().empty())
strokeType.createStrokedPath (strokePath, path, AffineTransform(), extraAccuracy);
else
strokeType.createDashedStroke (strokePath,
path,
strokeOptions.getDashArray().data(),
(int) strokeOptions.getDashArray().size(),
AffineTransform(),
extraAccuracy,
strokeOptions.getDashOffset());
callListeners();
}
Rectangle<float> DrawableShape::getDrawableBoundsUntransformed() const
{
if (isStrokeVisible())
return strokePath.getBounds();
return path.getBounds();
}
bool DrawableShape::hitTest (Point<float> p) const
{
const auto contains = [] (const Path& pathToCheck, Point<float> point, const AffineTransform& t)
{
auto transformed = pathToCheck;
transformed.applyTransform (t);
return transformed.contains (point);
};
return contains (path, p, getDrawableTransform())
|| (isStrokeVisible() && contains (strokePath, p, getDrawableTransform()));
}
//==============================================================================
static bool replaceColourInFill (FillType& fill, Colour original, Colour replacement)
{
if (fill.colour == original && fill.isColour())
{
fill = FillType (replacement);
return true;
}
return false;
}
bool DrawableShape::replaceColour (Colour original, Colour replacement)
{
bool changed1 = replaceColourInFill (mainFill, original, replacement);
bool changed2 = replaceColourInFill (strokeFill, original, replacement);
return changed1 || changed2;
}
Path DrawableShape::getOutlineAsPath() const
{
auto outline = isStrokeVisible() ? strokePath : path;
outline.applyTransform (getTransform());
return outline;
}
} // namespace juce
@@ -0,0 +1,133 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
A base class implementing common functionality for Drawable classes which
consist of some kind of filled and stroked outline.
@see DrawablePath, DrawableRectangle
@tags{GUI}
*/
class JUCE_API DrawableShape : public Drawable
{
protected:
//==============================================================================
DrawableShape() = default;
DrawableShape (const DrawableShape&) = default;
public:
//==============================================================================
/** Sets a fill type for the path.
This colour is used to fill the path - if you don't want the path to be
filled (e.g. if you're just drawing an outline), set this to a transparent
colour.
@see setPath, setStrokeFill
*/
void setFill (const FillType& newFill);
/** Returns the current fill type.
@see setFill
*/
const FillType& getFill() const noexcept { return mainFill; }
/** Sets the fill type with which the outline will be drawn.
@see setFill
*/
void setStrokeFill (const FillType& newStrokeFill);
/** Returns the current stroke fill.
@see setStrokeFill
*/
const FillType& getStrokeFill() const noexcept { return strokeFill; }
/** Changes the properties of the outline that will be drawn around the path.
If the stroke has 0 thickness, no stroke will be drawn.
@see setStrokeThickness, setStrokeColour
*/
void setStrokeType (const PathStrokeType& newStrokeType);
/** Changes the stroke thickness.
This is a shortcut for calling setStrokeType.
*/
void setStrokeThickness (float newThickness);
/** Returns the current outline style. */
PathStrokeType getStrokeType() const noexcept { return strokeOptions.createStrokeType(); }
/** Provides a set of dash lengths to use for stroking the path. */
void setDashLengths (Span<const float> newDashLengths);
/** Provides an offset on the rendering of the associated dash array. */
void setDashOffset (float dashOffset);
/** Returns the set of dash lengths that the path is using. */
Span<const float> getDashLengths() const& { return strokeOptions.getDashArray(); }
Span<const float> getDashLengths() const&& = delete;
//==============================================================================
/** @internal */
Rectangle<float> getDrawableBoundsUntransformed() const override;
/** @internal */
bool hitTest (Point<float>) const override;
/** @internal */
bool replaceColour (Colour originalColour, Colour replacementColour) override;
/** @internal */
Path getOutlineAsPath() const override;
protected:
//==============================================================================
/** Called when the cached path should be updated. */
void pathChanged();
/** Called when the cached stroke should be updated. */
void strokeChanged();
/** True if there's a stroke with a non-zero thickness and non-transparent colour. */
bool isStrokeVisible() const noexcept;
//==============================================================================
StrokeOptions strokeOptions = StrokeOptions{}.withWidth (0.0f);
Path path, strokePath;
private:
void paint (Graphics& g) const override;
FillType mainFill, strokeFill;
};
} // namespace juce
@@ -0,0 +1,284 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
std::unique_ptr<Drawable> DrawableText::createCopy() const
{
return std::make_unique<DrawableText> (*this);
}
//==============================================================================
void DrawableText::setText (const String& newText)
{
setMember (&DrawableText::text, newText);
}
void DrawableText::setPreserveWhitespace (bool shouldPreserveWhitespace)
{
setMember (&DrawableText::preserveWhitespace, shouldPreserveWhitespace);
}
void DrawableText::setColour (Colour newColour)
{
setFill (FillType { newColour });
}
void DrawableText::setFill (const FillType& newFill)
{
setMember (&DrawableText::fill, newFill);
}
void DrawableText::setStrokeOptions (const StrokeOptions& newStrokeOptions)
{
if (std::exchange (strokeOptions, newStrokeOptions) != newStrokeOptions)
update();
}
void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
{
if (font != newFont)
{
font = newFont;
if (applySizeAndScale)
{
fontHeight = font.getHeight();
fontHScale = font.getHorizontalScale();
}
update();
}
}
void DrawableText::setJustification (Justification newJustification)
{
setMember (&DrawableText::justification, newJustification);
}
void DrawableText::setBoundingBox (Parallelogram<float> newBounds)
{
setMember (&DrawableText::bounds, newBounds);
}
bool DrawableText::hitTest (Point<float> p) const
{
const auto t = getDrawableTransform();
Path path;
path.addRectangle (bounds.getBoundingBox());
path.applyTransform (t);
return path.contains (p);
}
void DrawableText::setFontHeight (float newHeight)
{
if (! approximatelyEqual (fontHeight, newHeight))
{
fontHeight = newHeight;
update();
}
}
void DrawableText::setFontHorizontalScale (float newScale)
{
if (! approximatelyEqual (fontHScale, newScale))
{
fontHScale = newScale;
update();
}
}
void DrawableText::update()
{
auto w = bounds.getWidth();
auto h = bounds.getHeight();
auto height = jlimit (0.01f, jmax (0.01f, h), fontHeight);
auto hscale = jlimit (0.01f, jmax (0.01f, w), fontHScale);
scaledFont = font;
scaledFont.setHeight (height);
scaledFont.setHorizontalScale (hscale);
if (strokeOptions.getWidth() > 0.0f)
{
const auto strokeType = strokeOptions.createStrokeType();
const auto path = getOutlineAsPath();
static constexpr float extraAccuracy = 4.0f;
if (strokeOptions.getDashArray().empty())
{
strokeType.createStrokedPath (strokePath, path, getTransform().inverted(), extraAccuracy);
}
else
{
strokeType.createDashedStroke (strokePath,
path,
strokeOptions.getDashArray().data(),
(int) strokeOptions.getDashArray().size(),
getTransform().inverted(),
extraAccuracy,
strokeOptions.getDashOffset());
}
}
callListeners();
}
//==============================================================================
Rectangle<float> DrawableText::getTextArea() const
{
return { bounds.getWidth(), bounds.getHeight() };
}
AffineTransform DrawableText::getTextTransform() const
{
const auto transformBounds = bounds - bounds.getTopLeft();
return AffineTransform::fromTargetPoints (Point<float>(), transformBounds.topLeft,
Point<float> (bounds.getWidth(), 0), transformBounds.topRight,
Point<float> (0, bounds.getHeight()), transformBounds.bottomLeft);
}
void DrawableText::paint (Graphics& g) const
{
const Graphics::ScopedSaveState ss (g);
g.setFont (scaledFont);
g.setFillType (fill);
if (preserveWhitespace)
{
g.drawText (text, getBoundingRectangle(), justification, false);
}
else
{
g.drawFittedText (text,
getBoundingRectangle().toNearestInt(),
justification,
0x100000);
}
if (strokeOptions.getWidth() > 0.0f)
{
g.setColour (strokeOptions.getColour());
g.fillPath (strokePath);
}
}
AffineTransform DrawableText::getTransform() const
{
return getTextTransform().followedBy (getDrawableTransform());
}
Rectangle<float> DrawableText::getDrawableBoundsUntransformed() const
{
return bounds.getBoundingBox();
}
Path DrawableText::getOutlineAsPath() const
{
auto area = getBoundingRectangle();
GlyphArrangement arr;
if (preserveWhitespace)
{
arr.addJustifiedText (scaledFont,
text,
area.getX(),
area.getY() + scaledFont.getAscent(),
area.getWidth(),
justification);
}
else
{
arr.addFittedText (scaledFont,
text,
area.getX(),
area.getY(),
area.getWidth(),
area.getHeight(),
justification,
0x100000);
}
Path pathOfAllGlyphs;
for (auto& glyph : arr)
{
Path gylphPath;
glyph.createPath (gylphPath);
pathOfAllGlyphs.addPath (gylphPath);
}
pathOfAllGlyphs.applyTransform (getTransform());
return pathOfAllGlyphs;
}
bool DrawableText::replaceColour (Colour originalColour, Colour replacementColour)
{
if (colour != originalColour)
return false;
setColour (replacementColour);
return true;
}
std::optional<String> DrawableText::getContainedText() const
{
return getText();
}
template <typename Object, typename Member, typename Other>
void DrawableText::setMember (Member Object::* member, const Other& value)
{
if (std::exchange (this->*member, value) != value)
update();
}
Rectangle<float> DrawableText::getBoundingRectangle() const
{
const auto boundingRectangle = bounds.getBoundingBox();
if (preserveWhitespace)
return boundingRectangle;
// Supporting legacy behaviour
return boundingRectangle.getSmallestIntegerContainer().toFloat();
}
} // namespace juce
@@ -0,0 +1,166 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
A drawable object which renders a line of text.
@see Drawable
@tags{GUI}
*/
class JUCE_API DrawableText : public Drawable
{
public:
//==============================================================================
/** Creates a DrawableText object. */
DrawableText() = default;
//==============================================================================
/** Sets the text to display.*/
void setText (const String& newText);
/** Sets whether whitespace should always be preserved when drawing. The default value is false.
Historically, DrawableText would sometimes trim the provided text during drawing based on
its contents. With this value set to true, trimming will never occur.
*/
void setPreserveWhitespace (bool shouldPreserveWhitespace);
/** Returns the currently displayed text */
const String& getText() const noexcept { return text;}
/** Sets the colour of the text. */
void setColour (Colour newColour);
/** Sets a fill type for the text. */
void setFill (const FillType& newFill);
/** Returns the current text colour. */
Colour getColour() const noexcept { return colour; }
/** Changes the properties of the outline that will be drawn around the text.
By default the text has no stroke. Specifying any StrokeOptions with a width
of 0.0f will be similarly not drawn.
@see setStrokeThickness, setStrokeColour
*/
void setStrokeOptions (const StrokeOptions& newStrokeOptions);
/** Returns the currently specified stroke attributes. A stroke with a width of 0.0f
is considered invisible, and will not be drawn.
@see setFill
*/
const StrokeOptions& getStrokeOptions() { return strokeOptions; }
/** Sets the font to use.
Note that the font height and horizontal scale are set using setFontHeight() and
setFontHorizontalScale(). If applySizeAndScale is true, then these height
and scale values will be changed to match the dimensions of the font supplied;
if it is false, then the new font object's height and scale are ignored.
*/
void setFont (const Font& newFont, bool applySizeAndScale);
/** Returns the current font. */
const Font& getFont() const noexcept { return font; }
/** Changes the justification of the text within the bounding box. */
void setJustification (Justification newJustification);
/** Returns the current justification. */
Justification getJustification() const noexcept { return justification; }
/** Returns the parallelogram that defines the text bounding box. */
Parallelogram<float> getBoundingBox() const noexcept { return bounds; }
/** Sets the bounding box that contains the text. */
void setBoundingBox (Parallelogram<float> newBounds);
bool hitTest (Point<float> p) const override;
float getFontHeight() const noexcept { return fontHeight; }
void setFontHeight (float newHeight);
float getFontHorizontalScale() const noexcept { return fontHScale; }
void setFontHorizontalScale (float newScale);
//==============================================================================
/** @internal */
std::unique_ptr<Drawable> createCopy() const override;
/** @internal */
Rectangle<float> getDrawableBoundsUntransformed() const override;
/** @internal */
Path getOutlineAsPath() const override;
/** @internal */
bool replaceColour (Colour originalColour, Colour replacementColour) override;
/** @internal */
std::optional<String> getContainedText() const override;
private:
template <typename Object, typename Member, typename Other>
void setMember (Member Object::* member, const Other& value);
Rectangle<float> getBoundingRectangle() const;
void update();
void paint (Graphics& g) const override;
AffineTransform getTransform() const override;
//==============================================================================
Parallelogram<float> bounds { { 0.0f, 0.0f, 50.0f, 20.0f } };
Font font { FontOptions (15.0f) };
Font scaledFont { FontOptions{} };
float fontHeight = font.getHeight();
float fontHScale = font.getHorizontalScale();
String text;
bool preserveWhitespace = false;
Colour colour { Colours::black };
FillType fill;
Justification justification { Justification::centredLeft };
StrokeOptions strokeOptions = StrokeOptions{}.withWidth (0.0f);
Path strokePath;
Rectangle<float> getTextArea() const;
AffineTransform getTextTransform() const;
JUCE_LEAK_DETECTOR (DrawableText)
};
} // namespace juce
@@ -0,0 +1,876 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
#include <juce_graphics/drawables/lunasvg/plutovg/source/plutovg-private.h>
#include <stack>
namespace juce
{
std::unique_ptr<Drawable> Drawable::createFromSVGFile (const File& svgFile)
{
return createFromSVGString (svgFile.loadFileAsString());
}
Path Drawable::parseSVGPath (const String& svgPath)
{
const auto svgString = "<svg xmlns=\"http://www.w3.org/2000/svg\"><path d=" + svgPath.quoted() + " /></svg>";
const auto composite = createFromSVGString (svgString);
if (composite->getNumChildren() != 1)
{
jassertfalse;
return {};
}
auto* p = dynamic_cast<const DrawablePath*> (&composite->getChild (0));
if (p == nullptr)
return {};
return p->getPath();
}
struct LunaSvgConverters
{
LunaSvgConverters() = delete;
static Path toJucePath (const lunasvg::Path& p,
const lunasvg::FillRule& fillRule = lunasvg::FillRule::NonZero)
{
juce::Path output;
for (auto it = lunasvg::PathIterator { p }; ! it.isDone(); it.next())
{
std::array<lunasvg::Point, 3> points;
switch (it.currentSegment (points))
{
case lunasvg::PathCommand::MoveTo:
output.startNewSubPath (points[0].x, points[0].y);
break;
case lunasvg::PathCommand::LineTo:
output.lineTo (points[0].x, points[0].y);
break;
case lunasvg::PathCommand::CubicTo:
output.cubicTo (
points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y);
break;
case lunasvg::PathCommand::Close:
output.closeSubPath();
break;
}
}
output.setUsingNonZeroWinding (fillRule == lunasvg::FillRule::NonZero);
return output;
}
static Rectangle<float> toJuceRectangle (const lunasvg::Rect& r)
{
return { r.x, r.y, r.w, r.h };
}
static PathStrokeType::JointStyle toJuceJointStyle (const lunasvg::LineJoin& lineCap)
{
switch (lineCap)
{
case lunasvg::LineJoin::Miter:
return PathStrokeType::mitered;
case lunasvg::LineJoin::Round:
return PathStrokeType::curved;
case lunasvg::LineJoin::Bevel:
return PathStrokeType::beveled;
}
jassertfalse;
return PathStrokeType::beveled;
}
static PathStrokeType::EndCapStyle toJuceEndCapStyle (const lunasvg::LineCap& lineCap)
{
switch (lineCap)
{
case lunasvg::LineCap::Butt:
return PathStrokeType::butt;
case lunasvg::LineCap::Round:
return PathStrokeType::rounded;
case lunasvg::LineCap::Square:
return PathStrokeType::square;
}
jassertfalse;
return PathStrokeType::square;
}
static AffineTransform toJuceTransform (const lunasvg::Transform& transform)
{
const auto& m = transform.matrix();
return AffineTransform { m.a, m.c, m.e, m.b, m.d, m.f };
}
static Colour toJuceColour (const lunasvg::Color& colour)
{
return Colour::fromRGBA (colour.red(), colour.green(), colour.blue(), colour.alpha());
}
static Colour toJuceColour (const juce_plutovg_color_t& colour)
{
return Colour::fromFloatRGBA (colour.r, colour.g, colour.b, colour.a);
}
static ColourGradient::SpreadMethod toJuceSpreadMethod (const lunasvg::SpreadMethod& spread)
{
switch (spread)
{
case lunasvg::SpreadMethod::Pad:
return ColourGradient::SpreadMethod::pad;
case lunasvg::SpreadMethod::Reflect:
return ColourGradient::SpreadMethod::reflect;
case lunasvg::SpreadMethod::Repeat:
return ColourGradient::SpreadMethod::repeat;
}
jassertfalse;
return ColourGradient::SpreadMethod::pad;
}
static Image toJuceImage (juce_plutovg_surface* s)
{
if (s == nullptr || s->data == nullptr || s->width <= 0 || s->height <= 0)
return {};
Image image { Image::ARGB, s->width, s->height, false };
Image::BitmapData destData { image, Image::BitmapData::writeOnly };
for (int y = 0; y < s->height; ++y)
{
const auto* src = s->data + (size_t) (y * s->stride);
auto* dest = destData.getLinePointer (y);
memcpy (dest, src, (size_t) s->width * 4);
}
return image;
}
static BlendMode toJuceBlendMode (const lunasvg::BlendMode& blendMode)
{
switch (blendMode)
{
case lunasvg::BlendMode::Src: return BlendMode::source;
case lunasvg::BlendMode::Src_Over: return BlendMode::sourceOver;
case lunasvg::BlendMode::Dst_In: return BlendMode::destinationIn;
case lunasvg::BlendMode::Dst_Out: return BlendMode::destinationOut;
}
jassertfalse;
return BlendMode::source;
}
static Rectangle<int> toJuceIntRectangle (const lunasvg::Rect& r)
{
return Rectangle<float> { r.x, r.y, r.w, r.h }.toNearestInt();
}
static lunasvg::Rect fromJuceRectangle (const Rectangle<float>& r)
{
return lunasvg::Rect { r.getX(), r.getY(), r.getWidth(), r.getHeight() };
}
};
namespace
{
class DrawableCanvas : public lunasvg::Canvas
{
private:
struct State
{
FillType fillType;
std::shared_ptr<Drawable> clipPath;
};
protected:
std::shared_ptr<Canvas> createFromBounds (int x, int y, int width, int height) override
{
auto canvas = std::make_shared<DrawableCanvas> (&document);
canvas->setContentArea (Rectangle<int> (x, y, width, height).toFloat());
return canvas;
}
std::shared_ptr<Canvas> createFromBitmap (const lunasvg::Bitmap&) override
{
jassertfalse;
return {};
}
public:
explicit DrawableCanvas (const lunasvg::Document* documentIn)
: document (*documentIn)
{
}
void setColor (const lunasvg::Color& color) override
{
getState().fillType = FillType { LunaSvgConverters::toJuceColour (color) };
}
void setColor (float r, float g, float b, float a) override
{
getState().fillType = Colour::fromFloatRGBA (r, g, b, a);
}
void setLinearGradient (float x1,
float y1,
float x2,
float y2,
lunasvg::SpreadMethod spread,
const lunasvg::GradientStops& stops,
const lunasvg::Transform& transform) override
{
ColourGradient gradient;
gradient.point1 = { x1, y1 };
gradient.point2 = { x2, y2 };
gradient.spreadMethod = LunaSvgConverters::toJuceSpreadMethod (spread);
for (const auto& stop : stops)
gradient.addColour (stop.offset, LunaSvgConverters::toJuceColour (stop.color));
const auto gradientTransform = LunaSvgConverters::toJuceTransform (transform);
getState().fillType = FillType { gradient }.transformed (gradientTransform);
}
void setRadialGradient (float cx,
float cy,
float r,
float fx,
float fy,
lunasvg::SpreadMethod spread,
const lunasvg::GradientStops& stops,
const lunasvg::Transform& transform) override
{
ColourGradient gradient;
gradient.isRadial = true;
for (const auto& stop : stops)
gradient.addColour (stop.offset, LunaSvgConverters::toJuceColour (stop.color));
const auto gradientTransform = LunaSvgConverters::toJuceTransform (transform);
const Point<float> endCentre { cx, cy };
const Point<float> startCentre { fx, fy };
gradient.point1 = startCentre;
gradient.point2 = endCentre;
gradient.endRadius = r;
gradient.spreadMethod = LunaSvgConverters::toJuceSpreadMethod (spread);
getState().fillType = FillType { gradient }.transformed (gradientTransform);
}
void setTexture (const Canvas& source,
lunasvg::TextureType type,
float opacity,
const lunasvg::Transform& transform) override
{
jassertquiet (type == lunasvg::TextureType::Tiled);
const DrawableCanvas* drawableCanvas = dynamic_cast<const DrawableCanvas*> (&source);
if (drawableCanvas == nullptr)
{
jassertfalse;
return;
}
auto image = drawableCanvas->getJuceSurface();
auto fill = FillType { std::move (image), LunaSvgConverters::toJuceTransform (transform) };
fill.setOpacity (opacity);
getState().fillType = std::move (fill);
}
static void applyClipPath (const Drawable* clip, Drawable& drawable)
{
if (clip == nullptr)
return;
auto clipForDrawable = clip->createCopy();
auto t = clip->getDrawableTransform();
clipForDrawable->setDrawableTransform (t.followedBy (drawable.getDrawableTransform().inverted()));
drawable.setClipPath (std::move (clipForDrawable));
}
void fillPath (const lunasvg::Path& path,
lunasvg::FillRule fillRule,
const lunasvg::Transform& transform) override
{
auto p = std::make_unique<DrawablePath>();
p->setName (document.getElementIdBeingRendered());
p->setFill (getState().fillType);
p->setPath (LunaSvgConverters::toJucePath (path, fillRule));
p->setDrawableTransform (LunaSvgConverters::toJuceTransform (transform));
applyClipPath (getState().clipPath.get(), *p);
lastPath = p.get();
composite->addChild (std::move (p));
}
void strokePath (const lunasvg::Path& path,
const lunasvg::StrokeData& strokeData,
const lunasvg::Transform& transform) override
{
const auto configureStrokeAndResetLastPath = [&] (DrawablePath& drawablePath)
{
drawablePath.setStrokeFill (getState().fillType);
PathStrokeType strokeType { strokeData.lineWidth(),
LunaSvgConverters::toJuceJointStyle (strokeData.lineJoin()),
LunaSvgConverters::toJuceEndCapStyle (strokeData.lineCap()) };
strokeType.setMiterLimit (strokeData.miterLimit());
drawablePath.setStrokeType (strokeType);
drawablePath.setDashLengths (strokeData.dashArray());
drawablePath.setDashOffset (strokeData.dashOffset());
lastPath = nullptr;
};
const auto jucePath = LunaSvgConverters::toJucePath (path);
const auto juceTransform = LunaSvgConverters::toJuceTransform (transform);
if (lastPath != nullptr
&& lastPath->getPath() == jucePath
&& lastPath->getDrawableTransform() == juceTransform)
{
configureStrokeAndResetLastPath (*lastPath);
return;
}
auto p = std::make_unique<DrawablePath>();
p->setName (document.getElementIdBeingRendered());
p->setFill (Colour::fromRGBA (0, 0, 0, 0));
configureStrokeAndResetLastPath (*p);
p->setPath (jucePath);
p->setDrawableTransform (juceTransform);
applyClipPath (getState().clipPath.get(), *p);
composite->addChild (std::move (p));
}
class LunaSvgTextParameters
{
public:
LunaSvgTextParameters (const std::u32string_view& textIn,
const lunasvg::Font& fontIn,
const lunasvg::Point& originIn,
const lunasvg::Transform& transformIn)
: text { toJuceString (textIn) },
font { fontIn.getFont() },
origin { originIn.x, originIn.y },
transform { LunaSvgConverters::toJuceTransform (transformIn) }
{
}
std::unique_ptr<DrawableText> createDrawableText()
{
auto t = std::make_unique<DrawableText>();
t->setPreserveWhitespace (true);
t->setFont (font, true);
t->setDrawableTransform (transform);
t->setText (text);
const Rectangle<float> bounds { origin.x,
origin.y - font.getAscent(),
GlyphArrangement::getStringWidth (font, text),
font.getHeight() };
t->setBoundingBox (bounds);
drawableText = t.get();
return t;
}
void setStrokeOptionsOnLastObject (const StrokeOptions& attrs)
{
if (drawableText == nullptr)
return;
drawableText->setStrokeOptions (attrs);
}
void setFillOnLastObject (const FillType& fill)
{
if (drawableText == nullptr)
return;
drawableText->setFill (fill);
}
bool operator== (const LunaSvgTextParameters& other) const noexcept
{
return text == other.text
&& font == other.font
&& origin == other.origin
&& transform == other.transform;
}
bool operator!= (const LunaSvgTextParameters& other) const noexcept
{
return ! operator== (other);
}
private:
static String toJuceString (const std::u32string_view& view)
{
return juce::String { juce::CharPointer_UTF32 (reinterpret_cast<const CharPointer_UTF32::CharType*> (view.data())),
view.length() };
}
String text;
Font font;
Point<float> origin;
AffineTransform transform;
DrawableText* drawableText = nullptr;
};
void fillText (const std::u32string_view& text,
const lunasvg::Font& font,
const lunasvg::Point& origin,
const lunasvg::Transform& transform) override
{
lastTextParams = LunaSvgTextParameters { text, font, origin, transform };
auto t = lastTextParams->createDrawableText();
t->setName (document.getElementIdBeingRendered());
t->setFill (getState().fillType);
applyClipPath (getState().clipPath.get(), *t);
composite->addChild (std::move (t));
}
void strokeText (const std::u32string_view& text,
float strokeWidth,
const lunasvg::Font& font,
const lunasvg::Point& origin,
const lunasvg::Transform& transform) override
{
const auto attrs = StrokeOptions{}.withWidth (strokeWidth).withColour (getState().fillType.colour);
LunaSvgTextParameters textParams { text, font, origin, transform };
if (auto lastParams = std::exchange (lastTextParams, {}); lastParams.has_value() && *lastParams == textParams)
{
lastParams->setStrokeOptionsOnLastObject (attrs);
return;
}
auto t = textParams.createDrawableText();
t->setName (document.getElementIdBeingRendered());
t->setFill (FillType { Colours::transparentBlack });
t->setStrokeOptions (attrs);
applyClipPath (getState().clipPath.get(), *t);
composite->addChild (std::move (t));
}
void clipPath (const Path& path,
const lunasvg::Transform& transform)
{
auto clip = std::make_unique<DrawablePath>();
clip->setPath (path);
clip->setDrawableTransform (LunaSvgConverters::toJuceTransform (transform));
getState().clipPath = std::move (clip);
}
void clipPath (const lunasvg::Path& path,
lunasvg::FillRule clipRule,
const lunasvg::Transform& transform) override
{
clipPath (LunaSvgConverters::toJucePath (path, clipRule), transform);
}
void clipRect (const lunasvg::Rect& rect,
lunasvg::FillRule clipRule,
const lunasvg::Transform& transform) override
{
auto r = LunaSvgConverters::toJuceRectangle (rect);
Path p;
p.addRectangle (r);
p.setUsingNonZeroWinding (clipRule == lunasvg::FillRule::NonZero);
clipPath (p, transform);
}
void drawImage (const lunasvg::Bitmap& image,
const lunasvg::Rect& dstRect,
const lunasvg::Rect& srcRect,
const lunasvg::Transform& transform) override
{
auto i = std::make_unique<DrawableImage> (LunaSvgConverters::toJuceImage (image.surface()),
LunaSvgConverters::toJuceIntRectangle (dstRect),
LunaSvgConverters::toJuceIntRectangle (srcRect));
i->setName (document.getElementIdBeingRendered());
i->setDrawableTransform (LunaSvgConverters::toJuceTransform (transform));
applyClipPath (getState().clipPath.get(), *i);
composite->addChild (std::move (i));
}
void blendCanvas (const Canvas& canvas, lunasvg::BlendMode blendMode, float opacity) override
{
const DrawableCanvas* drawableCanvas = dynamic_cast<const DrawableCanvas*> (&canvas);
if (drawableCanvas == nullptr)
{
// If this happened, we didn't replace all canvas objects inside lunasvg with DrawableCanvas
jassertfalse;
return;
}
std::unique_ptr<DrawableComposite> other { static_cast<DrawableComposite*> (drawableCanvas->composite->createCopy().release()) };
other->setBlendMode (LunaSvgConverters::toJuceBlendMode (blendMode));
other->setOpacity (opacity);
composite->addChild (std::move (other));
}
void save() override
{
saveState();
}
void restore() override
{
restoreState();
}
void convertToLuminanceMask() override
{
composite->setLuminanceMask (true);
}
int x() const override
{
return getContentArea().getSmallestIntegerContainer().getX();
}
int y() const override
{
return getContentArea().getSmallestIntegerContainer().getY();
}
int width() const override
{
return getContentArea().getSmallestIntegerContainer().getWidth();
}
int height() const override
{
return getContentArea().getSmallestIntegerContainer().getHeight();
}
lunasvg::Rect extents() const override
{
return LunaSvgConverters::fromJuceRectangle (getContentArea().getSmallestIntegerContainer().toFloat());
}
Image getJuceSurface() const
{
const auto extents = getContentArea().getSmallestIntegerContainer();
Image image { Image::ARGB, extents.getWidth(), extents.getHeight(), true };
Graphics g (image);
g.addTransform (AffineTransform::translation ((float) -extents.getX(), (float) -extents.getY()));
composite->draw (g, 1.0f);
return image;
}
juce_plutovg_surface_t* surface() const override
{
// We could implement this by converting the result of getJuceSurface(), but if every angle
// is covered by our code, this shouldn't be called, and our code can call getJuceSurface()
// directly.
jassertfalse;
return nullptr;
}
juce_plutovg_canvas_t* canvas() const override
{
// Not implemented
jassertfalse;
return nullptr;
}
std::unique_ptr<DrawableComposite> release()
{
return std::move (composite);
}
State& getState()
{
if (state.empty())
state.push (State());
return state.top();
}
void saveState()
{
state.push (getState());
}
void restoreState()
{
if (state.size() > 1)
state.pop();
}
void setContentArea (const Rectangle<float>& area)
{
composite->setContentArea (area);
composite->resetBoundingBoxToContentArea();
}
Rectangle<float> getContentArea() const
{
return composite->getContentArea();
}
const lunasvg::Document& document;
std::stack<State> state;
std::unique_ptr<DrawableComposite> composite = std::make_unique<DrawableComposite>();
DrawablePath* lastPath = nullptr;
std::optional<LunaSvgTextParameters> lastTextParams;
};
}
std::unique_ptr<DrawableComposite> Drawable::createFromSVGString (const String& svgString)
{
const auto document = lunasvg::Document::loadFromData (svgString.toStdString());
if (document == nullptr)
return {};
auto canvas = std::make_shared<DrawableCanvas> (document.get());
canvas->setContentArea ({ 0.0f, 0.0f, document->width(), document->height() });
document->renderToCanvas (canvas, lunasvg::Matrix());
return canvas->release();
}
//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS
struct SvgParserTests final : public UnitTest
{
SvgParserTests() : UnitTest ("SvgParser", UnitTestCategories::graphics)
{
}
void runTest() override
{
testCase ("Path parsing regression test", [this]
{
const auto juceLogoSvgPathString =
"m 72.87 84.28 c 49.518 84.341 30.521 65.492 30.4 42.14 30.756 18.936 49.668 "
"0.312 72.875 0.312 96.082 0.312 114.994 18.936 115.35 42.14 115.229 65.496 "
"96.226 84.346 72.87 84.28 z m 72.87 5.61 c 52.61 5.538 36.116 21.88 36 42.14 "
"36.332 62.269 52.744 78.412 72.875 78.412 93.006 78.412 109.418 62.269 109.75 "
"42.14 109.629 21.879 93.132 5.538 72.87 5.61 z m 77.62 49.59 c 80.16 56.066 "
"83.079 62.386 86.36 68.52 86.959 69.604 87.99 70.384 89.196 70.666 90.403 70.948 "
"91.672 70.706 92.69 70 96.165 67.569 99.162 64.518 101.53 61 102.279 59.861 "
"102.445 58.435 101.975 57.155 101.506 55.876 100.458 54.894 99.15 54.51 92.633 "
"52.485 86.239 50.084 80 47.32 79.342 47.029 78.573 47.163 78.052 47.66 77.531 "
"48.157 77.36 48.919 77.62 49.59 z m 81.05 44.27 c 87.597 47.162 94.32 49.637 "
"101.18 51.68 102.367 52.019 103.642 51.843 104.693 51.194 105.743 50.545 106.472 "
"49.483 106.7 48.27 107.066 46.247 107.25 44.196 107.25 42.14 107.251 39.883 "
"107.027 37.632 106.58 35.42 106.306 34.074 105.415 32.934 104.174 32.344 102.933 "
"31.754 101.487 31.782 100.27 32.42 94.041 35.627 87.642 38.491 81.1 41 80.426 "
"41.256 79.977 41.897 79.966 42.618 79.955 43.339 80.385 43.993 81.05 44.27 z m "
"74.47 50.44 c 74.195 49.774 73.545 49.34 72.825 49.34 72.105 49.34 71.455 49.774 "
"71.18 50.44 68.27 56.903 65.778 63.547 63.72 70.33 63.375 71.521 63.557 72.804 "
"64.221 73.852 64.884 74.9 65.965 75.613 67.19 75.81 69.068 76.115 70.967 76.269 "
"72.87 76.27 75.268 76.256 77.657 75.991 80 75.48 81.341 75.219 82.479 74.34 "
"83.07 73.109 83.661 71.877 83.635 70.439 83 69.23 79.814 63.128 76.967 56.855 "
"74.47 50.44 z m 71.59 34.12 c 71.855 34.79 72.498 35.234 73.218 35.245 73.939 "
"35.256 74.595 34.832 74.88 34.17 77.823 27.638 80.336 20.92 82.4 14.06 82.739 "
"12.88 82.563 11.612 81.915 10.57 81.267 9.527 80.208 8.808 79 8.59 74.674 7.83 "
"70.244 7.888 65.94 8.76 64.596 9.02 63.455 9.9 62.864 11.135 62.272 12.369 "
"62.301 13.81 62.94 15.02 66.176 21.221 69.063 27.598 71.59 34.12 z m 46.32 30.3 "
"c 53.132 32.387 59.811 34.885 66.32 37.78 66.98 38.068 67.748 37.931 68.267 "
"37.432 68.785 36.933 68.952 36.17 68.69 35.5 66.049 28.709 63.001 22.083 59.56 "
"15.66 58.959 14.577 57.928 13.8 56.721 13.52 55.515 13.239 54.247 13.483 53.23 "
"14.19 49.518 16.761 46.351 20.041 43.91 23.84 43.178 24.982 43.026 26.402 43.5 "
"27.672 43.974 28.943 45.019 29.917 46.32 30.3 z m 68.17 49.18 c 68.453 48.521 "
"68.311 47.756 67.809 47.243 67.307 46.73 66.545 46.571 65.88 46.84 59.209 49.394 "
"52.694 52.339 46.37 55.66 45.266 56.244 44.47 57.279 44.19 58.496 43.91 59.713 "
"44.173 60.992 44.91 62 47.459 65.53 50.656 68.544 54.33 70.88 55.475 71.608 "
"56.893 71.761 58.167 71.294 59.441 70.828 60.426 69.795 60.83 68.5 62.894 61.921 "
"65.345 55.47 68.17 49.18 z m 77.79 35.59 c 77.508 36.252 77.652 37.019 78.155 "
"37.533 78.659 38.047 79.422 38.208 80.09 37.94 86.792 35.368 93.337 32.403 99.69 "
"29.06 100.773 28.481 101.557 27.466 101.843 26.272 102.13 25.078 101.892 23.818 "
"101.19 22.81 98.669 19.188 95.474 16.085 91.78 13.67 90.639 12.925 89.216 12.756 "
"87.932 13.213 86.649 13.67 85.653 14.701 85.24 16 83.151 22.673 80.664 29.215 "
"77.79 35.59 z m 64.69 40.6 c 58.116 37.689 51.362 35.204 44.47 33.16 43.285 "
"32.828 42.014 33.012 40.972 33.667 39.931 34.323 39.214 35.388 39 36.6 38.698 "
"38.431 38.547 40.284 38.55 42.14 38.548 44.629 38.82 47.11 39.36 49.54 39.673 "
"50.851 40.576 51.944 41.804 52.499 43.032 53.055 44.448 53.011 45.64 52.38 "
"51.812 49.193 58.155 46.349 64.64 43.86 65.307 43.6 65.751 42.963 65.761 42.247 "
"65.772 41.531 65.349 40.88 64.69 40.6 z m 20 129.315 c 20 134.315 17.28 137.475 "
"12.89 137.475 10.52 137.475 8.72 136.475 6.69 133.915 l 6 133.135 -0 138.135 "
"0.57 138.895 c 3.82 143.255 7.73 145.285 12.88 145.285 21.88 145.285 28.22 "
"138.715 28.22 129.285 l 28.22 101.185 20 101.185 z m 61.69 126.505 c 61.69 "
"133.165 57.93 137.505 52.12 137.505 46.31 137.505 42.56 133.195 42.56 126.505 l "
"42.56 101.185 34.33 101.185 34.33 126.875 c 34.33 137.535 41.73 145.275 51.93 "
"145.275 61.93 145.275 69.54 137.555 69.93 126.875 l 69.93 101.185 61.69 101.185 "
"z m 106.83 134.095 c 103.25 136.525 100.65 137.475 97.58 137.475 89.933 136.983 "
"83.983 130.637 83.983 122.975 83.983 115.313 89.933 108.967 97.58 108.475 100.82 "
"108.475 103.24 109.355 106.83 111.855 l 107.59 112.385 112.37 106.385 111.62 "
"105.765 c 107.623 102.453 102.591 100.649 97.4 100.665 89.311 100.494 81.763 "
"104.711 77.669 111.689 73.574 118.667 73.574 127.313 77.669 134.291 81.763 "
"141.269 89.311 145.486 97.4 145.315 102.656 145.435 107.774 143.628 111.79 "
"140.235 l 112.6 139.595 107.6 133.595 z m 145.75 137.285 l 126.69 137.285 126.69 "
"126.565 144.99 126.565 144.99 118.955 126.69 118.955 126.69 108.795 145.75 "
"108.795 145.75 101.185 118.47 101.185 118.47 144.715 145.75 144.715 z m 68.015 "
"83.917 c 60.292 83.015 52.543 79.794 46.449 74.951 37.974 68.215 32.277 58.128 "
"30.875 47.376 29.303 35.31 33.538 22.7 42.21 13.631 49.154 6.368 58.07 1.902 "
"68.042 0.695 70.192 0.435 75.566 0.435 77.717 0.695 90.205 2.207 101.181 8.945 "
"108.154 19.381 116.486 31.852 117.472 47.504 110.759 60.749 108.479 65.249 "
"106.422 68.108 102.909 71.658 96.123 78.511 87.197 82.838 77.613 83.92 75.586 "
"84.147 69.969 84.145 68.015 83.917 z m 75.838 78.321 c 84.273 77.906 93.284 "
"73.643 99.521 67.116 105.497 60.862 108.871 53.393 109.702 44.579 110.334 37.874 "
"108.356 29.631 104.637 23.471 98.88 13.935 89.397 7.602 78.34 5.906 75.799 5.516 "
"69.942 5.52 67.38 5.912 53.54 8.034 42.185 17.542 37.81 30.67 35.003 39.096 "
"35.389 47.937 38.92 56.114 43.797 67.411 53.879 75.524 65.897 77.823 68.033 "
"78.231 71.997 78.578 73.274 78.468 73.599 78.44 74.754 78.374 75.838 78.321 z";
const auto juceLogoPathString =
"m 72.87 84.28 c 122.388 168.621 103.391 149.772 103.27 126.42 134.026 145.356 "
"152.938 126.732 176.145 126.732 272.227 127.044 291.139 145.668 291.495 168.872 "
"406.724 234.368 387.721 253.218 364.365 253.152 z m 145.74 89.89 c 198.35 95.428 "
"181.856 111.77 181.74 132.03 218.072 194.299 234.484 210.442 254.615 210.442 "
"347.621 288.854 364.033 272.711 364.365 252.582 473.994 274.461 457.497 258.12 "
"437.235 258.192 z m 223.36 139.48 c 303.52 195.546 306.439 201.866 309.72 208 "
"396.679 277.604 397.71 278.384 398.916 278.666 489.319 349.614 490.588 349.372 "
"491.606 348.666 587.771 416.235 590.768 413.184 593.136 409.666 695.415 469.527 "
"695.581 468.101 695.111 466.821 796.617 522.697 795.569 521.715 794.261 521.331 "
"886.894 573.816 880.5 571.415 874.261 568.651 953.603 615.68 952.834 615.814 "
"952.313 616.311 1029.844 664.468 1029.673 665.23 1029.933 665.901 z m 304.41 "
"183.75 c 392.007 230.912 398.73 233.387 405.59 235.43 507.957 287.449 509.232 "
"287.273 510.283 286.624 616.026 337.169 616.755 336.107 616.983 334.894 724.049 "
"381.141 724.233 379.09 724.233 377.034 831.484 416.917 831.26 414.666 830.813 "
"412.454 937.119 446.528 936.228 445.388 934.987 444.798 1037.92 476.552 1036.474 "
"476.58 1035.257 477.218 1129.298 512.845 1122.899 515.709 1116.357 518.218 "
"1196.783 559.474 1196.334 560.115 1196.323 560.836 1276.278 604.175 1276.708 "
"604.829 1277.373 605.106 z m 378.88 234.19 c 453.075 283.964 452.425 283.53 "
"451.705 283.53 523.81 332.87 523.16 333.304 522.885 333.97 591.155 390.873 "
"588.663 397.517 586.605 404.3 649.98 475.821 650.162 477.104 650.826 478.152 "
"715.71 553.052 716.791 553.765 718.016 553.962 787.084 630.077 788.983 630.231 "
"790.886 630.232 866.154 706.488 868.543 706.223 870.886 705.712 952.227 780.931 "
"953.365 780.052 953.956 778.821 1037.617 850.698 1037.591 849.26 1036.956 "
"848.051 1116.77 911.179 1113.923 904.906 1111.426 898.491 z m 450.47 268.31 c "
"522.325 303.1 522.968 303.544 523.688 303.555 597.627 338.811 598.283 338.387 "
"598.568 337.725 676.391 365.363 678.904 358.645 680.968 351.785 763.707 364.665 "
"763.531 363.397 762.883 362.355 844.15 371.882 843.091 371.163 841.883 370.945 "
"916.557 378.775 912.127 378.833 907.823 379.705 972.419 388.725 971.278 389.605 "
"970.687 390.84 1032.959 403.209 1032.988 404.65 1033.627 405.86 1099.803 427.081 "
"1102.69 433.458 1105.217 439.98 z m 496.79 298.61 c 549.922 330.997 556.601 "
"333.495 563.11 336.39 630.09 374.458 630.858 374.321 631.377 373.822 700.162 "
"410.755 700.329 409.992 700.067 409.322 766.116 438.031 763.068 431.405 759.627 "
"424.982 818.586 439.559 817.555 438.782 816.348 438.502 871.863 451.741 870.595 "
"451.985 869.578 452.692 919.096 469.453 915.929 472.733 913.488 476.532 956.666 "
"501.514 956.514 502.934 956.988 504.204 1000.962 533.147 1002.007 534.121 "
"1003.308 534.504 z m 564.96 347.79 c 633.413 396.311 633.271 395.546 632.769 "
"395.033 700.076 441.763 699.314 441.604 698.649 441.873 757.858 491.267 751.343 "
"494.212 745.019 497.533 790.285 553.777 789.489 554.812 789.209 556.029 833.119 "
"615.742 833.382 617.021 834.119 618.029 881.578 683.559 884.775 686.573 888.449 "
"688.909 943.924 760.517 945.342 760.67 946.616 760.203 1006.057 831.031 1007.042 "
"829.998 1007.446 828.703 1070.34 890.624 1072.791 884.173 1075.616 877.883 z m "
"642.75 383.38 c 720.258 419.632 720.402 420.399 720.905 420.913 799.564 458.96 "
"800.327 459.121 800.995 458.853 887.787 494.221 894.332 491.256 900.685 487.913 "
"1001.458 516.394 1002.242 515.379 1002.528 514.185 1104.658 539.263 1104.42 "
"538.003 1103.718 536.995 1202.387 556.183 1199.192 553.08 1195.498 550.665 "
"1286.137 563.59 1284.714 563.421 1283.43 563.878 1370.079 577.548 1369.083 "
"578.579 1368.67 579.878 1451.821 602.551 1449.334 609.093 1446.46 615.468 z m "
"707.44 423.98 c 765.556 461.669 758.802 459.184 751.91 457.14 795.195 489.968 "
"793.924 490.152 792.882 490.807 832.813 525.13 832.096 526.195 831.882 527.407 "
"870.58 565.838 870.429 567.691 870.432 569.547 908.98 614.176 909.252 616.657 "
"909.792 619.087 949.465 669.938 950.368 671.031 951.596 671.586 994.628 724.641 "
"996.044 724.597 997.236 723.966 1049.048 773.159 1055.391 770.315 1061.876 "
"767.826 1127.183 811.426 1127.627 810.789 1127.637 810.073 1193.409 851.604 "
"1192.986 850.953 1192.327 850.673 z m 727.44 553.295 c 747.44 687.61 744.72 "
"690.77 740.33 690.77 750.85 828.245 749.05 827.245 747.02 824.685 l 753.02 "
"957.82 753.02 1095.955 753.59 1234.85 c 757.41 1378.105 761.32 1380.135 766.47 "
"1380.135 788.35 1525.42 794.69 1518.85 794.69 1509.42 l 822.91 1610.605 842.91 "
"1711.79 z m 789.13 679.8 c 850.82 812.965 847.06 817.305 841.25 817.305 887.56 "
"954.81 883.81 950.5 883.81 943.81 l 926.37 1044.995 960.7 1146.18 995.03 "
"1273.055 c 1029.36 1410.59 1036.76 1418.33 1046.96 1418.33 1108.89 1563.605 "
"1116.5 1555.885 1116.89 1545.205 l 1186.82 1646.39 1248.51 1747.575 z m 895.96 "
"813.895 c 999.21 950.42 996.61 951.37 993.54 951.37 1083.473 1088.353 1077.523 "
"1082.007 1077.523 1074.345 1161.506 1189.658 1167.456 1183.312 1175.103 1182.82 "
"1275.923 1291.295 1278.343 1292.175 1281.933 1294.675 l 1389.523 1407.06 "
"1501.893 1513.445 1613.513 1619.21 c 1721.136 1721.663 1716.104 1719.859 "
"1710.913 1719.875 1800.224 1820.369 1792.676 1824.586 1788.582 1831.564 1862.156 "
"1950.231 1862.156 1958.877 1866.251 1965.855 1948.014 2107.124 1955.562 2111.341 "
"1963.651 2111.17 2066.307 2256.605 2071.425 2254.798 2075.441 2251.405 l "
"2188.041 2391 2295.641 2524.595 z m 1041.71 951.18 l 1168.4 1088.465 1295.09 "
"1215.03 1440.08 1341.595 1585.07 1460.55 1711.76 1579.505 1838.45 1688.3 1984.2 "
"1797.095 2129.95 1898.28 2248.42 1999.465 2366.89 2144.18 2512.64 2288.895 z m "
"1109.725 1035.097 c 1170.017 1118.112 1162.268 1114.891 1156.174 1110.048 "
"1194.148 1178.263 1188.451 1168.176 1187.049 1157.424 1216.352 1192.734 1220.587 "
"1180.124 1229.259 1171.055 1278.413 1177.423 1287.329 1172.957 1297.301 1171.75 "
"1367.493 1172.185 1372.867 1172.185 1375.018 1172.445 1465.223 1174.652 1476.199 "
"1181.39 1483.172 1191.826 1599.658 1223.678 1600.644 1239.33 1593.931 1252.575 "
"1702.41 1317.824 1700.353 1320.683 1696.84 1324.233 1792.963 1402.744 1784.037 "
"1407.071 1774.453 1408.153 1850.039 1492.3 1844.422 1492.298 1842.468 1492.07 z "
"m 1185.563 1113.418 c 1269.836 1191.324 1278.847 1187.061 1285.084 1180.534 "
"1390.581 1241.396 1393.955 1233.927 1394.786 1225.113 1505.12 1262.987 1503.142 "
"1254.744 1499.423 1248.584 1598.303 1262.519 1588.82 1256.186 1577.763 1254.49 "
"1653.562 1260.006 1647.705 1260.01 1645.143 1260.402 1698.683 1268.436 1687.328 "
"1277.944 1682.953 1291.072 1717.956 1330.168 1718.342 1339.009 1721.873 1347.186 "
"1765.67 1414.597 1775.752 1422.71 1787.77 1425.009 1855.803 1503.24 1859.767 "
"1503.587 1861.044 1503.477 1934.643 1581.917 1935.798 1581.851 1936.882 1581.798 z";
expect (Drawable::parseSVGPath (juceLogoSvgPathString).toString() == juceLogoPathString);
});
}
};
static SvgParserTests svgParserTests;
#endif
} // namespace juce
@@ -0,0 +1,54 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
bool StrokeOptions::operator== (const StrokeOptions& other) const noexcept
{
const auto tie = [] (auto& x)
{
return std::tie (x.colour,
x.dashArray,
x.dashOffset,
x.lineCap,
x.lineJoin,
x.miterLimit,
x.width);
};
return tie (*this) == tie (other);
}
} // namespace juce
@@ -0,0 +1,129 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
/** The set of SVG stroke attributes. */
class JUCE_API StrokeOptions
{
public:
/** Returns a copy of these attributes with a new colour. */
[[nodiscard]] StrokeOptions withColour (Colour x) const
{
return withMember (*this, &StrokeOptions::colour, x);
}
/** Returns a copy of these attributes with a new dash array. */
[[nodiscard]] StrokeOptions withDashArray (Span<const float> x) const
{
std::vector<float> arr (x.begin(), x.end());
return withMember (*this, &StrokeOptions::dashArray, std::move (arr));
}
/** Returns a copy of these attributes with a new dash offset. */
[[nodiscard]] StrokeOptions withDashOffset (float x) const
{
return withMember (*this, &StrokeOptions::dashOffset, x);
}
/** Returns a copy of these attributes with a new line cap style. */
[[nodiscard]] StrokeOptions withLineCap (PathStrokeType::EndCapStyle x) const
{
return withMember (*this, &StrokeOptions::lineCap, x);
}
/** Returns a copy of these attributes with a new line join style. */
[[nodiscard]] StrokeOptions withLineJoin (PathStrokeType::JointStyle x) const
{
return withMember (*this, &StrokeOptions::lineJoin, x);
}
/** Returns a copy of these attributes with a new miter limit. */
[[nodiscard]] StrokeOptions withMiterLimit (float x) const
{
return withMember (*this, &StrokeOptions::miterLimit, x);
}
/** Returns a copy of these attributes with a new stroke width. */
[[nodiscard]] StrokeOptions withWidth (float x) const
{
return withMember (*this, &StrokeOptions::width, x);
}
/** @see withColour() */
const auto& getColour() const { return colour; }
/** @see withDashArray() */
Span<const float> getDashArray() const { return dashArray; }
/** @see withDashOffset() */
const auto& getDashOffset() const { return dashOffset; }
/** @see withLineCap() */
const auto& getLineCap() const { return lineCap; }
/** @see withLineJoin() */
const auto& getLineJoin() const { return lineJoin; }
/** @see withMiterLimit() */
const auto& getMiterLimit() const { return miterLimit; }
/** @see withWidth() */
const auto& getWidth() const { return width; }
/** Creates a PathStrokeType object based on the current attributes. */
PathStrokeType createStrokeType() const
{
PathStrokeType type { width, lineJoin, lineCap };
type.setMiterLimit (miterLimit);
return type;
}
/** Equality operator. */
bool operator== (const StrokeOptions& other) const noexcept;
/** Inequality operator. */
bool operator!= (const StrokeOptions& other) const noexcept { return ! operator== (other); }
private:
Colour colour = Colours::black; // A combination of the 'stroke' and 'opacity' attributes.
std::vector<float> dashArray;
float dashOffset{};
PathStrokeType::EndCapStyle lineCap = PathStrokeType::EndCapStyle::butt;
PathStrokeType::JointStyle lineJoin = PathStrokeType::JointStyle::mitered;
float miterLimit = 4.0f;
float width = 1.0f;
};
} // namespace juce
@@ -0,0 +1,96 @@
Upstream: https://github.com/sammycage/lunasvg
The files in this directory are from the LunaSVG 3.5.0 release downloaded in a tarball from
https://github.com/sammycage/lunasvg/releases/tag/v3.5.0
First a script was used to modify them as little as possible to enable us building them in the
JUCE module structure, as well as to hide the LunaSVG symbols and rename the PlutoVG symbols. The
latter modification is needed to allow JUCE projects to use LunaSVG as a separate dependency. The
script is shown at the end of this file.
In separate commits a number of manual changes were added that allow us to replace LunaSVG's
built-in renderer and use a JUCE Drawable hierarchy instead. These changes are in commits with the
"lunasvg:" prefix.
In a commit with "lunasvg:" prefix, a fix was applied to allow compilation with Xcode 12.4.
In a commit with the "plutovg:" prefix, we turned off the optimisations for
the `juce_plutovg_font_face_cache_load_file` function under MSVC. Without this change an internal
compiler error occurs when building the file in Release mode.
```
#!/bin/bash
# During a lunasvg version bump, this script must be placed in the
# drawables/lunasvg directory and executed.
if [[ "$(uname)" != "Darwin" ]]; then
echo "This script only works on macOS."
exit 1
fi
SELF_DIR="$(cd "$(dirname "$0")" && pwd)" || { echo "Error: cannot determine script directory" >&2; exit 1; }
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# Wrap lunasvg code in an anonymous namespace
find "$SELF_DIR/source" -type f \( -name '*.cpp' -o -name '*.h' -o -name '*.hpp' \) | while read -r file; do
last_include=$(grep -n '#include' "$file" | tail -1 | cut -d: -f1)
if [ -z "$last_include" ]; then
echo "Skipping $file (no #include found)"
continue
fi
closing_line=$(grep -n '} // namespace lunasvg' "$file" | tail -1 | cut -d: -f1)
if [ -z "$closing_line" ]; then
echo "Skipping $file (no '} // namespace lunasvg' found)"
continue
fi
sed -i '' "${last_include}a\\
namespace {
" "$file"
closing_line=$((closing_line + 1))
sed -i '' "${closing_line}a\\
}
" "$file"
echo "Processed $file"
done
# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# Wrap lunasvg.h public namespace in an anonymous namespace
file="$SELF_DIR/include/lunasvg.h"
first_namespace=$(grep -n 'namespace lunasvg {' "$file" | head -1 | cut -d: -f1)
last_closing=$(grep -n '} // namespace lunasvg' "$file" | tail -1 | cut -d: -f1)
if [ -n "$first_namespace" ] && [ -n "$last_closing" ]; then
sed -i '' "${first_namespace}i\\
namespace {
" "$file"
last_closing=$((last_closing + 1))
sed -i '' "${last_closing}a\\
}
" "$file"
echo "Processed $file"
else
echo "Skipping $file (namespace markers not found)"
fi
# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# Prefix all plutovg symbols with juce_ to avoid collisions
find "$SELF_DIR" -type f \( -name '*.c' -o -name '*.cpp' -o -name '*.h' -o -name '*.hpp' \) | while read -r file; do
sed -i '' 's/plutovg_/juce_plutovg_/g; s/PLUTOVG_/JUCE_PLUTOVG_/g' "$file"
echo "Replaced plutovg_ in $file"
done
# <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
```
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-2025 Samuel Ugochukwu <sammycageagle@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,808 @@
/*
* Copyright (c) 2020-2025 Samuel Ugochukwu <sammycageagle@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef LUNASVG_H
#define LUNASVG_H
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#if defined(LUNASVG_BUILD_STATIC)
#define LUNASVG_EXPORT
#define LUNASVG_IMPORT
#elif (defined(_WIN32) || defined(__CYGWIN__))
#define LUNASVG_EXPORT __declspec(dllexport)
#define LUNASVG_IMPORT __declspec(dllimport)
#elif defined(__GNUC__) && (__GNUC__ >= 4)
#define LUNASVG_EXPORT __attribute__((__visibility__("default")))
#define LUNASVG_IMPORT
#else
#define LUNASVG_EXPORT
#define LUNASVG_IMPORT
#endif
#ifdef LUNASVG_BUILD
#define LUNASVG_API LUNASVG_EXPORT
#else
#define LUNASVG_API LUNASVG_IMPORT
#endif
#define LUNASVG_VERSION_MAJOR 3
#define LUNASVG_VERSION_MINOR 5
#define LUNASVG_VERSION_MICRO 0
#define LUNASVG_VERSION_ENCODE(major, minor, micro) (((major) * 10000) + ((minor) * 100) + ((micro) * 1))
#define LUNASVG_VERSION LUNASVG_VERSION_ENCODE(LUNASVG_VERSION_MAJOR, LUNASVG_VERSION_MINOR, LUNASVG_VERSION_MICRO)
#define LUNASVG_VERSION_XSTRINGIZE(major, minor, micro) #major"."#minor"."#micro
#define LUNASVG_VERSION_STRINGIZE(major, minor, micro) LUNASVG_VERSION_XSTRINGIZE(major, minor, micro)
#define LUNASVG_VERSION_STRING LUNASVG_VERSION_STRINGIZE(LUNASVG_VERSION_MAJOR, LUNASVG_VERSION_MINOR, LUNASVG_VERSION_MICRO)
#ifdef __cplusplus
extern "C" {
#endif
typedef struct juce_plutovg_surface juce_plutovg_surface_t;
typedef struct juce_plutovg_matrix juce_plutovg_matrix_t;
/**
* @brief Callback for cleaning up resources.
*
* This function is called to release resources associated with a specific operation.
*
* @param closure A user-defined pointer to the resource or context to be freed.
*/
typedef void (*lunasvg_destroy_func_t)(void* closure);
/**
* @brief A function pointer type for a write callback.
* @param closure A pointer to user-defined data or context.
* @param data A pointer to the data to be written.
* @param size The size of the data in bytes.
*/
typedef void (*lunasvg_write_func_t)(void* closure, void* data, int size);
/**
* @brief Returns the version of the lunasvg library encoded in a single integer.
*
* Encodes the version of the lunasvg library into a single integer for easier comparison.
* The version is typically represented by combining major, minor, and patch numbers into one integer.
*
* @return The lunasvg library version as a single integer.
*/
LUNASVG_API int lunasvg_version(void);
/**
* @brief Returns the lunasvg library version as a human-readable string in "X.Y.Z" format.
*
* Provides the version of the lunasvg library as a human-readable string in the format "X.Y.Z",
* where X represents the major version, Y the minor version, and Z the patch version.
*
* @return A pointer to a string containing the version in "X.Y.Z" format.
*/
LUNASVG_API const char* lunasvg_version_string(void);
/**
* @brief Add a font face from a file to the cache.
* @param family The name of the font family. If an empty string is provided, the font will act as a fallback.
* @param bold Use `true` for bold, `false` otherwise.
* @param italic Use `true` for italic, `false` otherwise.
* @param filename The path to the font file.
* @return `true` if the font face was successfully added to the cache, `false` otherwise.
*/
LUNASVG_API bool lunasvg_add_font_face_from_file(const char* family, bool bold, bool italic, const char* filename);
/**
* @brief Add a font face from memory to the cache.
* @param family The name of the font family. If an empty string is provided, the font will act as a fallback.
* @param bold Use `true` for bold, `false` otherwise.
* @param italic Use `true` for italic, `false` otherwise.
* @param data A pointer to the memory buffer containing the font data.
* @param length The size of the memory buffer in bytes.
* @param destroy_func Callback function to free the memory buffer when it is no longer needed.
* @param closure User-defined pointer passed to the `destroy_func` callback.
* @return `true` if the font face was successfully added to the cache, `false` otherwise.
*/
LUNASVG_API bool lunasvg_add_font_face_from_data(const char* family, bool bold, bool italic, const void* data, size_t length, lunasvg_destroy_func_t destroy_func, void* closure);
#ifdef __cplusplus
}
#endif
namespace {
namespace lunasvg {
/**
* @note Bitmap pixel format is ARGB32_Premultiplied.
*/
class LUNASVG_API Bitmap {
public:
/**
* @brief Constructs a null bitmap.
*/
Bitmap() = default;
/**
* @brief Constructs a bitmap with the specified width and height.
* @note A null bitmap will be returned if memory cannot be allocated.
* @param width The width of the bitmap in pixels.
* @param height The height of the bitmap in pixels.
*/
Bitmap(int width, int height);
/**
* @brief Constructs a bitmap with the provided pixel data, width, height, and stride.
*
* @param data A pointer to the raw pixel data in ARGB32 Premultiplied format.
* @param width The width of the bitmap in pixels.
* @param height The height of the bitmap in pixels.
* @param stride The number of bytes per row of pixel data (stride).
*/
Bitmap(uint8_t* data, int width, int height, int stride);
/**
* @brief Copy constructor.
* @param bitmap The bitmap to copy.
*/
Bitmap(const Bitmap& bitmap);
/**
* @brief Move constructor.
* @param bitmap The bitmap to move.
*/
Bitmap(Bitmap&& bitmap);
/**
* @internal
*/
Bitmap(juce_plutovg_surface_t* surface) : m_surface(surface) {}
/**
* @brief Cleans up any resources associated with the bitmap.
*/
~Bitmap();
/**
* @brief Copy assignment operator.
* @param bitmap The bitmap to copy.
* @return A reference to this bitmap.
*/
Bitmap& operator=(const Bitmap& bitmap);
/**
* @brief Move assignment operator.
* @param bitmap The bitmap to move.
* @return A reference to this bitmap.
*/
Bitmap& operator=(Bitmap&& bitmap);
/**
* @brief Swaps the content of this bitmap with another.
* @param bitmap The bitmap to swap with.
*/
void swap(Bitmap& bitmap);
/**
* @brief Gets the pointer to the raw pixel data.
* @return A pointer to the raw pixel data.
*/
uint8_t* data() const;
/**
* @brief Gets the width of the bitmap.
* @return The width of the bitmap in pixels.
*/
int width() const;
/**
* @brief Gets the height of the bitmap.
* @return The height of the bitmap in pixels.
*/
int height() const;
/**
* @brief Gets the stride of the bitmap.
* @return The number of bytes per row of pixel data (stride).
*/
int stride() const;
/**
* @brief Clears the bitmap with the specified color.
* @param The color value in 0xRRGGBBAA format.
*/
void clear(uint32_t value);
/**
* @brief Converts the bitmap pixel data from ARGB32 Premultiplied to RGBA Plain format in place.
*/
void convertToRGBA();
/**
* @brief Checks if the bitmap is null.
* @return True if the bitmap is null, false otherwise.
*/
bool isNull() const { return m_surface == nullptr; }
/**
* @brief Checks if the bitmap is valid.
* @deprecated This function has been deprecated. Use `isNull()` instead to check whether the bitmap is null.
* @return True if the bitmap is valid, false otherwise.
*/
bool valid() const { return !isNull(); }
/**
* @brief Writes the bitmap to a PNG file.
* @param filename The name of the file to write.
* @return True if the file was written successfully, false otherwise.
*/
bool writeToPng(const std::string& filename) const;
/**
* @brief Writes the bitmap to a PNG stream.
* @param callback Callback function for writing data.
* @param closure User-defined data passed to the callback.
* @return True if successful, false otherwise.
*/
bool writeToPng(lunasvg_write_func_t callback, void* closure) const;
/**
* @internal
*/
juce_plutovg_surface_t* surface() const { return m_surface; }
private:
juce_plutovg_surface_t* release();
juce_plutovg_surface_t* m_surface{nullptr};
};
class Rect;
class Matrix;
/**
* @brief Represents a 2D axis-aligned bounding box.
*/
class LUNASVG_API Box {
public:
/**
* @brief Constructs a box with zero dimensions.
*/
Box() = default;
/**
* @brief Constructs a box with the specified position and size.
* @param x The x-coordinate of the box's origin.
* @param y The y-coordinate of the box's origin.
* @param w The width of the box.
* @param h The height of the box.
*/
Box(float x, float y, float w, float h);
/**
* @internal
*/
Box(const Rect& rect);
/**
* @brief Transforms the box using the specified matrix.
* @param matrix The transformation matrix.
* @return A reference to this box, modified by the transformation.
*/
Box& transform(const Matrix& matrix);
/**
* @brief Returns a new box transformed by the specified matrix.
* @param matrix The transformation matrix.
* @return A new box, transformed by the matrix.
*/
Box transformed(const Matrix& matrix) const;
float x{0}; ///< The x-coordinate of the box's origin.
float y{0}; ///< The y-coordinate of the box's origin.
float w{0}; ///< The width of the box.
float h{0}; ///< The height of the box.
};
class Transform;
/**
* @brief Represents a 2D transformation matrix.
*/
class LUNASVG_API Matrix {
public:
/**
* @brief Initializes the matrix to the identity matrix.
*/
Matrix() = default;
/**
* @brief Constructs a matrix with the specified values.
* @param a The horizontal scaling factor.
* @param b The vertical shearing factor.
* @param c The horizontal shearing factor.
* @param d The vertical scaling factor.
* @param e The horizontal translation offset.
* @param f The vertical translation offset.
*/
Matrix(float a, float b, float c, float d, float e, float f);
/**
* @internal
*/
Matrix(const juce_plutovg_matrix_t& matrix);
/**
* @internal
*/
Matrix(const Transform& transform);
/**
* @brief Multiplies this matrix with another matrix.
* @param matrix The matrix to multiply with.
* @return A new matrix that is the result of the multiplication.
*/
Matrix operator*(const Matrix& matrix) const;
/**
* @brief Multiplies this matrix with another matrix in place.
* @param matrix The matrix to multiply with.
* @return A reference to this matrix after multiplication.
*/
Matrix& operator*=(const Matrix& matrix);
/**
* @brief Multiplies this matrix with another matrix.
* @param matrix The matrix to multiply with.
* @return A reference to this matrix after multiplication.
*/
Matrix& multiply(const Matrix& matrix);
/**
* @brief Translates this matrix by the specified offsets.
* @param tx The horizontal translation offset.
* @param ty The vertical translation offset.
* @return A reference to this matrix after translation.
*/
Matrix& translate(float tx, float ty);
/**
* @brief Scales this matrix by the specified factors.
* @param sx The horizontal scaling factor.
* @param sy The vertical scaling factor.
* @return A reference to this matrix after scaling.
*/
Matrix& scale(float sx, float sy);
/**
* @brief Rotates this matrix by the specified angle around a point.
* @param angle The rotation angle in degrees.
* @param cx The x-coordinate of the center of rotation.
* @param cy The y-coordinate of the center of rotation.
* @return A reference to this matrix after rotation.
*/
Matrix& rotate(float angle, float cx = 0.f, float cy = 0.f);
/**
* @brief Shears this matrix by the specified factors.
* @param shx The horizontal shearing factor.
* @param shy The vertical shearing factor.
* @return A reference to this matrix after shearing.
*/
Matrix& shear(float shx, float shy);
/**
* @brief Inverts this matrix.
* @return A reference to this matrix after inversion.
*/
Matrix& invert();
/**
* @brief Returns the inverse of this matrix.
* @return A new matrix that is the inverse of this matrix.
*/
Matrix inverse() const;
/**
* @brief Resets this matrix to the identity matrix.
*/
void reset();
/**
* @brief Creates a translation matrix with the specified offsets.
* @param tx The horizontal translation offset.
* @param ty The vertical translation offset.
* @return A new translation matrix.
*/
static Matrix translated(float tx, float ty);
/**
* @brief Creates a scaling matrix with the specified factors.
* @param sx The horizontal scaling factor.
* @param sy The vertical scaling factor.
* @return A new scaling matrix.
*/
static Matrix scaled(float sx, float sy);
/**
* @brief Creates a rotation matrix with the specified angle around a point.
* @param angle The rotation angle in degrees.
* @param cx The x-coordinate of the center of rotation.
* @param cy The y-coordinate of the center of rotation.
* @return A new rotation matrix.
*/
static Matrix rotated(float angle, float cx = 0.f, float cy = 0.f);
/**
* @brief Creates a shearing matrix with the specified factors.
* @param shx The horizontal shearing factor.
* @param shy The vertical shearing factor.
* @return A new shearing matrix.
*/
static Matrix sheared(float shx, float shy);
float a{1}; ///< The horizontal scaling factor.
float b{0}; ///< The vertical shearing factor.
float c{0}; ///< The horizontal shearing factor.
float d{1}; ///< The vertical scaling factor.
float e{0}; ///< The horizontal translation offset.
float f{0}; ///< The vertical translation offset.
};
class SVGNode;
class SVGTextNode;
class SVGElement;
class Element;
class TextNode;
class LUNASVG_API Node {
public:
/**
* @brief Constructs a null node.
*/
Node() = default;
/**
* @brief Checks if the node is a text node.
* @return True if the node is a text node, false otherwise.
*/
bool isTextNode() const;
/**
* @brief Checks if the node is an element node.
* @return True if the node is an element node, false otherwise.
*/
bool isElement() const;
/**
* @brief Converts the node to a TextNode.
* @return A TextNode or a null node if conversion is not possible.
*/
TextNode toTextNode() const;
/**
* @brief Converts the node to an Element.
* @return An Element or a null node if conversion is not possible.
*/
Element toElement() const;
/**
* @brief Returns the parent element.
* @return The parent element of this node. If this node has no parent, a null `Element` is returned.
*/
Element parentElement() const;
/**
* @brief Checks if the node is null.
* @return True if the node is null, false otherwise.
*/
bool isNull() const { return m_node == nullptr; }
/**
* @brief Checks if the node is not null.
* @return True if the node is not null, false otherwise.
*/
operator bool() const { return !isNull(); }
/**
* @brief Checks if two nodes are equal.
* @param element The node to compare.
* @return True if equal, otherwise false.
*/
bool operator==(const Node& node) const { return m_node == node.m_node; }
/**
* @brief Checks if two nodes are not equal.
* @param element The node to compare.
* @return True if not equal, otherwise false.
*/
bool operator!=(const Node& node) const { return m_node != node.m_node; }
protected:
Node(SVGNode* node);
SVGNode* node() const { return m_node; }
SVGNode* m_node{nullptr};
friend class Element;
};
using NodeList = std::vector<Node>;
class LUNASVG_API TextNode : public Node {
public:
/**
* @brief Constructs a null text node.
*/
TextNode() = default;
/**
* @brief Returns the text content of the node.
* @return A string representing the text content.
*/
const std::string& data() const;
/**
* @brief Sets the text content of the node.
* @param data The new text content to set.
*/
void setData(const std::string& data);
private:
TextNode(SVGTextNode* text);
SVGTextNode* text() const;
friend class Node;
};
class LUNASVG_API Element : public Node {
public:
/**
* @brief Constructs a null element.
*/
Element() = default;
/**
* @brief Checks if the element has a specific attribute.
* @param name The name of the attribute to check.
* @return True if the element has the specified attribute, false otherwise.
*/
bool hasAttribute(const std::string& name) const;
/**
* @brief Retrieves the value of an attribute.
* @param name The name of the attribute to retrieve.
* @return The value of the attribute as a string.
*/
const std::string& getAttribute(const std::string& name) const;
/**
* @brief Sets the value of an attribute.
* @param name The name of the attribute to set.
* @param value The value to assign to the attribute.
*/
void setAttribute(const std::string& name, const std::string& value);
/**
* @brief Renders the element onto a bitmap using a transformation matrix.
* @param bitmap The bitmap to render onto.
* @param The root transformation matrix.
*/
void render(Bitmap& bitmap, const Matrix& matrix = Matrix()) const;
/**
* @brief Renders the element to a bitmap with specified dimensions.
* @param width The desired width in pixels, or -1 to auto-scale based on the intrinsic size.
* @param height The desired height in pixels, or -1 to auto-scale based on the intrinsic size.
* @param backgroundColor The background color in 0xRRGGBBAA format.
* @return A Bitmap containing the raster representation of the element.
*/
Bitmap renderToBitmap(int width = -1, int height = -1, uint32_t backgroundColor = 0x00000000) const;
/**
* @brief Retrieves the local transformation matrix of the element.
* @return The matrix that applies only to the element, relative to its parent.
*/
Matrix getLocalMatrix() const;
/**
* @brief Retrieves the global transformation matrix of the element.
* @return The matrix combining the element's local and all parent transformations.
*/
Matrix getGlobalMatrix() const;
/**
* @brief Retrieves the local bounding box of the element.
* @return A Box representing the bounding box after applying local transformations.
*/
Box getLocalBoundingBox() const;
/**
* @brief Retrieves the global bounding box of the element.
* @return A Box representing the bounding box after applying global transformations.
*/
Box getGlobalBoundingBox() const;
/**
* @brief Retrieves the bounding box of the element without any transformations.
* @return A Box representing the bounding box of the element without any transformations applied.
*/
Box getBoundingBox() const;
/**
* @brief Returns the child nodes of this node.
* @return A NodeList containing the child nodes.
*/
NodeList children() const;
private:
Element(SVGElement* element);
SVGElement* element(bool layoutIfNeeded = false) const;
friend class Node;
friend class Document;
};
using ElementList = std::vector<Element>;
class SVGRootElement;
class Canvas;
class LUNASVG_API Document {
public:
/**
* @brief Load an SVG document from a file.
* @param filename The path to the SVG file.
* @return A pointer to the loaded `Document`, or `nullptr` on failure.
*/
static std::unique_ptr<Document> loadFromFile(const std::string& filename);
/**
* @brief Load an SVG document from a string.
* @param string The SVG data as a string.
* @return A pointer to the loaded `Document`, or `nullptr` on failure.
*/
static std::unique_ptr<Document> loadFromData(const std::string& string);
/**
* @brief Load an SVG document from a null-terminated string.
* @param data The string containing the SVG data.
* @return A pointer to the loaded `Document`, or `nullptr` on failure.
*/
static std::unique_ptr<Document> loadFromData(const char* data);
/**
* @brief Load an SVG document from a string with a specified length.
* @param data The string containing the SVG data.
* @param length The length of the string in bytes.
* @return A pointer to the loaded `Document`, or `nullptr` on failure.
*/
static std::unique_ptr<Document> loadFromData(const char* data, size_t length);
/**
* @brief Applies a CSS stylesheet to the document.
* @param content A string containing the CSS rules to apply, with comments removed.
*/
void applyStyleSheet(const std::string& content);
/**
* @brief Selects all elements that match the given CSS selector(s).
* @param content A string containing the CSS selector(s) to match elements.
* @return A list of elements matching the selector(s).
*/
ElementList querySelectorAll(const std::string& content) const;
/**
* @brief Returns the intrinsic width of the document in pixels.
* @return The width of the document.
*/
float width() const;
/**
* @brief Returns the intrinsic height of the document in pixels.
* @return The height of the document.
*/
float height() const;
/**
* @brief Returns the smallest rectangle that encloses the document content.
* @return A Box representing the bounding box of the document.
*/
Box boundingBox() const;
/**
* @brief Updates the layout of the document if needed.
*/
void updateLayout();
/**
* @brief Forces an immediate layout update.
*/
void forceLayout();
void renderToCanvas(std::shared_ptr<Canvas> canvas, const Matrix& matrix) const;
/**
* @brief Renders the document onto a bitmap using a transformation matrix.
* @param bitmap The bitmap to render onto.
* @param The root transformation matrix.
*/
void render(Bitmap& bitmap, const Matrix& matrix = Matrix()) const;
/**
* @brief Renders the document to a bitmap with specified dimensions.
* @param width The desired width in pixels, or -1 to auto-scale based on the intrinsic size.
* @param height The desired height in pixels, or -1 to auto-scale based on the intrinsic size.
* @param backgroundColor The background color in 0xRRGGBBAA format.
* @return A Bitmap containing the raster representation of the document.
*/
Bitmap renderToBitmap(int width = -1, int height = -1, uint32_t backgroundColor = 0x00000000) const;
/**
* @brief Returns the topmost element under the specified point.
* @param x The x-coordinate in viewport space.
* @param y The y-coordinate in viewport space.
* @return The topmost Element at the given point, or a null `Element` if no match is found.
*/
Element elementFromPoint(float x, float y) const;
/**
* @brief Retrieves an element by its ID.
* @param id The ID of the element to retrieve.
* @return The Element with the specified ID, or a null `Element` if not found.
*/
Element getElementById(const std::string& id) const;
/**
* @brief Retrieves the document element.
* @return The root Element of the document.
*/
Element documentElement() const;
const std::string& getElementIdBeingRendered() const
{
return elementIdBeingRendered;
}
std::string setElementIdBeingRendered (const std::string& eId)
{
return std::exchange (elementIdBeingRendered, eId);
}
Document(Document&&);
Document& operator=(Document&&);
~Document();
private:
Document();
Document(const Document&) = delete;
Document& operator=(const Document&) = delete;
SVGRootElement* rootElement(bool layoutIfNeeded = false) const;
bool parse(const char* data, size_t length);
std::unique_ptr<SVGRootElement> m_rootElement;
friend class SVGURIReference;
friend class SVGNode;
std::string elementIdBeingRendered;
};
} // namespace lunasvg
}
#endif // LUNASVG_H
@@ -0,0 +1,3 @@
# These are supported funding model platforms
github: sammycage
@@ -0,0 +1,57 @@
name: Build
on: [push, pull_request]
jobs:
linux:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Build with meson
run: |
pip install meson
pip install ninja
meson setup build
meson compile -C build
- name: Build with cmake
run: |
cmake .
cmake --build .
macos:
runs-on: macos-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Build with meson
run: |
pip install meson
pip install ninja
meson setup build
meson compile -C build
- name: Build with cmake
run: |
cmake .
cmake --build .
windows:
runs-on: windows-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Build with meson
run: |
pip install meson
pip install ninja
meson setup build
meson compile -C build
- name: Build with cmake
run: |
cmake .
cmake --build .
@@ -0,0 +1,2 @@
/build
*.user
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-2025 Samuel Ugochukwu <sammycageagle@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,166 @@
The FreeType Project LICENSE
----------------------------
2006-Jan-27
Copyright 1996-2002, 2006 by
David Turner, Robert Wilhelm, and Werner Lemberg
Introduction
============
The FreeType Project is distributed in several archive packages;
some of them may contain, in addition to the FreeType font engine,
various tools and contributions which rely on, or relate to, the
FreeType Project.
This license applies to all files found in such packages, and
which do not fall under their own explicit license. The license
affects thus the FreeType font engine, the test programs,
documentation and makefiles, at the very least.
This license was inspired by the BSD, Artistic, and IJG
(Independent JPEG Group) licenses, which all encourage inclusion
and use of free software in commercial and freeware products
alike. As a consequence, its main points are that:
o We don't promise that this software works. However, we will be
interested in any kind of bug reports. (`as is' distribution)
o You can use this software for whatever you want, in parts or
full form, without having to pay us. (`royalty-free' usage)
o You may not pretend that you wrote this software. If you use
it, or only parts of it, in a program, you must acknowledge
somewhere in your documentation that you have used the
FreeType code. (`credits')
We specifically permit and encourage the inclusion of this
software, with or without modifications, in commercial products.
We disclaim all warranties covering The FreeType Project and
assume no liability related to The FreeType Project.
Finally, many people asked us for a preferred form for a
credit/disclaimer to use in compliance with this license. We thus
encourage you to use the following text:
"""
Portions of this software are copyright � <year> The FreeType
Project (www.freetype.org). All rights reserved.
"""
Please replace <year> with the value from the FreeType version you
actually use.
Legal Terms
===========
0. Definitions
--------------
Throughout this license, the terms `package', `FreeType Project',
and `FreeType archive' refer to the set of files originally
distributed by the authors (David Turner, Robert Wilhelm, and
Werner Lemberg) as the `FreeType Project', be they named as alpha,
beta or final release.
`You' refers to the licensee, or person using the project, where
`using' is a generic term including compiling the project's source
code as well as linking it to form a `program' or `executable'.
This program is referred to as `a program using the FreeType
engine'.
This license applies to all files distributed in the original
FreeType Project, including all source code, binaries and
documentation, unless otherwise stated in the file in its
original, unmodified form as distributed in the original archive.
If you are unsure whether or not a particular file is covered by
this license, you must contact us to verify this.
The FreeType Project is copyright (C) 1996-2000 by David Turner,
Robert Wilhelm, and Werner Lemberg. All rights reserved except as
specified below.
1. No Warranty
--------------
THE FREETYPE PROJECT IS PROVIDED `AS IS' WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY DAMAGES CAUSED BY THE USE OR THE INABILITY TO
USE, OF THE FREETYPE PROJECT.
2. Redistribution
-----------------
This license grants a worldwide, royalty-free, perpetual and
irrevocable right and license to use, execute, perform, compile,
display, copy, create derivative works of, distribute and
sublicense the FreeType Project (in both source and object code
forms) and derivative works thereof for any purpose; and to
authorize others to exercise some or all of the rights granted
herein, subject to the following conditions:
o Redistribution of source code must retain this license file
(`FTL.TXT') unaltered; any additions, deletions or changes to
the original files must be clearly indicated in accompanying
documentation. The copyright notices of the unaltered,
original files must be preserved in all copies of source
files.
o Redistribution in binary form must provide a disclaimer that
states that the software is based in part of the work of the
FreeType Team, in the distribution documentation. We also
encourage you to put an URL to the FreeType web page in your
documentation, though this isn't mandatory.
These conditions apply to any software derived from or based on
the FreeType Project, not just the unmodified files. If you use
our work, you must acknowledge us. However, no fee need be paid
to us.
3. Advertising
--------------
Neither the FreeType authors and contributors nor you shall use
the name of the other for commercial, advertising, or promotional
purposes without specific prior written permission.
We suggest, but do not require, that you use one or more of the
following phrases to refer to this software in your documentation
or advertising materials: `FreeType Project', `FreeType Engine',
`FreeType library', or `FreeType Distribution'.
As you have not signed this license, you are not required to
accept it. However, as the FreeType Project is copyrighted
material, only this license, or another one contracted with the
authors, grants you the right to use, distribute, and modify it.
Therefore, by using, distributing, or modifying the FreeType
Project, you indicate that you understand and accept all the terms
of this license.
4. Contacts
-----------
There are two mailing lists related to FreeType:
o freetype@nongnu.org
Discusses general use and applications of FreeType, as well as
future and wanted additions to the library and distribution.
If you are looking for support, start in this list if you
haven't found anything to help you in the documentation.
o freetype-devel@nongnu.org
Discusses bugs, as well as engine internals, design issues,
specific licenses, porting, etc.
Our home page can be found at
http://www.freetype.org
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,759 @@
#include "plutovg-private.h"
#include "plutovg-utils.h"
int juce_plutovg_version(void)
{
return JUCE_PLUTOVG_VERSION;
}
const char* juce_plutovg_version_string(void)
{
return JUCE_PLUTOVG_VERSION_STRING;
}
#define JUCE_PLUTOVG_DEFAULT_STROKE_STYLE ((juce_plutovg_stroke_style_t){1.f, JUCE_PLUTOVG_LINE_CAP_BUTT, JUCE_PLUTOVG_LINE_JOIN_MITER, 10.f})
static juce_plutovg_state_t* juce_plutovg_state_create(void)
{
juce_plutovg_state_t* state = malloc(sizeof(juce_plutovg_state_t));
state->paint = NULL;
state->font_face = NULL;
state->color = JUCE_PLUTOVG_BLACK_COLOR;
state->matrix = JUCE_PLUTOVG_IDENTITY_MATRIX;
state->stroke.style = JUCE_PLUTOVG_DEFAULT_STROKE_STYLE;
state->stroke.dash.offset = 0.f;
juce_plutovg_array_init(state->stroke.dash.array);
juce_plutovg_span_buffer_init(&state->clip_spans);
state->winding = JUCE_PLUTOVG_FILL_RULE_NON_ZERO;
state->op = JUCE_PLUTOVG_OPERATOR_SRC_OVER;
state->font_size = 12.f;
state->opacity = 1.f;
state->clipping = false;
state->next = NULL;
return state;
}
static void juce_plutovg_state_reset(juce_plutovg_state_t* state)
{
juce_plutovg_paint_destroy(state->paint);
juce_plutovg_font_face_destroy(state->font_face);
state->paint = NULL;
state->font_face = NULL;
state->color = JUCE_PLUTOVG_BLACK_COLOR;
state->matrix = JUCE_PLUTOVG_IDENTITY_MATRIX;
state->stroke.style = JUCE_PLUTOVG_DEFAULT_STROKE_STYLE;
state->stroke.dash.offset = 0.f;
juce_plutovg_array_clear(state->stroke.dash.array);
juce_plutovg_span_buffer_reset(&state->clip_spans);
state->winding = JUCE_PLUTOVG_FILL_RULE_NON_ZERO;
state->op = JUCE_PLUTOVG_OPERATOR_SRC_OVER;
state->font_size = 12.f;
state->opacity = 1.f;
state->clipping = false;
}
static void juce_plutovg_state_copy(juce_plutovg_state_t* state, const juce_plutovg_state_t* source)
{
state->paint = juce_plutovg_paint_reference(source->paint);
state->font_face = juce_plutovg_font_face_reference(source->font_face);
state->color = source->color;
state->matrix = source->matrix;
state->stroke.style = source->stroke.style;
state->stroke.dash.offset = source->stroke.dash.offset;
juce_plutovg_array_clear(state->stroke.dash.array);
juce_plutovg_array_append(state->stroke.dash.array, source->stroke.dash.array);
juce_plutovg_span_buffer_copy(&state->clip_spans, &source->clip_spans);
state->winding = source->winding;
state->op = source->op;
state->font_size = source->font_size;
state->opacity = source->opacity;
state->clipping = source->clipping;
}
static void juce_plutovg_state_destroy(juce_plutovg_state_t* state)
{
juce_plutovg_paint_destroy(state->paint);
juce_plutovg_font_face_destroy(state->font_face);
juce_plutovg_array_destroy(state->stroke.dash.array);
juce_plutovg_span_buffer_destroy(&state->clip_spans);
free(state);
}
juce_plutovg_canvas_t* juce_plutovg_canvas_create(juce_plutovg_surface_t* surface)
{
juce_plutovg_canvas_t* canvas = malloc(sizeof(juce_plutovg_canvas_t));
juce_plutovg_init_reference(canvas);
canvas->surface = juce_plutovg_surface_reference(surface);
canvas->path = juce_plutovg_path_create();
canvas->state = juce_plutovg_state_create();
canvas->freed_state = NULL;
canvas->face_cache = NULL;
canvas->clip_rect = JUCE_PLUTOVG_MAKE_RECT(0, 0, surface->width, surface->height);
juce_plutovg_span_buffer_init(&canvas->clip_spans);
juce_plutovg_span_buffer_init(&canvas->fill_spans);
return canvas;
}
juce_plutovg_canvas_t* juce_plutovg_canvas_reference(juce_plutovg_canvas_t* canvas)
{
juce_plutovg_increment_reference(canvas);
return canvas;
}
void juce_plutovg_canvas_destroy(juce_plutovg_canvas_t* canvas)
{
if(juce_plutovg_destroy_reference(canvas)) {
while(canvas->state) {
juce_plutovg_state_t* state = canvas->state;
canvas->state = state->next;
juce_plutovg_state_destroy(state);
}
while(canvas->freed_state) {
juce_plutovg_state_t* state = canvas->freed_state;
canvas->freed_state = state->next;
juce_plutovg_state_destroy(state);
}
juce_plutovg_font_face_cache_destroy(canvas->face_cache);
juce_plutovg_span_buffer_destroy(&canvas->fill_spans);
juce_plutovg_span_buffer_destroy(&canvas->clip_spans);
juce_plutovg_surface_destroy(canvas->surface);
juce_plutovg_path_destroy(canvas->path);
free(canvas);
}
}
int juce_plutovg_canvas_get_reference_count(const juce_plutovg_canvas_t* canvas)
{
return juce_plutovg_get_reference_count(canvas);
}
juce_plutovg_surface_t* juce_plutovg_canvas_get_surface(const juce_plutovg_canvas_t* canvas)
{
return canvas->surface;
}
void juce_plutovg_canvas_save(juce_plutovg_canvas_t* canvas)
{
juce_plutovg_state_t* new_state = canvas->freed_state;
if(new_state == NULL)
new_state = juce_plutovg_state_create();
else
canvas->freed_state = new_state->next;
juce_plutovg_state_copy(new_state, canvas->state);
new_state->next = canvas->state;
canvas->state = new_state;
}
void juce_plutovg_canvas_restore(juce_plutovg_canvas_t* canvas)
{
if(canvas->state->next == NULL)
return;
juce_plutovg_state_t* old_state = canvas->state;
canvas->state = old_state->next;
juce_plutovg_state_reset(old_state);
old_state->next = canvas->freed_state;
canvas->freed_state = old_state;
}
void juce_plutovg_canvas_set_rgb(juce_plutovg_canvas_t* canvas, float r, float g, float b)
{
juce_plutovg_canvas_set_rgba(canvas, r, g, b, 1.f);
}
void juce_plutovg_canvas_set_rgba(juce_plutovg_canvas_t* canvas, float r, float g, float b, float a)
{
juce_plutovg_color_init_rgba(&canvas->state->color, r, g, b, a);
juce_plutovg_canvas_set_paint(canvas, NULL);
}
void juce_plutovg_canvas_set_color(juce_plutovg_canvas_t* canvas, const juce_plutovg_color_t* color)
{
juce_plutovg_canvas_set_rgba(canvas, color->r, color->g, color->b, color->a);
}
void juce_plutovg_canvas_set_linear_gradient(juce_plutovg_canvas_t* canvas, float x1, float y1, float x2, float y2, juce_plutovg_spread_method_t spread, const juce_plutovg_gradient_stop_t* stops, int nstops, const juce_plutovg_matrix_t* matrix)
{
juce_plutovg_paint_t* paint = juce_plutovg_paint_create_linear_gradient(x1, y1, x2, y2, spread, stops, nstops, matrix);
juce_plutovg_canvas_set_paint(canvas, paint);
juce_plutovg_paint_destroy(paint);
}
void juce_plutovg_canvas_set_radial_gradient(juce_plutovg_canvas_t* canvas, float cx, float cy, float cr, float fx, float fy, float fr, juce_plutovg_spread_method_t spread, const juce_plutovg_gradient_stop_t* stops, int nstops, const juce_plutovg_matrix_t* matrix)
{
juce_plutovg_paint_t* paint = juce_plutovg_paint_create_radial_gradient(cx, cy, cr, fx, fy, fr, spread, stops, nstops, matrix);
juce_plutovg_canvas_set_paint(canvas, paint);
juce_plutovg_paint_destroy(paint);
}
void juce_plutovg_canvas_set_texture(juce_plutovg_canvas_t* canvas, juce_plutovg_surface_t* surface, juce_plutovg_texture_type_t type, float opacity, const juce_plutovg_matrix_t* matrix)
{
juce_plutovg_paint_t* paint = juce_plutovg_paint_create_texture(surface, type, opacity, matrix);
juce_plutovg_canvas_set_paint(canvas, paint);
juce_plutovg_paint_destroy(paint);
}
void juce_plutovg_canvas_set_paint(juce_plutovg_canvas_t* canvas, juce_plutovg_paint_t* paint)
{
paint = juce_plutovg_paint_reference(paint);
juce_plutovg_paint_destroy(canvas->state->paint);
canvas->state->paint = paint;
}
juce_plutovg_paint_t* juce_plutovg_canvas_get_paint(const juce_plutovg_canvas_t* canvas, juce_plutovg_color_t* color)
{
if(color)
*color = canvas->state->color;
return canvas->state->paint;
}
void juce_plutovg_canvas_set_font_face_cache(juce_plutovg_canvas_t* canvas, juce_plutovg_font_face_cache_t* cache)
{
cache = juce_plutovg_font_face_cache_reference(cache);
juce_plutovg_font_face_cache_destroy(canvas->face_cache);
canvas->face_cache = cache;
}
juce_plutovg_font_face_cache_t* juce_plutovg_canvas_get_font_face_cache(const juce_plutovg_canvas_t* canvas)
{
return canvas->face_cache;
}
void juce_plutovg_canvas_add_font_face(juce_plutovg_canvas_t* canvas, const char* family, bool bold, bool italic, juce_plutovg_font_face_t* face)
{
if(canvas->face_cache == NULL)
canvas->face_cache = juce_plutovg_font_face_cache_create();
juce_plutovg_font_face_cache_add(canvas->face_cache, family, bold, italic, face);
}
bool juce_plutovg_canvas_add_font_file(juce_plutovg_canvas_t* canvas, const char* family, bool bold, bool italic, const char* filename, int ttcindex)
{
if(canvas->face_cache == NULL)
canvas->face_cache = juce_plutovg_font_face_cache_create();
return juce_plutovg_font_face_cache_add_file(canvas->face_cache, family, bold, italic, filename, ttcindex);
}
bool juce_plutovg_canvas_select_font_face(juce_plutovg_canvas_t* canvas, const char* family, bool bold, bool italic)
{
if(canvas->face_cache == NULL)
return false;
juce_plutovg_font_face_t* face = juce_plutovg_font_face_cache_get(canvas->face_cache, family, bold, italic);
if(face == NULL)
return false;
juce_plutovg_canvas_set_font_face(canvas, face);
return true;
}
void juce_plutovg_canvas_set_font(juce_plutovg_canvas_t* canvas, juce_plutovg_font_face_t* face, float size)
{
juce_plutovg_canvas_set_font_face(canvas, face);
juce_plutovg_canvas_set_font_size(canvas, size);
}
void juce_plutovg_canvas_set_font_face(juce_plutovg_canvas_t* canvas, juce_plutovg_font_face_t* face)
{
face = juce_plutovg_font_face_reference(face);
juce_plutovg_font_face_destroy(canvas->state->font_face);
canvas->state->font_face = face;
}
juce_plutovg_font_face_t* juce_plutovg_canvas_get_font_face(const juce_plutovg_canvas_t* canvas)
{
return canvas->state->font_face;
}
void juce_plutovg_canvas_set_font_size(juce_plutovg_canvas_t* canvas, float size)
{
canvas->state->font_size = size;
}
float juce_plutovg_canvas_get_font_size(const juce_plutovg_canvas_t* canvas)
{
return canvas->state->font_size;
}
void juce_plutovg_canvas_set_fill_rule(juce_plutovg_canvas_t* canvas, juce_plutovg_fill_rule_t winding)
{
canvas->state->winding = winding;
}
juce_plutovg_fill_rule_t juce_plutovg_canvas_get_fill_rule(const juce_plutovg_canvas_t* canvas)
{
return canvas->state->winding;
}
void juce_plutovg_canvas_set_operator(juce_plutovg_canvas_t* canvas, juce_plutovg_operator_t op)
{
canvas->state->op = op;
}
juce_plutovg_operator_t juce_plutovg_canvas_get_operator(const juce_plutovg_canvas_t* canvas)
{
return canvas->state->op;
}
void juce_plutovg_canvas_set_opacity(juce_plutovg_canvas_t* canvas, float opacity)
{
canvas->state->opacity = juce_plutovg_clamp(opacity, 0.f, 1.f);
}
float juce_plutovg_canvas_get_opacity(const juce_plutovg_canvas_t* canvas)
{
return canvas->state->opacity;
}
void juce_plutovg_canvas_set_line_width(juce_plutovg_canvas_t* canvas, float line_width)
{
canvas->state->stroke.style.width = line_width;
}
float juce_plutovg_canvas_get_line_width(const juce_plutovg_canvas_t* canvas)
{
return canvas->state->stroke.style.width;
}
void juce_plutovg_canvas_set_line_cap(juce_plutovg_canvas_t* canvas, juce_plutovg_line_cap_t line_cap)
{
canvas->state->stroke.style.cap = line_cap;
}
juce_plutovg_line_cap_t juce_plutovg_canvas_get_line_cap(const juce_plutovg_canvas_t* canvas)
{
return canvas->state->stroke.style.cap;
}
void juce_plutovg_canvas_set_line_join(juce_plutovg_canvas_t* canvas, juce_plutovg_line_join_t line_join)
{
canvas->state->stroke.style.join = line_join;
}
juce_plutovg_line_join_t juce_plutovg_canvas_get_line_join(const juce_plutovg_canvas_t* canvas)
{
return canvas->state->stroke.style.join;
}
void juce_plutovg_canvas_set_miter_limit(juce_plutovg_canvas_t* canvas, float miter_limit)
{
canvas->state->stroke.style.miter_limit = miter_limit;
}
float juce_plutovg_canvas_get_miter_limit(const juce_plutovg_canvas_t* canvas)
{
return canvas->state->stroke.style.miter_limit;
}
void juce_plutovg_canvas_set_dash(juce_plutovg_canvas_t* canvas, float offset, const float* dashes, int ndashes)
{
juce_plutovg_canvas_set_dash_offset(canvas, offset);
juce_plutovg_canvas_set_dash_array(canvas, dashes, ndashes);
}
void juce_plutovg_canvas_set_dash_offset(juce_plutovg_canvas_t* canvas, float offset)
{
canvas->state->stroke.dash.offset = offset;
}
float juce_plutovg_canvas_get_dash_offset(const juce_plutovg_canvas_t* canvas)
{
return canvas->state->stroke.dash.offset;
}
void juce_plutovg_canvas_set_dash_array(juce_plutovg_canvas_t* canvas, const float* dashes, int ndashes)
{
juce_plutovg_array_clear(canvas->state->stroke.dash.array);
juce_plutovg_array_append_data(canvas->state->stroke.dash.array, dashes, ndashes);
}
int juce_plutovg_canvas_get_dash_array(const juce_plutovg_canvas_t* canvas, const float** dashes)
{
if(dashes)
*dashes = canvas->state->stroke.dash.array.data;
return canvas->state->stroke.dash.array.size;
}
void juce_plutovg_canvas_translate(juce_plutovg_canvas_t* canvas, float tx, float ty)
{
juce_plutovg_matrix_translate(&canvas->state->matrix, tx, ty);
}
void juce_plutovg_canvas_scale(juce_plutovg_canvas_t* canvas, float sx, float sy)
{
juce_plutovg_matrix_scale(&canvas->state->matrix, sx, sy);
}
void juce_plutovg_canvas_shear(juce_plutovg_canvas_t* canvas, float shx, float shy)
{
juce_plutovg_matrix_shear(&canvas->state->matrix, shx, shy);
}
void juce_plutovg_canvas_rotate(juce_plutovg_canvas_t* canvas, float angle)
{
juce_plutovg_matrix_rotate(&canvas->state->matrix, angle);
}
void juce_plutovg_canvas_transform(juce_plutovg_canvas_t* canvas, const juce_plutovg_matrix_t* matrix)
{
juce_plutovg_matrix_multiply(&canvas->state->matrix, matrix, &canvas->state->matrix);
}
void juce_plutovg_canvas_reset_matrix(juce_plutovg_canvas_t* canvas)
{
juce_plutovg_matrix_init_identity(&canvas->state->matrix);
}
void juce_plutovg_canvas_set_matrix(juce_plutovg_canvas_t* canvas, const juce_plutovg_matrix_t* matrix)
{
canvas->state->matrix = matrix ? *matrix : JUCE_PLUTOVG_IDENTITY_MATRIX;
}
void juce_plutovg_canvas_get_matrix(const juce_plutovg_canvas_t* canvas, juce_plutovg_matrix_t* matrix)
{
*matrix = canvas->state->matrix;
}
void juce_plutovg_canvas_map(const juce_plutovg_canvas_t* canvas, float x, float y, float* xx, float* yy)
{
juce_plutovg_matrix_map(&canvas->state->matrix, x, y, xx, yy);
}
void juce_plutovg_canvas_map_point(const juce_plutovg_canvas_t* canvas, const juce_plutovg_point_t* src, juce_plutovg_point_t* dst)
{
juce_plutovg_matrix_map_point(&canvas->state->matrix, src, dst);
}
void juce_plutovg_canvas_map_rect(const juce_plutovg_canvas_t* canvas, const juce_plutovg_rect_t* src, juce_plutovg_rect_t* dst)
{
juce_plutovg_matrix_map_rect(&canvas->state->matrix, src, dst);
}
void juce_plutovg_canvas_move_to(juce_plutovg_canvas_t* canvas, float x, float y)
{
juce_plutovg_path_move_to(canvas->path, x, y);
}
void juce_plutovg_canvas_line_to(juce_plutovg_canvas_t* canvas, float x, float y)
{
juce_plutovg_path_line_to(canvas->path, x, y);
}
void juce_plutovg_canvas_quad_to(juce_plutovg_canvas_t* canvas, float x1, float y1, float x2, float y2)
{
juce_plutovg_path_quad_to(canvas->path, x1, y1, x2, y2);
}
void juce_plutovg_canvas_cubic_to(juce_plutovg_canvas_t* canvas, float x1, float y1, float x2, float y2, float x3, float y3)
{
juce_plutovg_path_cubic_to(canvas->path, x1, y1, x2, y2, x3, y3);
}
void juce_plutovg_canvas_arc_to(juce_plutovg_canvas_t* canvas, float rx, float ry, float angle, bool large_arc_flag, bool sweep_flag, float x, float y)
{
juce_plutovg_path_arc_to(canvas->path, rx, ry, angle, large_arc_flag, sweep_flag, x, y);
}
void juce_plutovg_canvas_rect(juce_plutovg_canvas_t* canvas, float x, float y, float w, float h)
{
juce_plutovg_path_add_rect(canvas->path, x, y, w, h);
}
void juce_plutovg_canvas_round_rect(juce_plutovg_canvas_t* canvas, float x, float y, float w, float h, float rx, float ry)
{
juce_plutovg_path_add_round_rect(canvas->path, x, y, w, h, rx, ry);
}
void juce_plutovg_canvas_ellipse(juce_plutovg_canvas_t* canvas, float cx, float cy, float rx, float ry)
{
juce_plutovg_path_add_ellipse(canvas->path, cx, cy, rx, ry);
}
void juce_plutovg_canvas_circle(juce_plutovg_canvas_t* canvas, float cx, float cy, float r)
{
juce_plutovg_path_add_circle(canvas->path, cx, cy, r);
}
void juce_plutovg_canvas_arc(juce_plutovg_canvas_t* canvas, float cx, float cy, float r, float a0, float a1, bool ccw)
{
juce_plutovg_path_add_arc(canvas->path, cx, cy, r, a0, a1, ccw);
}
void juce_plutovg_canvas_add_path(juce_plutovg_canvas_t* canvas, const juce_plutovg_path_t* path)
{
juce_plutovg_path_add_path(canvas->path, path, NULL);
}
void juce_plutovg_canvas_new_path(juce_plutovg_canvas_t* canvas)
{
juce_plutovg_path_reset(canvas->path);
}
void juce_plutovg_canvas_close_path(juce_plutovg_canvas_t* canvas)
{
juce_plutovg_path_close(canvas->path);
}
void juce_plutovg_canvas_get_current_point(const juce_plutovg_canvas_t* canvas, float* x, float* y)
{
juce_plutovg_path_get_current_point(canvas->path, x, y);
}
juce_plutovg_path_t* juce_plutovg_canvas_get_path(const juce_plutovg_canvas_t* canvas)
{
return canvas->path;
}
bool juce_plutovg_canvas_fill_contains(juce_plutovg_canvas_t* canvas, float x, float y)
{
juce_plutovg_rasterize(&canvas->fill_spans, canvas->path, &canvas->state->matrix, NULL, NULL, canvas->state->winding);
return juce_plutovg_span_buffer_contains(&canvas->fill_spans, x, y);
}
bool juce_plutovg_canvas_stroke_contains(juce_plutovg_canvas_t* canvas, float x, float y)
{
juce_plutovg_rasterize(&canvas->fill_spans, canvas->path, &canvas->state->matrix, NULL, NULL, canvas->state->winding);
return juce_plutovg_span_buffer_contains(&canvas->fill_spans, x, y);
}
bool juce_plutovg_canvas_clip_contains(juce_plutovg_canvas_t* canvas, float x, float y)
{
if(canvas->state->clipping) {
return juce_plutovg_span_buffer_contains(&canvas->state->clip_spans, x, y);
}
float l = canvas->clip_rect.x;
float t = canvas->clip_rect.y;
float r = canvas->clip_rect.x + canvas->clip_rect.w;
float b = canvas->clip_rect.y + canvas->clip_rect.h;
return x >= l && x <= r && y >= t && y <= b;
}
void juce_plutovg_canvas_fill_extents(juce_plutovg_canvas_t *canvas, juce_plutovg_rect_t* extents)
{
juce_plutovg_rasterize(&canvas->fill_spans, canvas->path, &canvas->state->matrix, NULL, NULL, canvas->state->winding);
juce_plutovg_span_buffer_extents(&canvas->fill_spans, extents);
}
void juce_plutovg_canvas_stroke_extents(juce_plutovg_canvas_t *canvas, juce_plutovg_rect_t* extents)
{
juce_plutovg_rasterize(&canvas->fill_spans, canvas->path, &canvas->state->matrix, NULL, &canvas->state->stroke, JUCE_PLUTOVG_FILL_RULE_NON_ZERO);
juce_plutovg_span_buffer_extents(&canvas->fill_spans, extents);
}
void juce_plutovg_canvas_clip_extents(juce_plutovg_canvas_t* canvas, juce_plutovg_rect_t* extents)
{
if(canvas->state->clipping) {
juce_plutovg_span_buffer_extents(&canvas->state->clip_spans, extents);
} else {
extents->x = canvas->clip_rect.x;
extents->y = canvas->clip_rect.y;
extents->w = canvas->clip_rect.w;
extents->h = canvas->clip_rect.h;
}
}
void juce_plutovg_canvas_fill(juce_plutovg_canvas_t* canvas)
{
juce_plutovg_canvas_fill_preserve(canvas);
juce_plutovg_canvas_new_path(canvas);
}
void juce_plutovg_canvas_stroke(juce_plutovg_canvas_t* canvas)
{
juce_plutovg_canvas_stroke_preserve(canvas);
juce_plutovg_canvas_new_path(canvas);
}
void juce_plutovg_canvas_clip(juce_plutovg_canvas_t* canvas)
{
juce_plutovg_canvas_clip_preserve(canvas);
juce_plutovg_canvas_new_path(canvas);
}
void juce_plutovg_canvas_paint(juce_plutovg_canvas_t* canvas)
{
if(canvas->state->clipping) {
juce_plutovg_blend(canvas, &canvas->state->clip_spans);
} else {
juce_plutovg_span_buffer_init_rect(&canvas->clip_spans, 0, 0, canvas->surface->width, canvas->surface->height);
juce_plutovg_blend(canvas, &canvas->clip_spans);
}
}
void juce_plutovg_canvas_fill_preserve(juce_plutovg_canvas_t* canvas)
{
juce_plutovg_rasterize(&canvas->fill_spans, canvas->path, &canvas->state->matrix, &canvas->clip_rect, NULL, canvas->state->winding);
if(canvas->state->clipping) {
juce_plutovg_span_buffer_intersect(&canvas->clip_spans, &canvas->fill_spans, &canvas->state->clip_spans);
juce_plutovg_blend(canvas, &canvas->clip_spans);
} else {
juce_plutovg_blend(canvas, &canvas->fill_spans);
}
}
void juce_plutovg_canvas_stroke_preserve(juce_plutovg_canvas_t* canvas)
{
juce_plutovg_rasterize(&canvas->fill_spans, canvas->path, &canvas->state->matrix, &canvas->clip_rect, &canvas->state->stroke, JUCE_PLUTOVG_FILL_RULE_NON_ZERO);
if(canvas->state->clipping) {
juce_plutovg_span_buffer_intersect(&canvas->clip_spans, &canvas->fill_spans, &canvas->state->clip_spans);
juce_plutovg_blend(canvas, &canvas->clip_spans);
} else {
juce_plutovg_blend(canvas, &canvas->fill_spans);
}
}
void juce_plutovg_canvas_clip_preserve(juce_plutovg_canvas_t* canvas)
{
if(canvas->state->clipping) {
juce_plutovg_rasterize(&canvas->fill_spans, canvas->path, &canvas->state->matrix, &canvas->clip_rect, NULL, canvas->state->winding);
juce_plutovg_span_buffer_intersect(&canvas->clip_spans, &canvas->fill_spans, &canvas->state->clip_spans);
juce_plutovg_span_buffer_copy(&canvas->state->clip_spans, &canvas->clip_spans);
} else {
juce_plutovg_rasterize(&canvas->state->clip_spans, canvas->path, &canvas->state->matrix, &canvas->clip_rect, NULL, canvas->state->winding);
canvas->state->clipping = true;
}
}
void juce_plutovg_canvas_fill_rect(juce_plutovg_canvas_t* canvas, float x, float y, float w, float h)
{
juce_plutovg_canvas_new_path(canvas);
juce_plutovg_canvas_rect(canvas, x, y, w, h);
juce_plutovg_canvas_fill(canvas);
}
void juce_plutovg_canvas_fill_path(juce_plutovg_canvas_t* canvas, const juce_plutovg_path_t* path)
{
juce_plutovg_canvas_new_path(canvas);
juce_plutovg_canvas_add_path(canvas, path);
juce_plutovg_canvas_fill(canvas);
}
void juce_plutovg_canvas_stroke_rect(juce_plutovg_canvas_t* canvas, float x, float y, float w, float h)
{
juce_plutovg_canvas_new_path(canvas);
juce_plutovg_canvas_rect(canvas, x, y, w, h);
juce_plutovg_canvas_stroke(canvas);
}
void juce_plutovg_canvas_stroke_path(juce_plutovg_canvas_t* canvas, const juce_plutovg_path_t* path)
{
juce_plutovg_canvas_new_path(canvas);
juce_plutovg_canvas_add_path(canvas, path);
juce_plutovg_canvas_stroke(canvas);
}
void juce_plutovg_canvas_clip_rect(juce_plutovg_canvas_t* canvas, float x, float y, float w, float h)
{
juce_plutovg_canvas_new_path(canvas);
juce_plutovg_canvas_rect(canvas, x, y, w, h);
juce_plutovg_canvas_clip(canvas);
}
void juce_plutovg_canvas_clip_path(juce_plutovg_canvas_t* canvas, const juce_plutovg_path_t* path)
{
juce_plutovg_canvas_new_path(canvas);
juce_plutovg_canvas_add_path(canvas, path);
juce_plutovg_canvas_clip(canvas);
}
float juce_plutovg_canvas_add_glyph(juce_plutovg_canvas_t* canvas, juce_plutovg_codepoint_t codepoint, float x, float y)
{
juce_plutovg_state_t* state = canvas->state;
if(state->font_face && state->font_size > 0.f)
return juce_plutovg_font_face_get_glyph_path(state->font_face, state->font_size, x, y, codepoint, canvas->path);
return 0.f;
}
float juce_plutovg_canvas_add_text(juce_plutovg_canvas_t* canvas, const void* text, int length, juce_plutovg_text_encoding_t encoding, float x, float y)
{
juce_plutovg_state_t* state = canvas->state;
if(state->font_face == NULL || state->font_size <= 0.f)
return 0.f;
juce_plutovg_text_iterator_t it;
juce_plutovg_text_iterator_init(&it, text, length, encoding);
float advance_width = 0.f;
while(juce_plutovg_text_iterator_has_next(&it)) {
juce_plutovg_codepoint_t codepoint = juce_plutovg_text_iterator_next(&it);
advance_width += juce_plutovg_font_face_get_glyph_path(state->font_face, state->font_size, x + advance_width, y, codepoint, canvas->path);
}
return advance_width;
}
float juce_plutovg_canvas_fill_text(juce_plutovg_canvas_t* canvas, const void* text, int length, juce_plutovg_text_encoding_t encoding, float x, float y)
{
juce_plutovg_canvas_new_path(canvas);
float advance_width = juce_plutovg_canvas_add_text(canvas, text, length, encoding, x, y);
juce_plutovg_canvas_fill(canvas);
return advance_width;
}
float juce_plutovg_canvas_stroke_text(juce_plutovg_canvas_t* canvas, const void* text, int length, juce_plutovg_text_encoding_t encoding, float x, float y)
{
juce_plutovg_canvas_new_path(canvas);
float advance_width = juce_plutovg_canvas_add_text(canvas, text, length, encoding, x, y);
juce_plutovg_canvas_stroke(canvas);
return advance_width;
}
float juce_plutovg_canvas_clip_text(juce_plutovg_canvas_t* canvas, const void* text, int length, juce_plutovg_text_encoding_t encoding, float x, float y)
{
juce_plutovg_canvas_new_path(canvas);
float advance_width = juce_plutovg_canvas_add_text(canvas, text, length, encoding, x, y);
juce_plutovg_canvas_clip(canvas);
return advance_width;
}
void juce_plutovg_canvas_font_metrics(const juce_plutovg_canvas_t* canvas, float* ascent, float* descent, float* line_gap, juce_plutovg_rect_t* extents)
{
juce_plutovg_state_t* state = canvas->state;
if(state->font_face && state->font_size > 0.f) {
juce_plutovg_font_face_get_metrics(state->font_face, state->font_size, ascent, descent, line_gap, extents);
return;
}
if(ascent) *ascent = 0.f;
if(descent) *descent = 0.f;
if(line_gap) *line_gap = 0.f;
if(extents) {
extents->x = 0.f;
extents->y = 0.f;
extents->w = 0.f;
extents->h = 0.f;
}
}
void juce_plutovg_canvas_glyph_metrics(juce_plutovg_canvas_t* canvas, juce_plutovg_codepoint_t codepoint, float* advance_width, float* left_side_bearing, juce_plutovg_rect_t* extents)
{
juce_plutovg_state_t* state = canvas->state;
if(state->font_face && state->font_size > 0.f) {
juce_plutovg_font_face_get_glyph_metrics(state->font_face, state->font_size, codepoint, advance_width, left_side_bearing, extents);
return;
}
if(advance_width) *advance_width = 0.f;
if(left_side_bearing) *left_side_bearing = 0.f;
if(extents) {
extents->x = 0.f;
extents->y = 0.f;
extents->w = 0.f;
extents->h = 0.f;
}
}
float juce_plutovg_canvas_text_extents(juce_plutovg_canvas_t* canvas, const void* text, int length, juce_plutovg_text_encoding_t encoding, juce_plutovg_rect_t* extents)
{
juce_plutovg_state_t* state = canvas->state;
if(state->font_face && state->font_size > 0.f) {
return juce_plutovg_font_face_text_extents(state->font_face, state->font_size, text, length, encoding, extents);
}
if(extents) {
extents->x = 0.f;
extents->y = 0.f;
extents->w = 0.f;
extents->h = 0.f;
}
return 0.f;
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,441 @@
/***************************************************************************/
/* */
/* fttrigon.c */
/* */
/* FreeType trigonometric functions (body). */
/* */
/* Copyright 2001-2005, 2012-2013 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, FTL.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include "plutovg-ft-math.h"
#if defined(_MSC_VER)
#include <intrin.h>
static inline int clz(unsigned int x) {
unsigned long r = 0;
if (_BitScanReverse(&r, x))
return 31 - r;
return 32;
}
#define PVG_FT_MSB(x) (31 - clz(x))
#elif defined(__GNUC__)
#define PVG_FT_MSB(x) (31 - __builtin_clz(x))
#else
static inline int clz(unsigned int x) {
int n = 0;
if (x == 0) return 32;
if (x <= 0x0000FFFFU) { n += 16; x <<= 16; }
if (x <= 0x00FFFFFFU) { n += 8; x <<= 8; }
if (x <= 0x0FFFFFFFU) { n += 4; x <<= 4; }
if (x <= 0x3FFFFFFFU) { n += 2; x <<= 2; }
if (x <= 0x7FFFFFFFU) { n += 1; }
return n;
}
#define PVG_FT_MSB(x) (31 - clz(x))
#endif
#define PVG_FT_PAD_FLOOR(x, n) ((x) & ~((n)-1))
#define PVG_FT_PAD_ROUND(x, n) PVG_FT_PAD_FLOOR((x) + ((n) / 2), n)
#define PVG_FT_PAD_CEIL(x, n) PVG_FT_PAD_FLOOR((x) + ((n)-1), n)
/* transfer sign leaving a positive number */
#define PVG_FT_MOVE_SIGN(x, s) \
PVG_FT_BEGIN_STMNT \
if (x < 0) { \
x = -x; \
s = -s; \
} \
PVG_FT_END_STMNT
PVG_FT_Long PVG_FT_MulFix(PVG_FT_Long a, PVG_FT_Long b)
{
PVG_FT_Int s = 1;
PVG_FT_Long c;
PVG_FT_MOVE_SIGN(a, s);
PVG_FT_MOVE_SIGN(b, s);
c = (PVG_FT_Long)(((PVG_FT_Int64)a * b + 0x8000L) >> 16);
return (s > 0) ? c : -c;
}
PVG_FT_Long PVG_FT_MulDiv(PVG_FT_Long a, PVG_FT_Long b, PVG_FT_Long c)
{
PVG_FT_Int s = 1;
PVG_FT_Long d;
PVG_FT_MOVE_SIGN(a, s);
PVG_FT_MOVE_SIGN(b, s);
PVG_FT_MOVE_SIGN(c, s);
d = (PVG_FT_Long)(c > 0 ? ((PVG_FT_Int64)a * b + (c >> 1)) / c : 0x7FFFFFFFL);
return (s > 0) ? d : -d;
}
PVG_FT_Long PVG_FT_DivFix(PVG_FT_Long a, PVG_FT_Long b)
{
PVG_FT_Int s = 1;
PVG_FT_Long q;
PVG_FT_MOVE_SIGN(a, s);
PVG_FT_MOVE_SIGN(b, s);
q = (PVG_FT_Long)(b > 0 ? (((PVG_FT_UInt64)a << 16) + (b >> 1)) / b
: 0x7FFFFFFFL);
return (s < 0 ? -q : q);
}
/*************************************************************************/
/* */
/* This is a fixed-point CORDIC implementation of trigonometric */
/* functions as well as transformations between Cartesian and polar */
/* coordinates. The angles are represented as 16.16 fixed-point values */
/* in degrees, i.e., the angular resolution is 2^-16 degrees. Note that */
/* only vectors longer than 2^16*180/pi (or at least 22 bits) on a */
/* discrete Cartesian grid can have the same or better angular */
/* resolution. Therefore, to maintain this precision, some functions */
/* require an interim upscaling of the vectors, whereas others operate */
/* with 24-bit long vectors directly. */
/* */
/*************************************************************************/
/* the Cordic shrink factor 0.858785336480436 * 2^32 */
#define PVG_FT_TRIG_SCALE 0xDBD95B16UL
/* the highest bit in overflow-safe vector components, */
/* MSB of 0.858785336480436 * sqrt(0.5) * 2^30 */
#define PVG_FT_TRIG_SAFE_MSB 29
/* this table was generated for PVG_FT_PI = 180L << 16, i.e. degrees */
#define PVG_FT_TRIG_MAX_ITERS 23
static const PVG_FT_Fixed ft_trig_arctan_table[] = {
1740967L, 919879L, 466945L, 234379L, 117304L, 58666L, 29335L, 14668L,
7334L, 3667L, 1833L, 917L, 458L, 229L, 115L, 57L,
29L, 14L, 7L, 4L, 2L, 1L};
/* multiply a given value by the CORDIC shrink factor */
static PVG_FT_Fixed ft_trig_downscale(PVG_FT_Fixed val)
{
PVG_FT_Fixed s;
PVG_FT_Int64 v;
s = val;
val = PVG_FT_ABS(val);
v = (val * (PVG_FT_Int64)PVG_FT_TRIG_SCALE) + 0x100000000UL;
val = (PVG_FT_Fixed)(v >> 32);
return (s >= 0) ? val : -val;
}
/* undefined and never called for zero vector */
static PVG_FT_Int ft_trig_prenorm(PVG_FT_Vector* vec)
{
PVG_FT_Pos x, y;
PVG_FT_Int shift;
x = vec->x;
y = vec->y;
shift = PVG_FT_MSB(PVG_FT_ABS(x) | PVG_FT_ABS(y));
if (shift <= PVG_FT_TRIG_SAFE_MSB) {
shift = PVG_FT_TRIG_SAFE_MSB - shift;
vec->x = (PVG_FT_Pos)((PVG_FT_ULong)x << shift);
vec->y = (PVG_FT_Pos)((PVG_FT_ULong)y << shift);
} else {
shift -= PVG_FT_TRIG_SAFE_MSB;
vec->x = x >> shift;
vec->y = y >> shift;
shift = -shift;
}
return shift;
}
static void ft_trig_pseudo_rotate(PVG_FT_Vector* vec, PVG_FT_Angle theta)
{
PVG_FT_Int i;
PVG_FT_Fixed x, y, xtemp, b;
const PVG_FT_Fixed* arctanptr;
x = vec->x;
y = vec->y;
/* Rotate inside [-PI/4,PI/4] sector */
while (theta < -PVG_FT_ANGLE_PI4) {
xtemp = y;
y = -x;
x = xtemp;
theta += PVG_FT_ANGLE_PI2;
}
while (theta > PVG_FT_ANGLE_PI4) {
xtemp = -y;
y = x;
x = xtemp;
theta -= PVG_FT_ANGLE_PI2;
}
arctanptr = ft_trig_arctan_table;
/* Pseudorotations, with right shifts */
for (i = 1, b = 1; i < PVG_FT_TRIG_MAX_ITERS; b <<= 1, i++) {
PVG_FT_Fixed v1 = ((y + b) >> i);
PVG_FT_Fixed v2 = ((x + b) >> i);
if (theta < 0) {
xtemp = x + v1;
y = y - v2;
x = xtemp;
theta += *arctanptr++;
} else {
xtemp = x - v1;
y = y + v2;
x = xtemp;
theta -= *arctanptr++;
}
}
vec->x = x;
vec->y = y;
}
static void ft_trig_pseudo_polarize(PVG_FT_Vector* vec)
{
PVG_FT_Angle theta;
PVG_FT_Int i;
PVG_FT_Fixed x, y, xtemp, b;
const PVG_FT_Fixed* arctanptr;
x = vec->x;
y = vec->y;
/* Get the vector into [-PI/4,PI/4] sector */
if (y > x) {
if (y > -x) {
theta = PVG_FT_ANGLE_PI2;
xtemp = y;
y = -x;
x = xtemp;
} else {
theta = y > 0 ? PVG_FT_ANGLE_PI : -PVG_FT_ANGLE_PI;
x = -x;
y = -y;
}
} else {
if (y < -x) {
theta = -PVG_FT_ANGLE_PI2;
xtemp = -y;
y = x;
x = xtemp;
} else {
theta = 0;
}
}
arctanptr = ft_trig_arctan_table;
/* Pseudorotations, with right shifts */
for (i = 1, b = 1; i < PVG_FT_TRIG_MAX_ITERS; b <<= 1, i++) {
PVG_FT_Fixed v1 = ((y + b) >> i);
PVG_FT_Fixed v2 = ((x + b) >> i);
if (y > 0) {
xtemp = x + v1;
y = y - v2;
x = xtemp;
theta += *arctanptr++;
} else {
xtemp = x - v1;
y = y + v2;
x = xtemp;
theta -= *arctanptr++;
}
}
/* round theta */
if (theta >= 0)
theta = PVG_FT_PAD_ROUND(theta, 32);
else
theta = -PVG_FT_PAD_ROUND(-theta, 32);
vec->x = x;
vec->y = theta;
}
/* documentation is in fttrigon.h */
PVG_FT_Fixed PVG_FT_Cos(PVG_FT_Angle angle)
{
PVG_FT_Vector v;
v.x = PVG_FT_TRIG_SCALE >> 8;
v.y = 0;
ft_trig_pseudo_rotate(&v, angle);
return (v.x + 0x80L) >> 8;
}
/* documentation is in fttrigon.h */
PVG_FT_Fixed PVG_FT_Sin(PVG_FT_Angle angle)
{
return PVG_FT_Cos(PVG_FT_ANGLE_PI2 - angle);
}
/* documentation is in fttrigon.h */
PVG_FT_Fixed PVG_FT_Tan(PVG_FT_Angle angle)
{
PVG_FT_Vector v;
v.x = PVG_FT_TRIG_SCALE >> 8;
v.y = 0;
ft_trig_pseudo_rotate(&v, angle);
return PVG_FT_DivFix(v.y, v.x);
}
/* documentation is in fttrigon.h */
PVG_FT_Angle PVG_FT_Atan2(PVG_FT_Fixed dx, PVG_FT_Fixed dy)
{
PVG_FT_Vector v;
if (dx == 0 && dy == 0) return 0;
v.x = dx;
v.y = dy;
ft_trig_prenorm(&v);
ft_trig_pseudo_polarize(&v);
return v.y;
}
/* documentation is in fttrigon.h */
void PVG_FT_Vector_Unit(PVG_FT_Vector* vec, PVG_FT_Angle angle)
{
vec->x = PVG_FT_TRIG_SCALE >> 8;
vec->y = 0;
ft_trig_pseudo_rotate(vec, angle);
vec->x = (vec->x + 0x80L) >> 8;
vec->y = (vec->y + 0x80L) >> 8;
}
void PVG_FT_Vector_Rotate(PVG_FT_Vector* vec, PVG_FT_Angle angle)
{
PVG_FT_Int shift;
PVG_FT_Vector v = *vec;
if ( v.x == 0 && v.y == 0 )
return;
shift = ft_trig_prenorm( &v );
ft_trig_pseudo_rotate( &v, angle );
v.x = ft_trig_downscale( v.x );
v.y = ft_trig_downscale( v.y );
if ( shift > 0 )
{
PVG_FT_Int32 half = (PVG_FT_Int32)1L << ( shift - 1 );
vec->x = ( v.x + half - ( v.x < 0 ) ) >> shift;
vec->y = ( v.y + half - ( v.y < 0 ) ) >> shift;
}
else
{
shift = -shift;
vec->x = (PVG_FT_Pos)( (PVG_FT_ULong)v.x << shift );
vec->y = (PVG_FT_Pos)( (PVG_FT_ULong)v.y << shift );
}
}
/* documentation is in fttrigon.h */
PVG_FT_Fixed PVG_FT_Vector_Length(PVG_FT_Vector* vec)
{
PVG_FT_Int shift;
PVG_FT_Vector v;
v = *vec;
/* handle trivial cases */
if (v.x == 0) {
return PVG_FT_ABS(v.y);
} else if (v.y == 0) {
return PVG_FT_ABS(v.x);
}
/* general case */
shift = ft_trig_prenorm(&v);
ft_trig_pseudo_polarize(&v);
v.x = ft_trig_downscale(v.x);
if (shift > 0) return (v.x + (1 << (shift - 1))) >> shift;
return (PVG_FT_Fixed)((PVG_FT_UInt32)v.x << -shift);
}
/* documentation is in fttrigon.h */
void PVG_FT_Vector_Polarize(PVG_FT_Vector* vec, PVG_FT_Fixed* length,
PVG_FT_Angle* angle)
{
PVG_FT_Int shift;
PVG_FT_Vector v;
v = *vec;
if (v.x == 0 && v.y == 0) return;
shift = ft_trig_prenorm(&v);
ft_trig_pseudo_polarize(&v);
v.x = ft_trig_downscale(v.x);
*length = (shift >= 0) ? (v.x >> shift)
: (PVG_FT_Fixed)((PVG_FT_UInt32)v.x << -shift);
*angle = v.y;
}
/* documentation is in fttrigon.h */
void PVG_FT_Vector_From_Polar(PVG_FT_Vector* vec, PVG_FT_Fixed length,
PVG_FT_Angle angle)
{
vec->x = length;
vec->y = 0;
PVG_FT_Vector_Rotate(vec, angle);
}
/* documentation is in fttrigon.h */
PVG_FT_Angle PVG_FT_Angle_Diff( PVG_FT_Angle angle1, PVG_FT_Angle angle2 )
{
PVG_FT_Angle delta = angle2 - angle1;
while ( delta <= -PVG_FT_ANGLE_PI )
delta += PVG_FT_ANGLE_2PI;
while ( delta > PVG_FT_ANGLE_PI )
delta -= PVG_FT_ANGLE_2PI;
return delta;
}
/* END */
@@ -0,0 +1,436 @@
/***************************************************************************/
/* */
/* fttrigon.h */
/* */
/* FreeType trigonometric functions (specification). */
/* */
/* Copyright 2001, 2003, 2005, 2007, 2013 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, FTL.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef JUCE_PLUTOVG_FT_MATH_H
#define JUCE_PLUTOVG_FT_MATH_H
#include "plutovg-ft-types.h"
/*************************************************************************/
/* */
/* The min and max functions missing in C. As usual, be careful not to */
/* write things like PVG_FT_MIN( a++, b++ ) to avoid side effects. */
/* */
#define PVG_FT_MIN( a, b ) ( (a) < (b) ? (a) : (b) )
#define PVG_FT_MAX( a, b ) ( (a) > (b) ? (a) : (b) )
#define PVG_FT_ABS( a ) ( (a) < 0 ? -(a) : (a) )
/*
* Approximate sqrt(x*x+y*y) using the `alpha max plus beta min'
* algorithm. We use alpha = 1, beta = 3/8, giving us results with a
* largest error less than 7% compared to the exact value.
*/
#define PVG_FT_HYPOT( x, y ) \
( x = PVG_FT_ABS( x ), \
y = PVG_FT_ABS( y ), \
x > y ? x + ( 3 * y >> 3 ) \
: y + ( 3 * x >> 3 ) )
/*************************************************************************/
/* */
/* <Function> */
/* PVG_FT_MulFix */
/* */
/* <Description> */
/* A very simple function used to perform the computation */
/* `(a*b)/0x10000' with maximum accuracy. Most of the time this is */
/* used to multiply a given value by a 16.16 fixed-point factor. */
/* */
/* <Input> */
/* a :: The first multiplier. */
/* b :: The second multiplier. Use a 16.16 factor here whenever */
/* possible (see note below). */
/* */
/* <Return> */
/* The result of `(a*b)/0x10000'. */
/* */
/* <Note> */
/* This function has been optimized for the case where the absolute */
/* value of `a' is less than 2048, and `b' is a 16.16 scaling factor. */
/* As this happens mainly when scaling from notional units to */
/* fractional pixels in FreeType, it resulted in noticeable speed */
/* improvements between versions 2.x and 1.x. */
/* */
/* As a conclusion, always try to place a 16.16 factor as the */
/* _second_ argument of this function; this can make a great */
/* difference. */
/* */
PVG_FT_Long
PVG_FT_MulFix( PVG_FT_Long a,
PVG_FT_Long b );
/*************************************************************************/
/* */
/* <Function> */
/* PVG_FT_MulDiv */
/* */
/* <Description> */
/* A very simple function used to perform the computation `(a*b)/c' */
/* with maximum accuracy (it uses a 64-bit intermediate integer */
/* whenever necessary). */
/* */
/* This function isn't necessarily as fast as some processor specific */
/* operations, but is at least completely portable. */
/* */
/* <Input> */
/* a :: The first multiplier. */
/* b :: The second multiplier. */
/* c :: The divisor. */
/* */
/* <Return> */
/* The result of `(a*b)/c'. This function never traps when trying to */
/* divide by zero; it simply returns `MaxInt' or `MinInt' depending */
/* on the signs of `a' and `b'. */
/* */
PVG_FT_Long
PVG_FT_MulDiv( PVG_FT_Long a,
PVG_FT_Long b,
PVG_FT_Long c );
/*************************************************************************/
/* */
/* <Function> */
/* PVG_FT_DivFix */
/* */
/* <Description> */
/* A very simple function used to perform the computation */
/* `(a*0x10000)/b' with maximum accuracy. Most of the time, this is */
/* used to divide a given value by a 16.16 fixed-point factor. */
/* */
/* <Input> */
/* a :: The numerator. */
/* b :: The denominator. Use a 16.16 factor here. */
/* */
/* <Return> */
/* The result of `(a*0x10000)/b'. */
/* */
PVG_FT_Long
PVG_FT_DivFix( PVG_FT_Long a,
PVG_FT_Long b );
/*************************************************************************/
/* */
/* <Section> */
/* computations */
/* */
/*************************************************************************/
/*************************************************************************
*
* @type:
* PVG_FT_Angle
*
* @description:
* This type is used to model angle values in FreeType. Note that the
* angle is a 16.16 fixed-point value expressed in degrees.
*
*/
typedef PVG_FT_Fixed PVG_FT_Angle;
/*************************************************************************
*
* @macro:
* PVG_FT_ANGLE_PI
*
* @description:
* The angle pi expressed in @PVG_FT_Angle units.
*
*/
#define PVG_FT_ANGLE_PI ( 180L << 16 )
/*************************************************************************
*
* @macro:
* PVG_FT_ANGLE_2PI
*
* @description:
* The angle 2*pi expressed in @PVG_FT_Angle units.
*
*/
#define PVG_FT_ANGLE_2PI ( PVG_FT_ANGLE_PI * 2 )
/*************************************************************************
*
* @macro:
* PVG_FT_ANGLE_PI2
*
* @description:
* The angle pi/2 expressed in @PVG_FT_Angle units.
*
*/
#define PVG_FT_ANGLE_PI2 ( PVG_FT_ANGLE_PI / 2 )
/*************************************************************************
*
* @macro:
* PVG_FT_ANGLE_PI4
*
* @description:
* The angle pi/4 expressed in @PVG_FT_Angle units.
*
*/
#define PVG_FT_ANGLE_PI4 ( PVG_FT_ANGLE_PI / 4 )
/*************************************************************************
*
* @function:
* PVG_FT_Sin
*
* @description:
* Return the sinus of a given angle in fixed-point format.
*
* @input:
* angle ::
* The input angle.
*
* @return:
* The sinus value.
*
* @note:
* If you need both the sinus and cosinus for a given angle, use the
* function @PVG_FT_Vector_Unit.
*
*/
PVG_FT_Fixed
PVG_FT_Sin( PVG_FT_Angle angle );
/*************************************************************************
*
* @function:
* PVG_FT_Cos
*
* @description:
* Return the cosinus of a given angle in fixed-point format.
*
* @input:
* angle ::
* The input angle.
*
* @return:
* The cosinus value.
*
* @note:
* If you need both the sinus and cosinus for a given angle, use the
* function @PVG_FT_Vector_Unit.
*
*/
PVG_FT_Fixed
PVG_FT_Cos( PVG_FT_Angle angle );
/*************************************************************************
*
* @function:
* PVG_FT_Tan
*
* @description:
* Return the tangent of a given angle in fixed-point format.
*
* @input:
* angle ::
* The input angle.
*
* @return:
* The tangent value.
*
*/
PVG_FT_Fixed
PVG_FT_Tan( PVG_FT_Angle angle );
/*************************************************************************
*
* @function:
* PVG_FT_Atan2
*
* @description:
* Return the arc-tangent corresponding to a given vector (x,y) in
* the 2d plane.
*
* @input:
* x ::
* The horizontal vector coordinate.
*
* y ::
* The vertical vector coordinate.
*
* @return:
* The arc-tangent value (i.e. angle).
*
*/
PVG_FT_Angle
PVG_FT_Atan2( PVG_FT_Fixed x,
PVG_FT_Fixed y );
/*************************************************************************
*
* @function:
* PVG_FT_Angle_Diff
*
* @description:
* Return the difference between two angles. The result is always
* constrained to the ]-PI..PI] interval.
*
* @input:
* angle1 ::
* First angle.
*
* angle2 ::
* Second angle.
*
* @return:
* Constrained value of `value2-value1'.
*
*/
PVG_FT_Angle
PVG_FT_Angle_Diff( PVG_FT_Angle angle1,
PVG_FT_Angle angle2 );
/*************************************************************************
*
* @function:
* PVG_FT_Vector_Unit
*
* @description:
* Return the unit vector corresponding to a given angle. After the
* call, the value of `vec.x' will be `sin(angle)', and the value of
* `vec.y' will be `cos(angle)'.
*
* This function is useful to retrieve both the sinus and cosinus of a
* given angle quickly.
*
* @output:
* vec ::
* The address of target vector.
*
* @input:
* angle ::
* The input angle.
*
*/
void
PVG_FT_Vector_Unit( PVG_FT_Vector* vec,
PVG_FT_Angle angle );
/*************************************************************************
*
* @function:
* PVG_FT_Vector_Rotate
*
* @description:
* Rotate a vector by a given angle.
*
* @inout:
* vec ::
* The address of target vector.
*
* @input:
* angle ::
* The input angle.
*
*/
void
PVG_FT_Vector_Rotate( PVG_FT_Vector* vec,
PVG_FT_Angle angle );
/*************************************************************************
*
* @function:
* PVG_FT_Vector_Length
*
* @description:
* Return the length of a given vector.
*
* @input:
* vec ::
* The address of target vector.
*
* @return:
* The vector length, expressed in the same units that the original
* vector coordinates.
*
*/
PVG_FT_Fixed
PVG_FT_Vector_Length( PVG_FT_Vector* vec );
/*************************************************************************
*
* @function:
* PVG_FT_Vector_Polarize
*
* @description:
* Compute both the length and angle of a given vector.
*
* @input:
* vec ::
* The address of source vector.
*
* @output:
* length ::
* The vector length.
*
* angle ::
* The vector angle.
*
*/
void
PVG_FT_Vector_Polarize( PVG_FT_Vector* vec,
PVG_FT_Fixed *length,
PVG_FT_Angle *angle );
/*************************************************************************
*
* @function:
* PVG_FT_Vector_From_Polar
*
* @description:
* Compute vector coordinates from a length and angle.
*
* @output:
* vec ::
* The address of source vector.
*
* @input:
* length ::
* The vector length.
*
* angle ::
* The vector angle.
*
*/
void
PVG_FT_Vector_From_Polar( PVG_FT_Vector* vec,
PVG_FT_Fixed length,
PVG_FT_Angle angle );
#endif /* JUCE_PLUTOVG_FT_MATH_H */
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,420 @@
/***************************************************************************/
/* */
/* ftimage.h */
/* */
/* FreeType glyph image formats and default raster interface */
/* (specification). */
/* */
/* Copyright 1996-2010, 2013 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, FTL.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef JUCE_PLUTOVG_FT_RASTER_H
#define JUCE_PLUTOVG_FT_RASTER_H
#include "plutovg-ft-types.h"
/*************************************************************************/
/* */
/* <Struct> */
/* FT_BBox */
/* */
/* <Description> */
/* A structure used to hold an outline's bounding box, i.e., the */
/* coordinates of its extrema in the horizontal and vertical */
/* directions. */
/* */
/* <Fields> */
/* xMin :: The horizontal minimum (left-most). */
/* */
/* yMin :: The vertical minimum (bottom-most). */
/* */
/* xMax :: The horizontal maximum (right-most). */
/* */
/* yMax :: The vertical maximum (top-most). */
/* */
/* <Note> */
/* The bounding box is specified with the coordinates of the lower */
/* left and the upper right corner. In PostScript, those values are */
/* often called (llx,lly) and (urx,ury), respectively. */
/* */
/* If `yMin' is negative, this value gives the glyph's descender. */
/* Otherwise, the glyph doesn't descend below the baseline. */
/* Similarly, if `ymax' is positive, this value gives the glyph's */
/* ascender. */
/* */
/* `xMin' gives the horizontal distance from the glyph's origin to */
/* the left edge of the glyph's bounding box. If `xMin' is negative, */
/* the glyph extends to the left of the origin. */
/* */
typedef struct PVG_FT_BBox_
{
PVG_FT_Pos xMin, yMin;
PVG_FT_Pos xMax, yMax;
} PVG_FT_BBox;
/*************************************************************************/
/* */
/* <Struct> */
/* PVG_FT_Outline */
/* */
/* <Description> */
/* This structure is used to describe an outline to the scan-line */
/* converter. */
/* */
/* <Fields> */
/* n_contours :: The number of contours in the outline. */
/* */
/* n_points :: The number of points in the outline. */
/* */
/* points :: A pointer to an array of `n_points' @PVG_FT_Vector */
/* elements, giving the outline's point coordinates. */
/* */
/* tags :: A pointer to an array of `n_points' chars, giving */
/* each outline point's type. */
/* */
/* If bit~0 is unset, the point is `off' the curve, */
/* i.e., a Bézier control point, while it is `on' if */
/* set. */
/* */
/* Bit~1 is meaningful for `off' points only. If set, */
/* it indicates a third-order Bézier arc control point; */
/* and a second-order control point if unset. */
/* */
/* If bit~2 is set, bits 5-7 contain the drop-out mode */
/* (as defined in the OpenType specification; the value */
/* is the same as the argument to the SCANMODE */
/* instruction). */
/* */
/* Bits 3 and~4 are reserved for internal purposes. */
/* */
/* contours :: An array of `n_contours' shorts, giving the end */
/* point of each contour within the outline. For */
/* example, the first contour is defined by the points */
/* `0' to `contours[0]', the second one is defined by */
/* the points `contours[0]+1' to `contours[1]', etc. */
/* */
/* flags :: A set of bit flags used to characterize the outline */
/* and give hints to the scan-converter and hinter on */
/* how to convert/grid-fit it. See @PVG_FT_OUTLINE_FLAGS.*/
/* */
typedef struct PVG_FT_Outline_
{
int n_contours; /* number of contours in glyph */
int n_points; /* number of points in the glyph */
PVG_FT_Vector* points; /* the outline's points */
char* tags; /* the points flags */
int* contours; /* the contour end points */
char* contours_flag; /* the contour open flags */
int flags; /* outline masks */
} PVG_FT_Outline;
/*************************************************************************/
/* */
/* <Enum> */
/* PVG_FT_OUTLINE_FLAGS */
/* */
/* <Description> */
/* A list of bit-field constants use for the flags in an outline's */
/* `flags' field. */
/* */
/* <Values> */
/* PVG_FT_OUTLINE_NONE :: */
/* Value~0 is reserved. */
/* */
/* PVG_FT_OUTLINE_OWNER :: */
/* If set, this flag indicates that the outline's field arrays */
/* (i.e., `points', `flags', and `contours') are `owned' by the */
/* outline object, and should thus be freed when it is destroyed. */
/* */
/* PVG_FT_OUTLINE_EVEN_ODD_FILL :: */
/* By default, outlines are filled using the non-zero winding rule. */
/* If set to 1, the outline will be filled using the even-odd fill */
/* rule (only works with the smooth rasterizer). */
/* */
/* PVG_FT_OUTLINE_REVERSE_FILL :: */
/* By default, outside contours of an outline are oriented in */
/* clock-wise direction, as defined in the TrueType specification. */
/* This flag is set if the outline uses the opposite direction */
/* (typically for Type~1 fonts). This flag is ignored by the scan */
/* converter. */
/* */
/* */
/* */
/* There exists a second mechanism to pass the drop-out mode to the */
/* B/W rasterizer; see the `tags' field in @PVG_FT_Outline. */
/* */
/* Please refer to the description of the `SCANTYPE' instruction in */
/* the OpenType specification (in file `ttinst1.doc') how simple */
/* drop-outs, smart drop-outs, and stubs are defined. */
/* */
#define PVG_FT_OUTLINE_NONE 0x0
#define PVG_FT_OUTLINE_OWNER 0x1
#define PVG_FT_OUTLINE_EVEN_ODD_FILL 0x2
#define PVG_FT_OUTLINE_REVERSE_FILL 0x4
/* */
#define PVG_FT_CURVE_TAG( flag ) ( flag & 3 )
#define PVG_FT_CURVE_TAG_ON 1
#define PVG_FT_CURVE_TAG_CONIC 0
#define PVG_FT_CURVE_TAG_CUBIC 2
#define PVG_FT_Curve_Tag_On PVG_FT_CURVE_TAG_ON
#define PVG_FT_Curve_Tag_Conic PVG_FT_CURVE_TAG_CONIC
#define PVG_FT_Curve_Tag_Cubic PVG_FT_CURVE_TAG_CUBIC
/*************************************************************************/
/* */
/* <Function> */
/* PVG_FT_Outline_Check */
/* */
/* <Description> */
/* Check the contents of an outline descriptor. */
/* */
/* <Input> */
/* outline :: A handle to a source outline. */
/* */
/* <Return> */
/* FreeType error code. 0~means success. */
/* */
PVG_FT_Error
PVG_FT_Outline_Check( PVG_FT_Outline* outline );
/*************************************************************************/
/* */
/* <Function> */
/* PVG_FT_Outline_Get_CBox */
/* */
/* <Description> */
/* Return an outline's `control box'. The control box encloses all */
/* the outline's points, including Bézier control points. Though it */
/* coincides with the exact bounding box for most glyphs, it can be */
/* slightly larger in some situations (like when rotating an outline */
/* that contains Bézier outside arcs). */
/* */
/* Computing the control box is very fast, while getting the bounding */
/* box can take much more time as it needs to walk over all segments */
/* and arcs in the outline. To get the latter, you can use the */
/* `ftbbox' component, which is dedicated to this single task. */
/* */
/* <Input> */
/* outline :: A pointer to the source outline descriptor. */
/* */
/* <Output> */
/* acbox :: The outline's control box. */
/* */
/* <Note> */
/* See @PVG_FT_Glyph_Get_CBox for a discussion of tricky fonts. */
/* */
void
PVG_FT_Outline_Get_CBox( const PVG_FT_Outline* outline,
PVG_FT_BBox *acbox );
/*************************************************************************/
/* */
/* <Struct> */
/* PVG_FT_Span */
/* */
/* <Description> */
/* A structure used to model a single span of gray (or black) pixels */
/* when rendering a monochrome or anti-aliased bitmap. */
/* */
/* <Fields> */
/* x :: The span's horizontal start position. */
/* */
/* len :: The span's length in pixels. */
/* */
/* coverage :: The span color/coverage, ranging from 0 (background) */
/* to 255 (foreground). Only used for anti-aliased */
/* rendering. */
/* */
/* <Note> */
/* This structure is used by the span drawing callback type named */
/* @PVG_FT_SpanFunc that takes the y~coordinate of the span as a */
/* parameter. */
/* */
/* The coverage value is always between 0 and 255. If you want less */
/* gray values, the callback function has to reduce them. */
/* */
typedef struct PVG_FT_Span_
{
int x;
int len;
int y;
unsigned char coverage;
} PVG_FT_Span;
/*************************************************************************/
/* */
/* <FuncType> */
/* PVG_FT_SpanFunc */
/* */
/* <Description> */
/* A function used as a call-back by the anti-aliased renderer in */
/* order to let client applications draw themselves the gray pixel */
/* spans on each scan line. */
/* */
/* <Input> */
/* y :: The scanline's y~coordinate. */
/* */
/* count :: The number of spans to draw on this scanline. */
/* */
/* spans :: A table of `count' spans to draw on the scanline. */
/* */
/* user :: User-supplied data that is passed to the callback. */
/* */
/* <Note> */
/* This callback allows client applications to directly render the */
/* gray spans of the anti-aliased bitmap to any kind of surfaces. */
/* */
/* This can be used to write anti-aliased outlines directly to a */
/* given background bitmap, and even perform translucency. */
/* */
/* Note that the `count' field cannot be greater than a fixed value */
/* defined by the `PVG_FT_MAX_GRAY_SPANS' configuration macro in */
/* `ftoption.h'. By default, this value is set to~32, which means */
/* that if there are more than 32~spans on a given scanline, the */
/* callback is called several times with the same `y' parameter in */
/* order to draw all callbacks. */
/* */
/* Otherwise, the callback is only called once per scan-line, and */
/* only for those scanlines that do have `gray' pixels on them. */
/* */
typedef void
(*PVG_FT_SpanFunc)( int count,
const PVG_FT_Span* spans,
void* user );
#define PVG_FT_Raster_Span_Func PVG_FT_SpanFunc
/*************************************************************************/
/* */
/* <Enum> */
/* PVG_FT_RASTER_FLAG_XXX */
/* */
/* <Description> */
/* A list of bit flag constants as used in the `flags' field of a */
/* @PVG_FT_Raster_Params structure. */
/* */
/* <Values> */
/* PVG_FT_RASTER_FLAG_DEFAULT :: This value is 0. */
/* */
/* PVG_FT_RASTER_FLAG_AA :: This flag is set to indicate that an */
/* anti-aliased glyph image should be */
/* generated. Otherwise, it will be */
/* monochrome (1-bit). */
/* */
/* PVG_FT_RASTER_FLAG_DIRECT :: This flag is set to indicate direct */
/* rendering. In this mode, client */
/* applications must provide their own span */
/* callback. This lets them directly */
/* draw or compose over an existing bitmap. */
/* If this bit is not set, the target */
/* pixmap's buffer _must_ be zeroed before */
/* rendering. */
/* */
/* Note that for now, direct rendering is */
/* only possible with anti-aliased glyphs. */
/* */
/* PVG_FT_RASTER_FLAG_CLIP :: This flag is only used in direct */
/* rendering mode. If set, the output will */
/* be clipped to a box specified in the */
/* `clip_box' field of the */
/* @PVG_FT_Raster_Params structure. */
/* */
/* Note that by default, the glyph bitmap */
/* is clipped to the target pixmap, except */
/* in direct rendering mode where all spans */
/* are generated if no clipping box is set. */
/* */
#define PVG_FT_RASTER_FLAG_DEFAULT 0x0
#define PVG_FT_RASTER_FLAG_AA 0x1
#define PVG_FT_RASTER_FLAG_DIRECT 0x2
#define PVG_FT_RASTER_FLAG_CLIP 0x4
/*************************************************************************/
/* */
/* <Struct> */
/* PVG_FT_Raster_Params */
/* */
/* <Description> */
/* A structure to hold the arguments used by a raster's render */
/* function. */
/* */
/* <Fields> */
/* target :: The target bitmap. */
/* */
/* source :: A pointer to the source glyph image (e.g., an */
/* @PVG_FT_Outline). */
/* */
/* flags :: The rendering flags. */
/* */
/* gray_spans :: The gray span drawing callback. */
/* */
/* black_spans :: The black span drawing callback. UNIMPLEMENTED! */
/* */
/* bit_test :: The bit test callback. UNIMPLEMENTED! */
/* */
/* bit_set :: The bit set callback. UNIMPLEMENTED! */
/* */
/* user :: User-supplied data that is passed to each drawing */
/* callback. */
/* */
/* clip_box :: An optional clipping box. It is only used in */
/* direct rendering mode. Note that coordinates here */
/* should be expressed in _integer_ pixels (and not in */
/* 26.6 fixed-point units). */
/* */
/* <Note> */
/* An anti-aliased glyph bitmap is drawn if the @PVG_FT_RASTER_FLAG_AA */
/* bit flag is set in the `flags' field, otherwise a monochrome */
/* bitmap is generated. */
/* */
/* If the @PVG_FT_RASTER_FLAG_DIRECT bit flag is set in `flags', the */
/* raster will call the `gray_spans' callback to draw gray pixel */
/* spans, in the case of an aa glyph bitmap, it will call */
/* `black_spans', and `bit_test' and `bit_set' in the case of a */
/* monochrome bitmap. This allows direct composition over a */
/* pre-existing bitmap through user-provided callbacks to perform the */
/* span drawing/composition. */
/* */
/* Note that the `bit_test' and `bit_set' callbacks are required when */
/* rendering a monochrome bitmap, as they are crucial to implement */
/* correct drop-out control as defined in the TrueType specification. */
/* */
typedef struct PVG_FT_Raster_Params_
{
const void* source;
int flags;
PVG_FT_SpanFunc gray_spans;
void* user;
PVG_FT_BBox clip_box;
} PVG_FT_Raster_Params;
void
PVG_FT_Raster_Render(const PVG_FT_Raster_Params *params);
#endif // JUCE_PLUTOVG_FT_RASTER_H
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,320 @@
/***************************************************************************/
/* */
/* ftstroke.h */
/* */
/* FreeType path stroker (specification). */
/* */
/* Copyright 2002-2006, 2008, 2009, 2011-2012 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, FTL.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#ifndef JUCE_PLUTOVG_FT_STROKER_H
#define JUCE_PLUTOVG_FT_STROKER_H
#include "plutovg-ft-raster.h"
/**************************************************************
*
* @type:
* PVG_FT_Stroker
*
* @description:
* Opaque handler to a path stroker object.
*/
typedef struct PVG_FT_StrokerRec_* PVG_FT_Stroker;
/**************************************************************
*
* @enum:
* PVG_FT_Stroker_LineJoin
*
* @description:
* These values determine how two joining lines are rendered
* in a stroker.
*
* @values:
* PVG_FT_STROKER_LINEJOIN_ROUND ::
* Used to render rounded line joins. Circular arcs are used
* to join two lines smoothly.
*
* PVG_FT_STROKER_LINEJOIN_BEVEL ::
* Used to render beveled line joins. The outer corner of
* the joined lines is filled by enclosing the triangular
* region of the corner with a straight line between the
* outer corners of each stroke.
*
* PVG_FT_STROKER_LINEJOIN_MITER_FIXED ::
* Used to render mitered line joins, with fixed bevels if the
* miter limit is exceeded. The outer edges of the strokes
* for the two segments are extended until they meet at an
* angle. If the segments meet at too sharp an angle (such
* that the miter would extend from the intersection of the
* segments a distance greater than the product of the miter
* limit value and the border radius), then a bevel join (see
* above) is used instead. This prevents long spikes being
* created. PVG_FT_STROKER_LINEJOIN_MITER_FIXED generates a miter
* line join as used in PostScript and PDF.
*
* PVG_FT_STROKER_LINEJOIN_MITER_VARIABLE ::
* PVG_FT_STROKER_LINEJOIN_MITER ::
* Used to render mitered line joins, with variable bevels if
* the miter limit is exceeded. The intersection of the
* strokes is clipped at a line perpendicular to the bisector
* of the angle between the strokes, at the distance from the
* intersection of the segments equal to the product of the
* miter limit value and the border radius. This prevents
* long spikes being created.
* PVG_FT_STROKER_LINEJOIN_MITER_VARIABLE generates a mitered line
* join as used in XPS. PVG_FT_STROKER_LINEJOIN_MITER is an alias
* for PVG_FT_STROKER_LINEJOIN_MITER_VARIABLE, retained for
* backwards compatibility.
*/
typedef enum PVG_FT_Stroker_LineJoin_
{
PVG_FT_STROKER_LINEJOIN_ROUND = 0,
PVG_FT_STROKER_LINEJOIN_BEVEL = 1,
PVG_FT_STROKER_LINEJOIN_MITER_VARIABLE = 2,
PVG_FT_STROKER_LINEJOIN_MITER = PVG_FT_STROKER_LINEJOIN_MITER_VARIABLE,
PVG_FT_STROKER_LINEJOIN_MITER_FIXED = 3
} PVG_FT_Stroker_LineJoin;
/**************************************************************
*
* @enum:
* PVG_FT_Stroker_LineCap
*
* @description:
* These values determine how the end of opened sub-paths are
* rendered in a stroke.
*
* @values:
* PVG_FT_STROKER_LINECAP_BUTT ::
* The end of lines is rendered as a full stop on the last
* point itself.
*
* PVG_FT_STROKER_LINECAP_ROUND ::
* The end of lines is rendered as a half-circle around the
* last point.
*
* PVG_FT_STROKER_LINECAP_SQUARE ::
* The end of lines is rendered as a square around the
* last point.
*/
typedef enum PVG_FT_Stroker_LineCap_
{
PVG_FT_STROKER_LINECAP_BUTT = 0,
PVG_FT_STROKER_LINECAP_ROUND,
PVG_FT_STROKER_LINECAP_SQUARE
} PVG_FT_Stroker_LineCap;
/**************************************************************
*
* @enum:
* PVG_FT_StrokerBorder
*
* @description:
* These values are used to select a given stroke border
* in @PVG_FT_Stroker_GetBorderCounts and @PVG_FT_Stroker_ExportBorder.
*
* @values:
* PVG_FT_STROKER_BORDER_LEFT ::
* Select the left border, relative to the drawing direction.
*
* PVG_FT_STROKER_BORDER_RIGHT ::
* Select the right border, relative to the drawing direction.
*
* @note:
* Applications are generally interested in the `inside' and `outside'
* borders. However, there is no direct mapping between these and the
* `left' and `right' ones, since this really depends on the glyph's
* drawing orientation, which varies between font formats.
*
* You can however use @PVG_FT_Outline_GetInsideBorder and
* @PVG_FT_Outline_GetOutsideBorder to get these.
*/
typedef enum PVG_FT_StrokerBorder_
{
PVG_FT_STROKER_BORDER_LEFT = 0,
PVG_FT_STROKER_BORDER_RIGHT
} PVG_FT_StrokerBorder;
/**************************************************************
*
* @function:
* PVG_FT_Stroker_New
*
* @description:
* Create a new stroker object.
*
* @input:
* library ::
* FreeType library handle.
*
* @output:
* astroker ::
* A new stroker object handle. NULL in case of error.
*
* @return:
* FreeType error code. 0~means success.
*/
PVG_FT_Error
PVG_FT_Stroker_New( PVG_FT_Stroker *astroker );
/**************************************************************
*
* @function:
* PVG_FT_Stroker_Set
*
* @description:
* Reset a stroker object's attributes.
*
* @input:
* stroker ::
* The target stroker handle.
*
* radius ::
* The border radius.
*
* line_cap ::
* The line cap style.
*
* line_join ::
* The line join style.
*
* miter_limit ::
* The miter limit for the PVG_FT_STROKER_LINEJOIN_MITER_FIXED and
* PVG_FT_STROKER_LINEJOIN_MITER_VARIABLE line join styles,
* expressed as 16.16 fixed-point value.
*
* @note:
* The radius is expressed in the same units as the outline
* coordinates.
*/
void
PVG_FT_Stroker_Set( PVG_FT_Stroker stroker,
PVG_FT_Fixed radius,
PVG_FT_Stroker_LineCap line_cap,
PVG_FT_Stroker_LineJoin line_join,
PVG_FT_Fixed miter_limit );
/**************************************************************
*
* @function:
* PVG_FT_Stroker_ParseOutline
*
* @description:
* A convenience function used to parse a whole outline with
* the stroker. The resulting outline(s) can be retrieved
* later by functions like @PVG_FT_Stroker_GetCounts and @PVG_FT_Stroker_Export.
*
* @input:
* stroker ::
* The target stroker handle.
*
* outline ::
* The source outline.
*
*
* @return:
* FreeType error code. 0~means success.
*
* @note:
* If `opened' is~0 (the default), the outline is treated as a closed
* path, and the stroker generates two distinct `border' outlines.
*
*
* This function calls @PVG_FT_Stroker_Rewind automatically.
*/
PVG_FT_Error
PVG_FT_Stroker_ParseOutline( PVG_FT_Stroker stroker,
const PVG_FT_Outline* outline);
/**************************************************************
*
* @function:
* PVG_FT_Stroker_GetCounts
*
* @description:
* Call this function once you have finished parsing your paths
* with the stroker. It returns the number of points and
* contours necessary to export all points/borders from the stroked
* outline/path.
*
* @input:
* stroker ::
* The target stroker handle.
*
* @output:
* anum_points ::
* The number of points.
*
* anum_contours ::
* The number of contours.
*
* @return:
* FreeType error code. 0~means success.
*/
PVG_FT_Error
PVG_FT_Stroker_GetCounts( PVG_FT_Stroker stroker,
PVG_FT_UInt *anum_points,
PVG_FT_UInt *anum_contours );
/**************************************************************
*
* @function:
* PVG_FT_Stroker_Export
*
* @description:
* Call this function after @PVG_FT_Stroker_GetBorderCounts to
* export all borders to your own @PVG_FT_Outline structure.
*
* Note that this function appends the border points and
* contours to your outline, but does not try to resize its
* arrays.
*
* @input:
* stroker ::
* The target stroker handle.
*
* outline ::
* The target outline handle.
*/
void
PVG_FT_Stroker_Export( PVG_FT_Stroker stroker,
PVG_FT_Outline* outline );
/**************************************************************
*
* @function:
* PVG_FT_Stroker_Done
*
* @description:
* Destroy a stroker object.
*
* @input:
* stroker ::
* A stroker handle. Can be NULL.
*/
void
PVG_FT_Stroker_Done( PVG_FT_Stroker stroker );
#endif // JUCE_PLUTOVG_FT_STROKER_H
@@ -0,0 +1,176 @@
/****************************************************************************
*
* fttypes.h
*
* FreeType simple types definitions (specification only).
*
* Copyright (C) 1996-2020 by
* David Turner, Robert Wilhelm, and Werner Lemberg.
*
* This file is part of the FreeType project, and may only be used,
* modified, and distributed under the terms of the FreeType project
* license, FTL.TXT. By continuing to use, modify, or distribute
* this file you indicate that you have read the license and
* understand and accept it fully.
*
*/
#ifndef JUCE_PLUTOVG_FT_TYPES_H
#define JUCE_PLUTOVG_FT_TYPES_H
/*************************************************************************/
/* */
/* <Type> */
/* PVG_FT_Fixed */
/* */
/* <Description> */
/* This type is used to store 16.16 fixed-point values, like scaling */
/* values or matrix coefficients. */
/* */
typedef signed long PVG_FT_Fixed;
/*************************************************************************/
/* */
/* <Type> */
/* PVG_FT_Int */
/* */
/* <Description> */
/* A typedef for the int type. */
/* */
typedef signed int PVG_FT_Int;
/*************************************************************************/
/* */
/* <Type> */
/* PVG_FT_UInt */
/* */
/* <Description> */
/* A typedef for the unsigned int type. */
/* */
typedef unsigned int PVG_FT_UInt;
/*************************************************************************/
/* */
/* <Type> */
/* PVG_FT_Long */
/* */
/* <Description> */
/* A typedef for signed long. */
/* */
typedef signed long PVG_FT_Long;
/*************************************************************************/
/* */
/* <Type> */
/* PVG_FT_ULong */
/* */
/* <Description> */
/* A typedef for unsigned long. */
/* */
typedef unsigned long PVG_FT_ULong;
/*************************************************************************/
/* */
/* <Type> */
/* PVG_FT_Short */
/* */
/* <Description> */
/* A typedef for signed short. */
/* */
typedef signed short PVG_FT_Short;
/*************************************************************************/
/* */
/* <Type> */
/* PVG_FT_Byte */
/* */
/* <Description> */
/* A simple typedef for the _unsigned_ char type. */
/* */
typedef unsigned char PVG_FT_Byte;
/*************************************************************************/
/* */
/* <Type> */
/* PVG_FT_Bool */
/* */
/* <Description> */
/* A typedef of unsigned char, used for simple booleans. As usual, */
/* values 1 and~0 represent true and false, respectively. */
/* */
typedef unsigned char PVG_FT_Bool;
/*************************************************************************/
/* */
/* <Type> */
/* PVG_FT_Error */
/* */
/* <Description> */
/* The FreeType error code type. A value of~0 is always interpreted */
/* as a successful operation. */
/* */
typedef int PVG_FT_Error;
/*************************************************************************/
/* */
/* <Type> */
/* PVG_FT_Pos */
/* */
/* <Description> */
/* The type PVG_FT_Pos is used to store vectorial coordinates. Depending */
/* on the context, these can represent distances in integer font */
/* units, or 16.16, or 26.6 fixed-point pixel coordinates. */
/* */
typedef signed long PVG_FT_Pos;
/*************************************************************************/
/* */
/* <Struct> */
/* PVG_FT_Vector */
/* */
/* <Description> */
/* A simple structure used to store a 2D vector; coordinates are of */
/* the PVG_FT_Pos type. */
/* */
/* <Fields> */
/* x :: The horizontal coordinate. */
/* y :: The vertical coordinate. */
/* */
typedef struct PVG_FT_Vector_
{
PVG_FT_Pos x;
PVG_FT_Pos y;
} PVG_FT_Vector;
typedef long long int PVG_FT_Int64;
typedef unsigned long long int PVG_FT_UInt64;
typedef signed int PVG_FT_Int32;
typedef unsigned int PVG_FT_UInt32;
#define PVG_FT_BOOL( x ) ( (PVG_FT_Bool)( x ) )
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#define PVG_FT_BEGIN_STMNT do {
#define PVG_FT_END_STMNT } while (0)
#endif // JUCE_PLUTOVG_FT_TYPES_H
@@ -0,0 +1,229 @@
#include "../include/plutovg.h"
#include "plutovg-utils.h"
void juce_plutovg_matrix_init(juce_plutovg_matrix_t* matrix, float a, float b, float c, float d, float e, float f)
{
matrix->a = a; matrix->b = b;
matrix->c = c; matrix->d = d;
matrix->e = e; matrix->f = f;
}
void juce_plutovg_matrix_init_identity(juce_plutovg_matrix_t* matrix)
{
juce_plutovg_matrix_init(matrix, 1, 0, 0, 1, 0, 0);
}
void juce_plutovg_matrix_init_translate(juce_plutovg_matrix_t* matrix, float tx, float ty)
{
juce_plutovg_matrix_init(matrix, 1, 0, 0, 1, tx, ty);
}
void juce_plutovg_matrix_init_scale(juce_plutovg_matrix_t* matrix, float sx, float sy)
{
juce_plutovg_matrix_init(matrix, sx, 0, 0, sy, 0, 0);
}
void juce_plutovg_matrix_init_rotate(juce_plutovg_matrix_t* matrix, float angle)
{
float c = cosf(angle);
float s = sinf(angle);
juce_plutovg_matrix_init(matrix, c, s, -s, c, 0, 0);
}
void juce_plutovg_matrix_init_shear(juce_plutovg_matrix_t* matrix, float shx, float shy)
{
juce_plutovg_matrix_init(matrix, 1, tanf(shy), tanf(shx), 1, 0, 0);
}
void juce_plutovg_matrix_translate(juce_plutovg_matrix_t* matrix, float tx, float ty)
{
juce_plutovg_matrix_t m;
juce_plutovg_matrix_init_translate(&m, tx, ty);
juce_plutovg_matrix_multiply(matrix, &m, matrix);
}
void juce_plutovg_matrix_scale(juce_plutovg_matrix_t* matrix, float sx, float sy)
{
juce_plutovg_matrix_t m;
juce_plutovg_matrix_init_scale(&m, sx, sy);
juce_plutovg_matrix_multiply(matrix, &m, matrix);
}
void juce_plutovg_matrix_rotate(juce_plutovg_matrix_t* matrix, float angle)
{
juce_plutovg_matrix_t m;
juce_plutovg_matrix_init_rotate(&m, angle);
juce_plutovg_matrix_multiply(matrix, &m, matrix);
}
void juce_plutovg_matrix_shear(juce_plutovg_matrix_t* matrix, float shx, float shy)
{
juce_plutovg_matrix_t m;
juce_plutovg_matrix_init_shear(&m, shx, shy);
juce_plutovg_matrix_multiply(matrix, &m, matrix);
}
void juce_plutovg_matrix_multiply(juce_plutovg_matrix_t* matrix, const juce_plutovg_matrix_t* left, const juce_plutovg_matrix_t* right)
{
float a = left->a * right->a + left->b * right->c;
float b = left->a * right->b + left->b * right->d;
float c = left->c * right->a + left->d * right->c;
float d = left->c * right->b + left->d * right->d;
float e = left->e * right->a + left->f * right->c + right->e;
float f = left->e * right->b + left->f * right->d + right->f;
juce_plutovg_matrix_init(matrix, a, b, c, d, e, f);
}
bool juce_plutovg_matrix_invert(const juce_plutovg_matrix_t* matrix, juce_plutovg_matrix_t* inverse)
{
float det = (matrix->a * matrix->d - matrix->b * matrix->c);
if(det == 0.f)
return false;
if(inverse) {
float inv_det = 1.f / det;
float a = matrix->a * inv_det;
float b = matrix->b * inv_det;
float c = matrix->c * inv_det;
float d = matrix->d * inv_det;
float e = (matrix->c * matrix->f - matrix->d * matrix->e) * inv_det;
float f = (matrix->b * matrix->e - matrix->a * matrix->f) * inv_det;
juce_plutovg_matrix_init(inverse, d, -b, -c, a, e, f);
}
return true;
}
void juce_plutovg_matrix_map(const juce_plutovg_matrix_t* matrix, float x, float y, float* xx, float* yy)
{
*xx = x * matrix->a + y * matrix->c + matrix->e;
*yy = x * matrix->b + y * matrix->d + matrix->f;
}
void juce_plutovg_matrix_map_point(const juce_plutovg_matrix_t* matrix, const juce_plutovg_point_t* src, juce_plutovg_point_t* dst)
{
juce_plutovg_matrix_map(matrix, src->x, src->y, &dst->x, &dst->y);
}
void juce_plutovg_matrix_map_points(const juce_plutovg_matrix_t* matrix, const juce_plutovg_point_t* src, juce_plutovg_point_t* dst, int count)
{
for(int i = 0; i < count; ++i) {
juce_plutovg_matrix_map_point(matrix, &src[i], &dst[i]);
}
}
void juce_plutovg_matrix_map_rect(const juce_plutovg_matrix_t* matrix, const juce_plutovg_rect_t* src, juce_plutovg_rect_t* dst)
{
juce_plutovg_point_t p[4];
p[0].x = src->x;
p[0].y = src->y;
p[1].x = src->x + src->w;
p[1].y = src->y;
p[2].x = src->x + src->w;
p[2].y = src->y + src->h;
p[3].x = src->x;
p[3].y = src->y + src->h;
juce_plutovg_matrix_map_points(matrix, p, p, 4);
float l = p[0].x;
float t = p[0].y;
float r = p[0].x;
float b = p[0].y;
for(int i = 1; i < 4; i++) {
if(p[i].x < l) l = p[i].x;
if(p[i].x > r) r = p[i].x;
if(p[i].y < t) t = p[i].y;
if(p[i].y > b) b = p[i].y;
}
dst->x = l;
dst->y = t;
dst->w = r - l;
dst->h = b - t;
}
static int parse_matrix_parameters(const char** begin, const char* end, float values[6], int required, int optional)
{
if(!juce_plutovg_skip_ws_and_delim(begin, end, '('))
return 0;
int count = 0;
int max_count = required + optional;
bool has_trailing_comma = false;
for(; count < max_count; ++count) {
if(!juce_plutovg_parse_number(begin, end, values + count))
break;
juce_plutovg_skip_ws_or_comma(begin, end, &has_trailing_comma);
}
if(!has_trailing_comma && (count == required || count == max_count)
&& juce_plutovg_skip_delim(begin, end, ')')) {
return count;
}
return 0;
}
bool juce_plutovg_matrix_parse(juce_plutovg_matrix_t* matrix, const char* data, int length)
{
float values[6];
juce_plutovg_matrix_init_identity(matrix);
if(length == -1)
length = strlen(data);
const char* it = data;
const char* end = it + length;
bool has_trailing_comma = false;
juce_plutovg_skip_ws(&it, end);
while(it < end) {
if(juce_plutovg_skip_string(&it, end, "matrix")) {
int count = parse_matrix_parameters(&it, end, values, 6, 0);
if(count == 0)
return false;
juce_plutovg_matrix_t m = { values[0], values[1], values[2], values[3], values[4], values[5] };
juce_plutovg_matrix_multiply(matrix, &m, matrix);
} else if(juce_plutovg_skip_string(&it, end, "translate")) {
int count = parse_matrix_parameters(&it, end, values, 1, 1);
if(count == 0)
return false;
if(count == 1) {
juce_plutovg_matrix_translate(matrix, values[0], 0);
} else {
juce_plutovg_matrix_translate(matrix, values[0], values[1]);
}
} else if(juce_plutovg_skip_string(&it, end, "scale")) {
int count = parse_matrix_parameters(&it, end, values, 1, 1);
if(count == 0)
return false;
if(count == 1) {
juce_plutovg_matrix_scale(matrix, values[0], values[0]);
} else {
juce_plutovg_matrix_scale(matrix, values[0], values[1]);
}
} else if(juce_plutovg_skip_string(&it, end, "rotate")) {
int count = parse_matrix_parameters(&it, end, values, 1, 2);
if(count == 0)
return false;
if(count == 3)
juce_plutovg_matrix_translate(matrix, values[1], values[2]);
juce_plutovg_matrix_rotate(matrix, JUCE_PLUTOVG_DEG2RAD(values[0]));
if(count == 3) {
juce_plutovg_matrix_translate(matrix, -values[1], -values[2]);
}
} else if(juce_plutovg_skip_string(&it, end, "skewX")) {
int count = parse_matrix_parameters(&it, end, values, 1, 0);
if(count == 0)
return false;
juce_plutovg_matrix_shear(matrix, JUCE_PLUTOVG_DEG2RAD(values[0]), 0);
} else if(juce_plutovg_skip_string(&it, end, "skewY")) {
int count = parse_matrix_parameters(&it, end, values, 1, 0);
if(count == 0)
return false;
juce_plutovg_matrix_shear(matrix, 0, JUCE_PLUTOVG_DEG2RAD(values[0]));
} else {
return false;
}
juce_plutovg_skip_ws_or_comma(&it, end, &has_trailing_comma);
}
return !has_trailing_comma;
}
@@ -0,0 +1,489 @@
#include "plutovg-private.h"
#include "plutovg-utils.h"
#include <ctype.h>
void juce_plutovg_color_init_rgb(juce_plutovg_color_t* color, float r, float g, float b)
{
juce_plutovg_color_init_rgba(color, r, g, b, 1.f);
}
void juce_plutovg_color_init_rgba(juce_plutovg_color_t* color, float r, float g, float b, float a)
{
color->r = juce_plutovg_clamp(r, 0.f, 1.f);
color->g = juce_plutovg_clamp(g, 0.f, 1.f);
color->b = juce_plutovg_clamp(b, 0.f, 1.f);
color->a = juce_plutovg_clamp(a, 0.f, 1.f);
}
void juce_plutovg_color_init_rgb8(juce_plutovg_color_t* color, int r, int g, int b)
{
juce_plutovg_color_init_rgba8(color, r, g, b, 255);
}
void juce_plutovg_color_init_rgba8(juce_plutovg_color_t* color, int r, int g, int b, int a)
{
juce_plutovg_color_init_rgba(color, r / 255.f, g / 255.f, b / 255.f, a / 255.f);
}
void juce_plutovg_color_init_rgba32(juce_plutovg_color_t* color, unsigned int value)
{
uint8_t r = (value >> 24) & 0xFF;
uint8_t g = (value >> 16) & 0xFF;
uint8_t b = (value >> 8) & 0xFF;
uint8_t a = (value >> 0) & 0xFF;
juce_plutovg_color_init_rgba8(color, r, g, b, a);
}
void juce_plutovg_color_init_argb32(juce_plutovg_color_t* color, unsigned int value)
{
uint8_t a = (value >> 24) & 0xFF;
uint8_t r = (value >> 16) & 0xFF;
uint8_t g = (value >> 8) & 0xFF;
uint8_t b = (value >> 0) & 0xFF;
juce_plutovg_color_init_rgba8(color, r, g, b, a);
}
void juce_plutovg_color_init_hsl(juce_plutovg_color_t* color, float h, float s, float l)
{
juce_plutovg_color_init_hsla(color, h, s, l, 1.f);
}
static inline float hsl_component(float h, float s, float l, float n)
{
const float k = fmodf(n + h / 30.f, 12.f);
const float a = s * juce_plutovg_min(l, 1.f - l);
return l - a * juce_plutovg_max(-1.f, juce_plutovg_min(1.f, juce_plutovg_min(k - 3.f, 9.f - k)));
}
void juce_plutovg_color_init_hsla(juce_plutovg_color_t* color, float h, float s, float l, float a)
{
h = fmodf(h, 360.f);
if(h < 0.f) { h += 360.f; }
float r = hsl_component(h, s, l, 0);
float g = hsl_component(h, s, l, 8);
float b = hsl_component(h, s, l, 4);
juce_plutovg_color_init_rgba(color, r, g, b, a);
}
unsigned int juce_plutovg_color_to_rgba32(const juce_plutovg_color_t* color)
{
uint32_t r = lroundf(color->r * 255);
uint32_t g = lroundf(color->g * 255);
uint32_t b = lroundf(color->b * 255);
uint32_t a = lroundf(color->a * 255);
return (r << 24) | (g << 16) | (b << 8) | (a);
}
unsigned int juce_plutovg_color_to_argb32(const juce_plutovg_color_t* color)
{
uint32_t a = lroundf(color->a * 255);
uint32_t r = lroundf(color->r * 255);
uint32_t g = lroundf(color->g * 255);
uint32_t b = lroundf(color->b * 255);
return (a << 24) | (r << 16) | (g << 8) | (b);
}
static inline uint8_t hex_digit(uint8_t c)
{
if(c >= '0' && c <= '9')
return c - '0';
if(c >= 'a' && c <= 'f')
return 10 + c - 'a';
return 10 + c - 'A';
}
static inline uint8_t hex_byte(uint8_t c1, uint8_t c2)
{
uint8_t h1 = hex_digit(c1);
uint8_t h2 = hex_digit(c2);
return (h1 << 4) | h2;
}
#define MAX_NAME 20
typedef struct {
const char* name;
uint32_t value;
} color_entry_t;
static int color_entry_compare(const void* a, const void* b)
{
const char* name = a;
const color_entry_t* entry = b;
return strcmp(name, entry->name);
}
static bool parse_rgb_component(const char** begin, const char* end, float* component)
{
float value = 0;
if(!juce_plutovg_parse_number(begin, end, &value))
return false;
if(juce_plutovg_skip_delim(begin, end, '%'))
value *= 2.55f;
*component = juce_plutovg_clamp(value, 0.f, 255.f) / 255.f;
return true;
}
static bool parse_alpha_component(const char** begin, const char* end, float* component)
{
float value = 0;
if(!juce_plutovg_parse_number(begin, end, &value))
return false;
if(juce_plutovg_skip_delim(begin, end, '%'))
value /= 100.f;
*component = juce_plutovg_clamp(value, 0.f, 1.f);
return true;
}
int juce_plutovg_color_parse(juce_plutovg_color_t* color, const char* data, int length)
{
if(length == -1)
length = strlen(data);
const char* it = data;
const char* end = it + length;
juce_plutovg_skip_ws(&it, end);
if(juce_plutovg_skip_delim(&it, end, '#')) {
int r, g, b, a = 255;
const char* begin = it;
while(it < end && isxdigit(*it))
++it;
int count = it - begin;
if(count == 3 || count == 4) {
r = hex_byte(begin[0], begin[0]);
g = hex_byte(begin[1], begin[1]);
b = hex_byte(begin[2], begin[2]);
if(count == 4) {
a = hex_byte(begin[3], begin[3]);
}
} else if(count == 6 || count == 8) {
r = hex_byte(begin[0], begin[1]);
g = hex_byte(begin[2], begin[3]);
b = hex_byte(begin[4], begin[5]);
if(count == 8) {
a = hex_byte(begin[6], begin[7]);
}
} else {
return 0;
}
juce_plutovg_color_init_rgba8(color, r, g, b, a);
} else {
int name_length = 0;
char name[MAX_NAME + 1];
while(it < end && name_length < MAX_NAME && isalpha(*it))
name[name_length++] = tolower(*it++);
name[name_length] = '\0';
if(strcmp(name, "transparent") == 0) {
juce_plutovg_color_init_rgba(color, 0, 0, 0, 0);
} else if(strcmp(name, "rgb") == 0 || strcmp(name, "rgba") == 0) {
if(!juce_plutovg_skip_ws_and_delim(&it, end, '('))
return 0;
float r, g, b, a = 1.f;
if(!parse_rgb_component(&it, end, &r)
|| !juce_plutovg_skip_ws_and_comma(&it, end)
|| !parse_rgb_component(&it, end, &g)
|| !juce_plutovg_skip_ws_and_comma(&it, end)
|| !parse_rgb_component(&it, end, &b)) {
return 0;
}
if(juce_plutovg_skip_ws_and_comma(&it, end)
&& !parse_alpha_component(&it, end, &a)) {
return 0;
}
juce_plutovg_skip_ws(&it, end);
if(!juce_plutovg_skip_delim(&it, end, ')'))
return 0;
juce_plutovg_color_init_rgba(color, r, g, b, a);
} else if(strcmp(name, "hsl") == 0 || strcmp(name, "hsla") == 0) {
if(!juce_plutovg_skip_ws_and_delim(&it, end, '('))
return 0;
float h, s, l, a = 1.f;
if(!juce_plutovg_parse_number(&it, end, &h)
|| !juce_plutovg_skip_ws_and_comma(&it, end)
|| !parse_alpha_component(&it, end, &s)
|| !juce_plutovg_skip_ws_and_comma(&it, end)
|| !parse_alpha_component(&it, end, &l)) {
return 0;
}
if(juce_plutovg_skip_ws_and_comma(&it, end)
&& !parse_alpha_component(&it, end, &a)) {
return 0;
}
juce_plutovg_skip_ws(&it, end);
if(!juce_plutovg_skip_delim(&it, end, ')'))
return 0;
juce_plutovg_color_init_hsla(color, h, s, l, a);
} else {
static const color_entry_t colormap[] = {
{"aliceblue", 0xF0F8FF},
{"antiquewhite", 0xFAEBD7},
{"aqua", 0x00FFFF},
{"aquamarine", 0x7FFFD4},
{"azure", 0xF0FFFF},
{"beige", 0xF5F5DC},
{"bisque", 0xFFE4C4},
{"black", 0x000000},
{"blanchedalmond", 0xFFEBCD},
{"blue", 0x0000FF},
{"blueviolet", 0x8A2BE2},
{"brown", 0xA52A2A},
{"burlywood", 0xDEB887},
{"cadetblue", 0x5F9EA0},
{"chartreuse", 0x7FFF00},
{"chocolate", 0xD2691E},
{"coral", 0xFF7F50},
{"cornflowerblue", 0x6495ED},
{"cornsilk", 0xFFF8DC},
{"crimson", 0xDC143C},
{"cyan", 0x00FFFF},
{"darkblue", 0x00008B},
{"darkcyan", 0x008B8B},
{"darkgoldenrod", 0xB8860B},
{"darkgray", 0xA9A9A9},
{"darkgreen", 0x006400},
{"darkgrey", 0xA9A9A9},
{"darkkhaki", 0xBDB76B},
{"darkmagenta", 0x8B008B},
{"darkolivegreen", 0x556B2F},
{"darkorange", 0xFF8C00},
{"darkorchid", 0x9932CC},
{"darkred", 0x8B0000},
{"darksalmon", 0xE9967A},
{"darkseagreen", 0x8FBC8F},
{"darkslateblue", 0x483D8B},
{"darkslategray", 0x2F4F4F},
{"darkslategrey", 0x2F4F4F},
{"darkturquoise", 0x00CED1},
{"darkviolet", 0x9400D3},
{"deeppink", 0xFF1493},
{"deepskyblue", 0x00BFFF},
{"dimgray", 0x696969},
{"dimgrey", 0x696969},
{"dodgerblue", 0x1E90FF},
{"firebrick", 0xB22222},
{"floralwhite", 0xFFFAF0},
{"forestgreen", 0x228B22},
{"fuchsia", 0xFF00FF},
{"gainsboro", 0xDCDCDC},
{"ghostwhite", 0xF8F8FF},
{"gold", 0xFFD700},
{"goldenrod", 0xDAA520},
{"gray", 0x808080},
{"green", 0x008000},
{"greenyellow", 0xADFF2F},
{"grey", 0x808080},
{"honeydew", 0xF0FFF0},
{"hotpink", 0xFF69B4},
{"indianred", 0xCD5C5C},
{"indigo", 0x4B0082},
{"ivory", 0xFFFFF0},
{"khaki", 0xF0E68C},
{"lavender", 0xE6E6FA},
{"lavenderblush", 0xFFF0F5},
{"lawngreen", 0x7CFC00},
{"lemonchiffon", 0xFFFACD},
{"lightblue", 0xADD8E6},
{"lightcoral", 0xF08080},
{"lightcyan", 0xE0FFFF},
{"lightgoldenrodyellow", 0xFAFAD2},
{"lightgray", 0xD3D3D3},
{"lightgreen", 0x90EE90},
{"lightgrey", 0xD3D3D3},
{"lightpink", 0xFFB6C1},
{"lightsalmon", 0xFFA07A},
{"lightseagreen", 0x20B2AA},
{"lightskyblue", 0x87CEFA},
{"lightslategray", 0x778899},
{"lightslategrey", 0x778899},
{"lightsteelblue", 0xB0C4DE},
{"lightyellow", 0xFFFFE0},
{"lime", 0x00FF00},
{"limegreen", 0x32CD32},
{"linen", 0xFAF0E6},
{"magenta", 0xFF00FF},
{"maroon", 0x800000},
{"mediumaquamarine", 0x66CDAA},
{"mediumblue", 0x0000CD},
{"mediumorchid", 0xBA55D3},
{"mediumpurple", 0x9370DB},
{"mediumseagreen", 0x3CB371},
{"mediumslateblue", 0x7B68EE},
{"mediumspringgreen", 0x00FA9A},
{"mediumturquoise", 0x48D1CC},
{"mediumvioletred", 0xC71585},
{"midnightblue", 0x191970},
{"mintcream", 0xF5FFFA},
{"mistyrose", 0xFFE4E1},
{"moccasin", 0xFFE4B5},
{"navajowhite", 0xFFDEAD},
{"navy", 0x000080},
{"oldlace", 0xFDF5E6},
{"olive", 0x808000},
{"olivedrab", 0x6B8E23},
{"orange", 0xFFA500},
{"orangered", 0xFF4500},
{"orchid", 0xDA70D6},
{"palegoldenrod", 0xEEE8AA},
{"palegreen", 0x98FB98},
{"paleturquoise", 0xAFEEEE},
{"palevioletred", 0xDB7093},
{"papayawhip", 0xFFEFD5},
{"peachpuff", 0xFFDAB9},
{"peru", 0xCD853F},
{"pink", 0xFFC0CB},
{"plum", 0xDDA0DD},
{"powderblue", 0xB0E0E6},
{"purple", 0x800080},
{"rebeccapurple", 0x663399},
{"red", 0xFF0000},
{"rosybrown", 0xBC8F8F},
{"royalblue", 0x4169E1},
{"saddlebrown", 0x8B4513},
{"salmon", 0xFA8072},
{"sandybrown", 0xF4A460},
{"seagreen", 0x2E8B57},
{"seashell", 0xFFF5EE},
{"sienna", 0xA0522D},
{"silver", 0xC0C0C0},
{"skyblue", 0x87CEEB},
{"slateblue", 0x6A5ACD},
{"slategray", 0x708090},
{"slategrey", 0x708090},
{"snow", 0xFFFAFA},
{"springgreen", 0x00FF7F},
{"steelblue", 0x4682B4},
{"tan", 0xD2B48C},
{"teal", 0x008080},
{"thistle", 0xD8BFD8},
{"tomato", 0xFF6347},
{"turquoise", 0x40E0D0},
{"violet", 0xEE82EE},
{"wheat", 0xF5DEB3},
{"white", 0xFFFFFF},
{"whitesmoke", 0xF5F5F5},
{"yellow", 0xFFFF00},
{"yellowgreen", 0x9ACD32}
};
const color_entry_t* entry = bsearch(name, colormap, sizeof(colormap) / sizeof(color_entry_t), sizeof(color_entry_t), color_entry_compare);
if(entry == NULL)
return 0;
juce_plutovg_color_init_argb32(color, 0xFF000000 | entry->value);
}
}
juce_plutovg_skip_ws(&it, end);
return it - data;
}
static void* juce_plutovg_paint_create(juce_plutovg_paint_type_t type, size_t size)
{
juce_plutovg_paint_t* paint = malloc(size);
juce_plutovg_init_reference(paint);
paint->type = type;
return paint;
}
juce_plutovg_paint_t* juce_plutovg_paint_create_rgb(float r, float g, float b)
{
return juce_plutovg_paint_create_rgba(r, g, b, 1.f);
}
juce_plutovg_paint_t* juce_plutovg_paint_create_rgba(float r, float g, float b, float a)
{
juce_plutovg_solid_paint_t* solid = juce_plutovg_paint_create(JUCE_PLUTOVG_PAINT_TYPE_COLOR, sizeof(juce_plutovg_solid_paint_t));
solid->color.r = juce_plutovg_clamp(r, 0.f, 1.f);
solid->color.g = juce_plutovg_clamp(g, 0.f, 1.f);
solid->color.b = juce_plutovg_clamp(b, 0.f, 1.f);
solid->color.a = juce_plutovg_clamp(a, 0.f, 1.f);
return &solid->base;
}
juce_plutovg_paint_t* juce_plutovg_paint_create_color(const juce_plutovg_color_t* color)
{
return juce_plutovg_paint_create_rgba(color->r, color->g, color->b, color->a);
}
static juce_plutovg_gradient_paint_t* juce_plutovg_gradient_create(juce_plutovg_gradient_type_t type, juce_plutovg_spread_method_t spread, const juce_plutovg_gradient_stop_t* stops, int nstops, const juce_plutovg_matrix_t* matrix)
{
juce_plutovg_gradient_paint_t* gradient = juce_plutovg_paint_create(JUCE_PLUTOVG_PAINT_TYPE_GRADIENT, sizeof(juce_plutovg_gradient_paint_t) + nstops * sizeof(juce_plutovg_gradient_stop_t));
gradient->type = type;
gradient->spread = spread;
gradient->matrix = matrix ? *matrix : JUCE_PLUTOVG_IDENTITY_MATRIX;
gradient->stops = (juce_plutovg_gradient_stop_t*)(gradient + 1);
gradient->nstops = nstops;
float prev_offset = 0.f;
for(int i = 0; i < nstops; ++i) {
const juce_plutovg_gradient_stop_t* stop = stops + i;
gradient->stops[i].offset = juce_plutovg_max(prev_offset, juce_plutovg_clamp(stop->offset, 0.f, 1.f));
gradient->stops[i].color.r = juce_plutovg_clamp(stop->color.r, 0.f, 1.f);
gradient->stops[i].color.g = juce_plutovg_clamp(stop->color.g, 0.f, 1.f);
gradient->stops[i].color.b = juce_plutovg_clamp(stop->color.b, 0.f, 1.f);
gradient->stops[i].color.a = juce_plutovg_clamp(stop->color.a, 0.f, 1.f);
prev_offset = gradient->stops[i].offset;
}
return gradient;
}
juce_plutovg_paint_t* juce_plutovg_paint_create_linear_gradient(float x1, float y1, float x2, float y2, juce_plutovg_spread_method_t spread, const juce_plutovg_gradient_stop_t* stops, int nstops, const juce_plutovg_matrix_t* matrix)
{
juce_plutovg_gradient_paint_t* gradient = juce_plutovg_gradient_create(JUCE_PLUTOVG_GRADIENT_TYPE_LINEAR, spread, stops, nstops, matrix);
gradient->values[0] = x1;
gradient->values[1] = y1;
gradient->values[2] = x2;
gradient->values[3] = y2;
return &gradient->base;
}
juce_plutovg_paint_t* juce_plutovg_paint_create_radial_gradient(float cx, float cy, float cr, float fx, float fy, float fr, juce_plutovg_spread_method_t spread, const juce_plutovg_gradient_stop_t* stops, int nstops, const juce_plutovg_matrix_t* matrix)
{
juce_plutovg_gradient_paint_t* gradient = juce_plutovg_gradient_create(JUCE_PLUTOVG_GRADIENT_TYPE_RADIAL, spread, stops, nstops, matrix);
gradient->values[0] = cx;
gradient->values[1] = cy;
gradient->values[2] = cr;
gradient->values[3] = fx;
gradient->values[4] = fy;
gradient->values[5] = fr;
return &gradient->base;
}
juce_plutovg_paint_t* juce_plutovg_paint_create_texture(juce_plutovg_surface_t* surface, juce_plutovg_texture_type_t type, float opacity, const juce_plutovg_matrix_t* matrix)
{
juce_plutovg_texture_paint_t* texture = juce_plutovg_paint_create(JUCE_PLUTOVG_PAINT_TYPE_TEXTURE, sizeof(juce_plutovg_texture_paint_t));
texture->type = type;
texture->opacity = juce_plutovg_clamp(opacity, 0.f, 1.f);
texture->matrix = matrix ? *matrix : JUCE_PLUTOVG_IDENTITY_MATRIX;
texture->surface = juce_plutovg_surface_reference(surface);
return &texture->base;
}
juce_plutovg_paint_t* juce_plutovg_paint_reference(juce_plutovg_paint_t* paint)
{
juce_plutovg_increment_reference(paint);
return paint;
}
void juce_plutovg_paint_destroy(juce_plutovg_paint_t* paint)
{
if(juce_plutovg_destroy_reference(paint)) {
if(paint->type == JUCE_PLUTOVG_PAINT_TYPE_TEXTURE) {
juce_plutovg_texture_paint_t* texture = (juce_plutovg_texture_paint_t*)(paint);
juce_plutovg_surface_destroy(texture->surface);
}
free(paint);
}
}
int juce_plutovg_paint_get_reference_count(const juce_plutovg_paint_t* paint)
{
return juce_plutovg_get_reference_count(paint);
}
@@ -0,0 +1,918 @@
#include "plutovg-private.h"
#include "plutovg-utils.h"
#include <assert.h>
void juce_plutovg_path_iterator_init(juce_plutovg_path_iterator_t* it, const juce_plutovg_path_t* path)
{
it->elements = path->elements.data;
it->size = path->elements.size;
it->index = 0;
}
bool juce_plutovg_path_iterator_has_next(const juce_plutovg_path_iterator_t* it)
{
return it->index < it->size;
}
juce_plutovg_path_command_t juce_plutovg_path_iterator_next(juce_plutovg_path_iterator_t* it, juce_plutovg_point_t points[3])
{
const juce_plutovg_path_element_t* elements = it->elements + it->index;
switch(elements[0].header.command) {
case JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO:
case JUCE_PLUTOVG_PATH_COMMAND_LINE_TO:
case JUCE_PLUTOVG_PATH_COMMAND_CLOSE:
points[0] = elements[1].point;
break;
case JUCE_PLUTOVG_PATH_COMMAND_CUBIC_TO:
points[0] = elements[1].point;
points[1] = elements[2].point;
points[2] = elements[3].point;
break;
}
it->index += elements[0].header.length;
return elements[0].header.command;
}
juce_plutovg_path_t* juce_plutovg_path_create(void)
{
juce_plutovg_path_t* path = malloc(sizeof(juce_plutovg_path_t));
juce_plutovg_init_reference(path);
path->num_points = 0;
path->num_contours = 0;
path->num_curves = 0;
path->start_point = JUCE_PLUTOVG_EMPTY_POINT;
juce_plutovg_array_init(path->elements);
return path;
}
juce_plutovg_path_t* juce_plutovg_path_reference(juce_plutovg_path_t* path)
{
juce_plutovg_increment_reference(path);
return path;
}
void juce_plutovg_path_destroy(juce_plutovg_path_t* path)
{
if(juce_plutovg_destroy_reference(path)) {
juce_plutovg_array_destroy(path->elements);
free(path);
}
}
int juce_plutovg_path_get_reference_count(const juce_plutovg_path_t* path)
{
return juce_plutovg_get_reference_count(path);
}
int juce_plutovg_path_get_elements(const juce_plutovg_path_t* path, const juce_plutovg_path_element_t** elements)
{
if(elements)
*elements = path->elements.data;
return path->elements.size;
}
static juce_plutovg_path_element_t* juce_plutovg_path_add_command(juce_plutovg_path_t* path, juce_plutovg_path_command_t command, int npoints)
{
const int length = npoints + 1;
juce_plutovg_array_ensure(path->elements, length);
juce_plutovg_path_element_t* elements = path->elements.data + path->elements.size;
elements->header.command = command;
elements->header.length = length;
path->elements.size += length;
path->num_points += npoints;
return elements + 1;
}
void juce_plutovg_path_move_to(juce_plutovg_path_t* path, float x, float y)
{
juce_plutovg_path_element_t* elements = juce_plutovg_path_add_command(path, JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO, 1);
elements[0].point = JUCE_PLUTOVG_MAKE_POINT(x, y);
path->start_point = JUCE_PLUTOVG_MAKE_POINT(x, y);
path->num_contours += 1;
}
void juce_plutovg_path_line_to(juce_plutovg_path_t* path, float x, float y)
{
if(path->elements.size == 0)
juce_plutovg_path_move_to(path, 0, 0);
juce_plutovg_path_element_t* elements = juce_plutovg_path_add_command(path, JUCE_PLUTOVG_PATH_COMMAND_LINE_TO, 1);
elements[0].point = JUCE_PLUTOVG_MAKE_POINT(x, y);
}
void juce_plutovg_path_quad_to(juce_plutovg_path_t* path, float x1, float y1, float x2, float y2)
{
float current_x, current_y;
juce_plutovg_path_get_current_point(path, &current_x, &current_y);
float cp1x = 2.f / 3.f * x1 + 1.f / 3.f * current_x;
float cp1y = 2.f / 3.f * y1 + 1.f / 3.f * current_y;
float cp2x = 2.f / 3.f * x1 + 1.f / 3.f * x2;
float cp2y = 2.f / 3.f * y1 + 1.f / 3.f * y2;
juce_plutovg_path_cubic_to(path, cp1x, cp1y, cp2x, cp2y, x2, y2);
}
void juce_plutovg_path_cubic_to(juce_plutovg_path_t* path, float x1, float y1, float x2, float y2, float x3, float y3)
{
if(path->elements.size == 0)
juce_plutovg_path_move_to(path, 0, 0);
juce_plutovg_path_element_t* elements = juce_plutovg_path_add_command(path, JUCE_PLUTOVG_PATH_COMMAND_CUBIC_TO, 3);
elements[0].point = JUCE_PLUTOVG_MAKE_POINT(x1, y1);
elements[1].point = JUCE_PLUTOVG_MAKE_POINT(x2, y2);
elements[2].point = JUCE_PLUTOVG_MAKE_POINT(x3, y3);
path->num_curves += 1;
}
void juce_plutovg_path_arc_to(juce_plutovg_path_t* path, float rx, float ry, float angle, bool large_arc_flag, bool sweep_flag, float x, float y)
{
float current_x, current_y;
juce_plutovg_path_get_current_point(path, &current_x, &current_y);
if(rx == 0.f || ry == 0.f || (current_x == x && current_y == y)) {
juce_plutovg_path_line_to(path, x, y);
return;
}
if(rx < 0.f) rx = -rx;
if(ry < 0.f) ry = -ry;
float dx = (current_x - x) * 0.5f;
float dy = (current_y - y) * 0.5f;
juce_plutovg_matrix_t matrix;
juce_plutovg_matrix_init_rotate(&matrix, -angle);
juce_plutovg_matrix_map(&matrix, dx, dy, &dx, &dy);
float rxrx = rx * rx;
float ryry = ry * ry;
float dxdx = dx * dx;
float dydy = dy * dy;
float radius = dxdx / rxrx + dydy / ryry;
if(radius > 1.f) {
rx *= sqrtf(radius);
ry *= sqrtf(radius);
}
juce_plutovg_matrix_init_scale(&matrix, 1.f / rx, 1.f / ry);
juce_plutovg_matrix_rotate(&matrix, -angle);
float x1, y1;
float x2, y2;
juce_plutovg_matrix_map(&matrix, current_x, current_y, &x1, &y1);
juce_plutovg_matrix_map(&matrix, x, y, &x2, &y2);
float dx1 = x2 - x1;
float dy1 = y2 - y1;
float d = dx1 * dx1 + dy1 * dy1;
float scale_sq = 1.f / d - 0.25f;
if(scale_sq < 0.f) scale_sq = 0.f;
float scale = sqrtf(scale_sq);
if(sweep_flag == large_arc_flag)
scale = -scale;
dx1 *= scale;
dy1 *= scale;
float cx1 = 0.5f * (x1 + x2) - dy1;
float cy1 = 0.5f * (y1 + y2) + dx1;
float th1 = atan2f(y1 - cy1, x1 - cx1);
float th2 = atan2f(y2 - cy1, x2 - cx1);
float th_arc = th2 - th1;
if(th_arc < 0.f && sweep_flag)
th_arc += JUCE_PLUTOVG_TWO_PI;
else if(th_arc > 0.f && !sweep_flag)
th_arc -= JUCE_PLUTOVG_TWO_PI;
juce_plutovg_matrix_init_rotate(&matrix, angle);
juce_plutovg_matrix_scale(&matrix, rx, ry);
int segments = (int)(ceilf(fabsf(th_arc / (JUCE_PLUTOVG_HALF_PI + 0.001f))));
for(int i = 0; i < segments; i++) {
float th_start = th1 + i * th_arc / segments;
float th_end = th1 + (i + 1) * th_arc / segments;
float t = (8.f / 6.f) * tanf(0.25f * (th_end - th_start));
float x3 = cosf(th_end) + cx1;
float y3 = sinf(th_end) + cy1;
float cp2x = x3 + t * sinf(th_end);
float cp2y = y3 - t * cosf(th_end);
float cp1x = cosf(th_start) - t * sinf(th_start);
float cp1y = sinf(th_start) + t * cosf(th_start);
cp1x += cx1;
cp1y += cy1;
juce_plutovg_matrix_map(&matrix, cp1x, cp1y, &cp1x, &cp1y);
juce_plutovg_matrix_map(&matrix, cp2x, cp2y, &cp2x, &cp2y);
juce_plutovg_matrix_map(&matrix, x3, y3, &x3, &y3);
juce_plutovg_path_cubic_to(path, cp1x, cp1y, cp2x, cp2y, x3, y3);
}
}
void juce_plutovg_path_close(juce_plutovg_path_t* path)
{
if(path->elements.size == 0)
return;
juce_plutovg_path_element_t* elements = juce_plutovg_path_add_command(path, JUCE_PLUTOVG_PATH_COMMAND_CLOSE, 1);
elements[0].point = path->start_point;
}
void juce_plutovg_path_get_current_point(const juce_plutovg_path_t* path, float* x, float* y)
{
float xx = 0.f;
float yy = 0.f;
if(path->num_points > 0) {
xx = path->elements.data[path->elements.size - 1].point.x;
yy = path->elements.data[path->elements.size - 1].point.y;
}
if(x) *x = xx;
if(y) *y = yy;
}
void juce_plutovg_path_reserve(juce_plutovg_path_t* path, int count)
{
juce_plutovg_array_ensure(path->elements, count);
}
void juce_plutovg_path_reset(juce_plutovg_path_t* path)
{
juce_plutovg_array_clear(path->elements);
path->start_point = JUCE_PLUTOVG_EMPTY_POINT;
path->num_points = 0;
path->num_contours = 0;
path->num_curves = 0;
}
void juce_plutovg_path_add_rect(juce_plutovg_path_t* path, float x, float y, float w, float h)
{
juce_plutovg_path_reserve(path, 6 * 2);
juce_plutovg_path_move_to(path, x, y);
juce_plutovg_path_line_to(path, x + w, y);
juce_plutovg_path_line_to(path, x + w, y + h);
juce_plutovg_path_line_to(path, x, y + h);
juce_plutovg_path_line_to(path, x, y);
juce_plutovg_path_close(path);
}
void juce_plutovg_path_add_round_rect(juce_plutovg_path_t* path, float x, float y, float w, float h, float rx, float ry)
{
rx = juce_plutovg_min(rx, w * 0.5f);
ry = juce_plutovg_min(ry, h * 0.5f);
if(rx == 0.f && ry == 0.f) {
juce_plutovg_path_add_rect(path, x, y, w, h);
return;
}
float right = x + w;
float bottom = y + h;
float cpx = rx * JUCE_PLUTOVG_KAPPA;
float cpy = ry * JUCE_PLUTOVG_KAPPA;
juce_plutovg_path_reserve(path, 6 * 2 + 4 * 4);
juce_plutovg_path_move_to(path, x, y+ry);
juce_plutovg_path_cubic_to(path, x, y+ry-cpy, x+rx-cpx, y, x+rx, y);
juce_plutovg_path_line_to(path, right-rx, y);
juce_plutovg_path_cubic_to(path, right-rx+cpx, y, right, y+ry-cpy, right, y+ry);
juce_plutovg_path_line_to(path, right, bottom-ry);
juce_plutovg_path_cubic_to(path, right, bottom-ry+cpy, right-rx+cpx, bottom, right-rx, bottom);
juce_plutovg_path_line_to(path, x+rx, bottom);
juce_plutovg_path_cubic_to(path, x+rx-cpx, bottom, x, bottom-ry+cpy, x, bottom-ry);
juce_plutovg_path_line_to(path, x, y+ry);
juce_plutovg_path_close(path);
}
void juce_plutovg_path_add_ellipse(juce_plutovg_path_t* path, float cx, float cy, float rx, float ry)
{
float left = cx - rx;
float top = cy - ry;
float right = cx + rx;
float bottom = cy + ry;
float cpx = rx * JUCE_PLUTOVG_KAPPA;
float cpy = ry * JUCE_PLUTOVG_KAPPA;
juce_plutovg_path_reserve(path, 2 * 2 + 4 * 4);
juce_plutovg_path_move_to(path, cx, top);
juce_plutovg_path_cubic_to(path, cx+cpx, top, right, cy-cpy, right, cy);
juce_plutovg_path_cubic_to(path, right, cy+cpy, cx+cpx, bottom, cx, bottom);
juce_plutovg_path_cubic_to(path, cx-cpx, bottom, left, cy+cpy, left, cy);
juce_plutovg_path_cubic_to(path, left, cy-cpy, cx-cpx, top, cx, top);
juce_plutovg_path_close(path);
}
void juce_plutovg_path_add_circle(juce_plutovg_path_t* path, float cx, float cy, float r)
{
juce_plutovg_path_add_ellipse(path, cx, cy, r, r);
}
void juce_plutovg_path_add_arc(juce_plutovg_path_t* path, float cx, float cy, float r, float a0, float a1, bool ccw)
{
float da = a1 - a0;
if(fabsf(da) > JUCE_PLUTOVG_TWO_PI) {
da = JUCE_PLUTOVG_TWO_PI;
} else if(da != 0.f && ccw != (da < 0.f)) {
da += JUCE_PLUTOVG_TWO_PI * (ccw ? -1 : 1);
}
int seg_n = (int)(ceilf(fabsf(da) / JUCE_PLUTOVG_HALF_PI));
if(seg_n == 0)
return;
float a = a0;
float ax = cx + cosf(a) * r;
float ay = cy + sinf(a) * r;
float seg_a = da / seg_n;
float d = (seg_a / JUCE_PLUTOVG_HALF_PI) * JUCE_PLUTOVG_KAPPA * r;
float dx = -sinf(a) * d;
float dy = cosf(a) * d;
juce_plutovg_path_reserve(path, 2 + 4 * seg_n);
if(path->elements.size == 0) {
juce_plutovg_path_move_to(path, ax, ay);
} else {
juce_plutovg_path_line_to(path, ax, ay);
}
for(int i = 0; i < seg_n; i++) {
float cp1x = ax + dx;
float cp1y = ay + dy;
a += seg_a;
ax = cx + cosf(a) * r;
ay = cy + sinf(a) * r;
dx = -sinf(a) * d;
dy = cosf(a) * d;
float cp2x = ax - dx;
float cp2y = ay - dy;
juce_plutovg_path_cubic_to(path, cp1x, cp1y, cp2x, cp2y, ax, ay);
}
}
void juce_plutovg_path_transform(juce_plutovg_path_t* path, const juce_plutovg_matrix_t* matrix)
{
juce_plutovg_path_element_t* elements = path->elements.data;
for(int i = 0; i < path->elements.size; i += elements[i].header.length) {
switch(elements[i].header.command) {
case JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO:
case JUCE_PLUTOVG_PATH_COMMAND_LINE_TO:
case JUCE_PLUTOVG_PATH_COMMAND_CLOSE:
juce_plutovg_matrix_map_point(matrix, &elements[i + 1].point, &elements[i + 1].point);
break;
case JUCE_PLUTOVG_PATH_COMMAND_CUBIC_TO:
juce_plutovg_matrix_map_point(matrix, &elements[i + 1].point, &elements[i + 1].point);
juce_plutovg_matrix_map_point(matrix, &elements[i + 2].point, &elements[i + 2].point);
juce_plutovg_matrix_map_point(matrix, &elements[i + 3].point, &elements[i + 3].point);
break;
}
}
}
void juce_plutovg_path_add_path(juce_plutovg_path_t* path, const juce_plutovg_path_t* source, const juce_plutovg_matrix_t* matrix)
{
if(matrix == NULL) {
juce_plutovg_array_append(path->elements, source->elements);
path->start_point = source->start_point;
path->num_points += source->num_points;
path->num_contours += source->num_contours;
path->num_curves += source->num_curves;
return;
}
juce_plutovg_path_iterator_t it;
juce_plutovg_path_iterator_init(&it, source);
juce_plutovg_point_t points[3];
juce_plutovg_array_ensure(path->elements, source->elements.size);
while(juce_plutovg_path_iterator_has_next(&it)) {
switch(juce_plutovg_path_iterator_next(&it, points)) {
case JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO:
juce_plutovg_matrix_map_points(matrix, points, points, 1);
juce_plutovg_path_move_to(path, points[0].x, points[0].y);
break;
case JUCE_PLUTOVG_PATH_COMMAND_LINE_TO:
juce_plutovg_matrix_map_points(matrix, points, points, 1);
juce_plutovg_path_line_to(path, points[0].x, points[0].y);
break;
case JUCE_PLUTOVG_PATH_COMMAND_CUBIC_TO:
juce_plutovg_matrix_map_points(matrix, points, points, 3);
juce_plutovg_path_cubic_to(path, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y);
break;
case JUCE_PLUTOVG_PATH_COMMAND_CLOSE:
juce_plutovg_path_close(path);
break;
}
}
}
void juce_plutovg_path_traverse(const juce_plutovg_path_t* path, juce_plutovg_path_traverse_func_t traverse_func, void* closure)
{
juce_plutovg_path_iterator_t it;
juce_plutovg_path_iterator_init(&it, path);
juce_plutovg_point_t points[3];
while(juce_plutovg_path_iterator_has_next(&it)) {
switch(juce_plutovg_path_iterator_next(&it, points)) {
case JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO:
traverse_func(closure, JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO, points, 1);
break;
case JUCE_PLUTOVG_PATH_COMMAND_LINE_TO:
traverse_func(closure, JUCE_PLUTOVG_PATH_COMMAND_LINE_TO, points, 1);
break;
case JUCE_PLUTOVG_PATH_COMMAND_CUBIC_TO:
traverse_func(closure, JUCE_PLUTOVG_PATH_COMMAND_CUBIC_TO, points, 3);
break;
case JUCE_PLUTOVG_PATH_COMMAND_CLOSE:
traverse_func(closure, JUCE_PLUTOVG_PATH_COMMAND_CLOSE, points, 1);
break;
}
}
}
typedef struct {
float x1; float y1;
float x2; float y2;
float x3; float y3;
float x4; float y4;
} bezier_t;
static inline void split_bezier(const bezier_t* b, bezier_t* first, bezier_t* second)
{
float c = (b->x2 + b->x3) * 0.5f;
first->x2 = (b->x1 + b->x2) * 0.5f;
second->x3 = (b->x3 + b->x4) * 0.5f;
first->x1 = b->x1;
second->x4 = b->x4;
first->x3 = (first->x2 + c) * 0.5f;
second->x2 = (second->x3 + c) * 0.5f;
first->x4 = second->x1 = (first->x3 + second->x2) * 0.5f;
c = (b->y2 + b->y3) * 0.5f;
first->y2 = (b->y1 + b->y2) * 0.5f;
second->y3 = (b->y3 + b->y4) * 0.5f;
first->y1 = b->y1;
second->y4 = b->y4;
first->y3 = (first->y2 + c) * 0.5f;
second->y2 = (second->y3 + c) * 0.5f;
first->y4 = second->y1 = (first->y3 + second->y2) * 0.5f;
}
void juce_plutovg_path_traverse_flatten(const juce_plutovg_path_t* path, juce_plutovg_path_traverse_func_t traverse_func, void* closure)
{
if(path->num_curves == 0) {
juce_plutovg_path_traverse(path, traverse_func, closure);
return;
}
const float threshold = 0.25f;
juce_plutovg_path_iterator_t it;
juce_plutovg_path_iterator_init(&it, path);
bezier_t beziers[32];
juce_plutovg_point_t points[3];
juce_plutovg_point_t current_point = {0, 0};
while(juce_plutovg_path_iterator_has_next(&it)) {
juce_plutovg_path_command_t command = juce_plutovg_path_iterator_next(&it, points);
switch(command) {
case JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO:
case JUCE_PLUTOVG_PATH_COMMAND_LINE_TO:
case JUCE_PLUTOVG_PATH_COMMAND_CLOSE:
traverse_func(closure, command, points, 1);
current_point = points[0];
break;
case JUCE_PLUTOVG_PATH_COMMAND_CUBIC_TO:
beziers[0].x1 = current_point.x;
beziers[0].y1 = current_point.y;
beziers[0].x2 = points[0].x;
beziers[0].y2 = points[0].y;
beziers[0].x3 = points[1].x;
beziers[0].y3 = points[1].y;
beziers[0].x4 = points[2].x;
beziers[0].y4 = points[2].y;
bezier_t* b = beziers;
while(b >= beziers) {
float y4y1 = b->y4 - b->y1;
float x4x1 = b->x4 - b->x1;
float l = fabsf(x4x1) + fabsf(y4y1);
float d;
if(l > 1.f) {
d = fabsf((x4x1)*(b->y1 - b->y2) - (y4y1)*(b->x1 - b->x2)) + fabsf((x4x1)*(b->y1 - b->y3) - (y4y1)*(b->x1 - b->x3));
} else {
d = fabsf(b->x1 - b->x2) + fabsf(b->y1 - b->y2) + fabsf(b->x1 - b->x3) + fabsf(b->y1 - b->y3);
l = 1.f;
}
if(d < threshold*l || b == beziers + 31) {
juce_plutovg_point_t p = { b->x4, b->y4 };
traverse_func(closure, JUCE_PLUTOVG_PATH_COMMAND_LINE_TO, &p, 1);
--b;
} else {
split_bezier(b, b + 1, b);
++b;
}
}
current_point = points[2];
break;
}
}
}
typedef struct {
const float* dashes; int ndashes;
float start_phase; float phase;
int start_index; int index;
bool start_toggle; bool toggle;
juce_plutovg_point_t current_point;
juce_plutovg_path_traverse_func_t traverse_func;
void* closure;
} dasher_t;
static void dash_traverse_func(void* closure, juce_plutovg_path_command_t command, const juce_plutovg_point_t* points, int npoints)
{
dasher_t* dasher = (dasher_t*)(closure);
if(command == JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO) {
if(dasher->start_toggle)
dasher->traverse_func(dasher->closure, JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO, points, npoints);
dasher->current_point = points[0];
dasher->phase = dasher->start_phase;
dasher->index = dasher->start_index;
dasher->toggle = dasher->start_toggle;
return;
}
assert(command == JUCE_PLUTOVG_PATH_COMMAND_LINE_TO || command == JUCE_PLUTOVG_PATH_COMMAND_CLOSE);
juce_plutovg_point_t p0 = dasher->current_point;
juce_plutovg_point_t p1 = points[0];
float dx = p1.x - p0.x;
float dy = p1.y - p0.y;
float dist0 = sqrtf(dx*dx + dy*dy);
float dist1 = 0.f;
while(dist0 - dist1 > dasher->dashes[dasher->index % dasher->ndashes] - dasher->phase) {
dist1 += dasher->dashes[dasher->index % dasher->ndashes] - dasher->phase;
float a = dist1 / dist0;
juce_plutovg_point_t p = { p0.x + a * dx, p0.y + a * dy };
if(dasher->toggle) {
dasher->traverse_func(dasher->closure, JUCE_PLUTOVG_PATH_COMMAND_LINE_TO, &p, 1);
} else {
dasher->traverse_func(dasher->closure, JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO, &p, 1);
}
dasher->phase = 0.f;
dasher->toggle = !dasher->toggle;
dasher->index++;
}
if(dasher->toggle) {
dasher->traverse_func(dasher->closure, JUCE_PLUTOVG_PATH_COMMAND_LINE_TO, &p1, 1);
}
dasher->phase += dist0 - dist1;
dasher->current_point = p1;
}
void juce_plutovg_path_traverse_dashed(const juce_plutovg_path_t* path, float offset, const float* dashes, int ndashes, juce_plutovg_path_traverse_func_t traverse_func, void* closure)
{
float dash_sum = 0.f;
for(int i = 0; i < ndashes; ++i)
dash_sum += dashes[i];
if(ndashes % 2 == 1)
dash_sum *= 2.f;
if(dash_sum <= 0.f) {
juce_plutovg_path_traverse(path, traverse_func, closure);
return;
}
dasher_t dasher;
dasher.dashes = dashes;
dasher.ndashes = ndashes;
dasher.start_phase = fmodf(offset, dash_sum);
if(dasher.start_phase < 0.f)
dasher.start_phase += dash_sum;
dasher.start_index = 0;
dasher.start_toggle = true;
while(dasher.start_phase > 0.f && dasher.start_phase >= dasher.dashes[dasher.start_index % dasher.ndashes]) {
dasher.start_phase -= dashes[dasher.start_index % dasher.ndashes];
dasher.start_toggle = !dasher.start_toggle;
dasher.start_index++;
}
dasher.phase = dasher.start_phase;
dasher.index = dasher.start_index;
dasher.toggle = dasher.start_toggle;
dasher.current_point = JUCE_PLUTOVG_EMPTY_POINT;
dasher.traverse_func = traverse_func;
dasher.closure = closure;
juce_plutovg_path_traverse_flatten(path, dash_traverse_func, &dasher);
}
juce_plutovg_path_t* juce_plutovg_path_clone(const juce_plutovg_path_t* path)
{
juce_plutovg_path_t* clone = juce_plutovg_path_create();
juce_plutovg_array_append(clone->elements, path->elements);
clone->start_point = path->start_point;
clone->num_points = path->num_points;
clone->num_contours = path->num_contours;
clone->num_curves = path->num_curves;
return clone;
}
static void clone_traverse_func(void* closure, juce_plutovg_path_command_t command, const juce_plutovg_point_t* points, int npoints)
{
juce_plutovg_path_t* path = (juce_plutovg_path_t*)(closure);
switch(command) {
case JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO:
juce_plutovg_path_move_to(path, points[0].x, points[0].y);
break;
case JUCE_PLUTOVG_PATH_COMMAND_LINE_TO:
juce_plutovg_path_line_to(path, points[0].x, points[0].y);
break;
case JUCE_PLUTOVG_PATH_COMMAND_CUBIC_TO:
juce_plutovg_path_cubic_to(path, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y);
break;
case JUCE_PLUTOVG_PATH_COMMAND_CLOSE:
juce_plutovg_path_close(path);
break;
}
}
juce_plutovg_path_t* juce_plutovg_path_clone_flatten(const juce_plutovg_path_t* path)
{
juce_plutovg_path_t* clone = juce_plutovg_path_create();
juce_plutovg_path_reserve(clone, path->elements.size + path->num_curves * 32);
juce_plutovg_path_traverse_flatten(path, clone_traverse_func, clone);
return clone;
}
juce_plutovg_path_t* juce_plutovg_path_clone_dashed(const juce_plutovg_path_t* path, float offset, const float* dashes, int ndashes)
{
juce_plutovg_path_t* clone = juce_plutovg_path_create();
juce_plutovg_path_reserve(clone, path->elements.size + path->num_curves * 32);
juce_plutovg_path_traverse_dashed(path, offset, dashes, ndashes, clone_traverse_func, clone);
return clone;
}
typedef struct {
juce_plutovg_point_t current_point;
bool is_first_point;
float length;
float x1;
float y1;
float x2;
float y2;
} extents_calculator_t;
static void extents_traverse_func(void* closure, juce_plutovg_path_command_t command, const juce_plutovg_point_t* points, int npoints)
{
extents_calculator_t* calculator = (extents_calculator_t*)(closure);
if(calculator->is_first_point) {
assert(command == JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO);
calculator->is_first_point = false;
calculator->current_point = points[0];
calculator->x1 = points[0].x;
calculator->y1 = points[0].y;
calculator->x2 = points[0].x;
calculator->y2 = points[0].y;
calculator->length = 0;
return;
}
for(int i = 0; i < npoints; ++i) {
calculator->x1 = juce_plutovg_min(calculator->x1, points[i].x);
calculator->y1 = juce_plutovg_min(calculator->y1, points[i].y);
calculator->x2 = juce_plutovg_max(calculator->x2, points[i].x);
calculator->y2 = juce_plutovg_max(calculator->y2, points[i].y);
if(command != JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO)
calculator->length += hypotf(points[i].x - calculator->current_point.x, points[i].y - calculator->current_point.y);
calculator->current_point = points[i];
}
}
float juce_plutovg_path_extents(const juce_plutovg_path_t* path, juce_plutovg_rect_t* extents, bool tight)
{
extents_calculator_t calculator = {{0, 0}, true, 0, 0, 0, 0, 0};
if(tight) {
juce_plutovg_path_traverse_flatten(path, extents_traverse_func, &calculator);
} else {
juce_plutovg_path_traverse(path, extents_traverse_func, &calculator);
}
if(extents) {
extents->x = calculator.x1;
extents->y = calculator.y1;
extents->w = calculator.x2 - calculator.x1;
extents->h = calculator.y2 - calculator.y1;
}
return calculator.length;
}
float juce_plutovg_path_length(const juce_plutovg_path_t* path)
{
return juce_plutovg_path_extents(path, NULL, true);
}
static inline bool parse_arc_flag(const char** begin, const char* end, bool* flag)
{
if(juce_plutovg_skip_delim(begin, end, '0'))
*flag = 0;
else if(juce_plutovg_skip_delim(begin, end, '1'))
*flag = 1;
else
return false;
juce_plutovg_skip_ws_or_comma(begin, end, NULL);
return true;
}
static inline bool parse_path_coordinates(const char** begin, const char* end, float values[6], int offset, int count)
{
for(int i = 0; i < count; i++) {
if(!juce_plutovg_parse_number(begin, end, values + offset + i))
return false;
juce_plutovg_skip_ws_or_comma(begin, end, NULL);
}
return true;
}
bool juce_plutovg_path_parse(juce_plutovg_path_t* path, const char* data, int length)
{
if(length == -1)
length = strlen(data);
const char* it = data;
const char* end = it + length;
float values[6];
bool flags[2];
float start_x = 0;
float start_y = 0;
float current_x = 0;
float current_y = 0;
float last_control_x = 0;
float last_control_y = 0;
char command = 0;
char last_command = 0;
juce_plutovg_skip_ws(&it, end);
while(it < end) {
if(JUCE_PLUTOVG_IS_ALPHA(*it)) {
command = *it++;
juce_plutovg_skip_ws(&it, end);
}
if(!last_command && !(command == 'M' || command == 'm'))
return false;
if(command == 'M' || command == 'm') {
if(!parse_path_coordinates(&it, end, values, 0, 2))
return false;
if(command == 'm') {
values[0] += current_x;
values[1] += current_y;
}
juce_plutovg_path_move_to(path, values[0], values[1]);
current_x = start_x = values[0];
current_y = start_y = values[1];
command = command == 'm' ? 'l' : 'L';
} else if(command == 'L' || command == 'l') {
if(!parse_path_coordinates(&it, end, values, 0, 2))
return false;
if(command == 'l') {
values[0] += current_x;
values[1] += current_y;
}
juce_plutovg_path_line_to(path, values[0], values[1]);
current_x = values[0];
current_y = values[1];
} else if(command == 'H' || command == 'h') {
if(!parse_path_coordinates(&it, end, values, 0, 1))
return false;
if(command == 'h') {
values[0] += current_x;
}
juce_plutovg_path_line_to(path, values[0], current_y);
current_x = values[0];
} else if(command == 'V' || command == 'v') {
if(!parse_path_coordinates(&it, end, values, 1, 1))
return false;
if(command == 'v') {
values[1] += current_y;
}
juce_plutovg_path_line_to(path, current_x, values[1]);
current_y = values[1];
} else if(command == 'Q' || command == 'q') {
if(!parse_path_coordinates(&it, end, values, 0, 4))
return false;
if(command == 'q') {
values[0] += current_x;
values[1] += current_y;
values[2] += current_x;
values[3] += current_y;
}
juce_plutovg_path_quad_to(path, values[0], values[1], values[2], values[3]);
last_control_x = values[0];
last_control_y = values[1];
current_x = values[2];
current_y = values[3];
} else if(command == 'C' || command == 'c') {
if(!parse_path_coordinates(&it, end, values, 0, 6))
return false;
if(command == 'c') {
values[0] += current_x;
values[1] += current_y;
values[2] += current_x;
values[3] += current_y;
values[4] += current_x;
values[5] += current_y;
}
juce_plutovg_path_cubic_to(path, values[0], values[1], values[2], values[3], values[4], values[5]);
last_control_x = values[2];
last_control_y = values[3];
current_x = values[4];
current_y = values[5];
} else if(command == 'T' || command == 't') {
if(last_command != 'Q' && last_command != 'q' && last_command != 'T' && last_command != 't') {
values[0] = current_x;
values[1] = current_y;
} else {
values[0] = 2 * current_x - last_control_x;
values[1] = 2 * current_y - last_control_y;
}
if(!parse_path_coordinates(&it, end, values, 2, 2))
return false;
if(command == 't') {
values[2] += current_x;
values[3] += current_y;
}
juce_plutovg_path_quad_to(path, values[0], values[1], values[2], values[3]);
last_control_x = values[0];
last_control_y = values[1];
current_x = values[2];
current_y = values[3];
} else if(command == 'S' || command == 's') {
if(last_command != 'C' && last_command != 'c' && last_command != 'S' && last_command != 's') {
values[0] = current_x;
values[1] = current_y;
} else {
values[0] = 2 * current_x - last_control_x;
values[1] = 2 * current_y - last_control_y;
}
if(!parse_path_coordinates(&it, end, values, 2, 4))
return false;
if(command == 's') {
values[2] += current_x;
values[3] += current_y;
values[4] += current_x;
values[5] += current_y;
}
juce_plutovg_path_cubic_to(path, values[0], values[1], values[2], values[3], values[4], values[5]);
last_control_x = values[2];
last_control_y = values[3];
current_x = values[4];
current_y = values[5];
} else if(command == 'A' || command == 'a') {
if(!parse_path_coordinates(&it, end, values, 0, 3)
|| !parse_arc_flag(&it, end, &flags[0])
|| !parse_arc_flag(&it, end, &flags[1])
|| !parse_path_coordinates(&it, end, values, 3, 2)) {
return false;
}
if(command == 'a') {
values[3] += current_x;
values[4] += current_y;
}
juce_plutovg_path_arc_to(path, values[0], values[1], JUCE_PLUTOVG_DEG2RAD(values[2]), flags[0], flags[1], values[3], values[4]);
current_x = values[3];
current_y = values[4];
} else if(command == 'Z' || command == 'z') {
if(last_command == 'Z' || last_command == 'z')
return false;
juce_plutovg_path_close(path);
current_x = start_x;
current_y = start_y;
} else {
return false;
}
last_command = command;
}
return true;
}
@@ -0,0 +1,180 @@
#ifndef JUCE_PLUTOVG_PRIVATE_H
#define JUCE_PLUTOVG_PRIVATE_H
#include "../include/plutovg.h"
#if defined(_WIN32)
#include <windows.h>
typedef LONG juce_plutovg_ref_count_t;
#define juce_plutovg_init_reference(ob) ((ob)->ref_count = 1)
#define juce_plutovg_increment_reference(ob) (void)(ob && InterlockedIncrement(&(ob)->ref_count))
#define juce_plutovg_destroy_reference(ob) (ob && InterlockedDecrement(&(ob)->ref_count) == 0)
#define juce_plutovg_get_reference_count(ob) ((ob) ? InterlockedCompareExchange((LONG*)&(ob)->ref_count, 0, 0) : 0)
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_ATOMICS__)
#include <stdatomic.h>
typedef atomic_int juce_plutovg_ref_count_t;
#define juce_plutovg_init_reference(ob) atomic_init(&(ob)->ref_count, 1)
#define juce_plutovg_increment_reference(ob) (void)(ob && atomic_fetch_add(&(ob)->ref_count, 1))
#define juce_plutovg_destroy_reference(ob) (ob && atomic_fetch_sub(&(ob)->ref_count, 1) == 1)
#define juce_plutovg_get_reference_count(ob) ((ob) ? atomic_load(&(ob)->ref_count) : 0)
#else
typedef int juce_plutovg_ref_count_t;
#define juce_plutovg_init_reference(ob) ((ob)->ref_count = 1)
#define juce_plutovg_increment_reference(ob) (void)(ob && ++(ob)->ref_count)
#define juce_plutovg_destroy_reference(ob) (ob && --(ob)->ref_count == 0)
#define juce_plutovg_get_reference_count(ob) ((ob) ? (ob)->ref_count : 0)
#endif
struct juce_plutovg_surface {
juce_plutovg_ref_count_t ref_count;
int width;
int height;
int stride;
unsigned char* data;
};
struct juce_plutovg_path {
juce_plutovg_ref_count_t ref_count;
int num_points;
int num_contours;
int num_curves;
juce_plutovg_point_t start_point;
struct {
juce_plutovg_path_element_t* data;
int size;
int capacity;
} elements;
};
typedef enum {
JUCE_PLUTOVG_PAINT_TYPE_COLOR,
JUCE_PLUTOVG_PAINT_TYPE_GRADIENT,
JUCE_PLUTOVG_PAINT_TYPE_TEXTURE
} juce_plutovg_paint_type_t;
struct juce_plutovg_paint {
juce_plutovg_ref_count_t ref_count;
juce_plutovg_paint_type_t type;
};
typedef struct {
juce_plutovg_paint_t base;
juce_plutovg_color_t color;
} juce_plutovg_solid_paint_t;
typedef enum {
JUCE_PLUTOVG_GRADIENT_TYPE_LINEAR,
JUCE_PLUTOVG_GRADIENT_TYPE_RADIAL
} juce_plutovg_gradient_type_t;
typedef struct {
juce_plutovg_paint_t base;
juce_plutovg_gradient_type_t type;
juce_plutovg_spread_method_t spread;
juce_plutovg_matrix_t matrix;
juce_plutovg_gradient_stop_t* stops;
int nstops;
float values[6];
} juce_plutovg_gradient_paint_t;
typedef struct {
juce_plutovg_paint_t base;
juce_plutovg_texture_type_t type;
float opacity;
juce_plutovg_matrix_t matrix;
juce_plutovg_surface_t* surface;
} juce_plutovg_texture_paint_t;
typedef struct {
int x;
int len;
int y;
unsigned char coverage;
} juce_plutovg_span_t;
typedef struct {
struct {
juce_plutovg_span_t* data;
int size;
int capacity;
} spans;
int x;
int y;
int w;
int h;
} juce_plutovg_span_buffer_t;
typedef struct {
float offset;
struct {
float* data;
int size;
int capacity;
} array;
} juce_plutovg_stroke_dash_t;
typedef struct {
float width;
juce_plutovg_line_cap_t cap;
juce_plutovg_line_join_t join;
float miter_limit;
} juce_plutovg_stroke_style_t;
typedef struct {
juce_plutovg_stroke_style_t style;
juce_plutovg_stroke_dash_t dash;
} juce_plutovg_stroke_data_t;
typedef struct juce_plutovg_state {
juce_plutovg_paint_t* paint;
juce_plutovg_font_face_t* font_face;
juce_plutovg_color_t color;
juce_plutovg_matrix_t matrix;
juce_plutovg_stroke_data_t stroke;
juce_plutovg_span_buffer_t clip_spans;
juce_plutovg_fill_rule_t winding;
juce_plutovg_operator_t op;
float font_size;
float opacity;
bool clipping;
struct juce_plutovg_state* next;
} juce_plutovg_state_t;
struct juce_plutovg_canvas {
juce_plutovg_ref_count_t ref_count;
juce_plutovg_surface_t* surface;
juce_plutovg_path_t* path;
juce_plutovg_state_t* state;
juce_plutovg_state_t* freed_state;
juce_plutovg_font_face_cache_t* face_cache;
juce_plutovg_rect_t clip_rect;
juce_plutovg_span_buffer_t clip_spans;
juce_plutovg_span_buffer_t fill_spans;
};
void juce_plutovg_span_buffer_init(juce_plutovg_span_buffer_t* span_buffer);
void juce_plutovg_span_buffer_init_rect(juce_plutovg_span_buffer_t* span_buffer, int x, int y, int width, int height);
void juce_plutovg_span_buffer_reset(juce_plutovg_span_buffer_t* span_buffer);
void juce_plutovg_span_buffer_destroy(juce_plutovg_span_buffer_t* span_buffer);
void juce_plutovg_span_buffer_copy(juce_plutovg_span_buffer_t* span_buffer, const juce_plutovg_span_buffer_t* source);
bool juce_plutovg_span_buffer_contains(const juce_plutovg_span_buffer_t* span_buffer, float x, float y);
void juce_plutovg_span_buffer_extents(juce_plutovg_span_buffer_t* span_buffer, juce_plutovg_rect_t* extents);
void juce_plutovg_span_buffer_intersect(juce_plutovg_span_buffer_t* span_buffer, const juce_plutovg_span_buffer_t* a, const juce_plutovg_span_buffer_t* b);
void juce_plutovg_rasterize(juce_plutovg_span_buffer_t* span_buffer, const juce_plutovg_path_t* path, const juce_plutovg_matrix_t* matrix, const juce_plutovg_rect_t* clip_rect, const juce_plutovg_stroke_data_t* stroke_data, juce_plutovg_fill_rule_t winding);
void juce_plutovg_blend(juce_plutovg_canvas_t* canvas, const juce_plutovg_span_buffer_t* span_buffer);
void juce_plutovg_memfill32(unsigned int* dest, int length, unsigned int value);
#endif // JUCE_PLUTOVG_PRIVATE_H
@@ -0,0 +1,394 @@
#include "plutovg-private.h"
#include "plutovg-utils.h"
#include "plutovg-ft-raster.h"
#include "plutovg-ft-stroker.h"
#include <limits.h>
void juce_plutovg_span_buffer_init(juce_plutovg_span_buffer_t* span_buffer)
{
juce_plutovg_array_init(span_buffer->spans);
juce_plutovg_span_buffer_reset(span_buffer);
}
void juce_plutovg_span_buffer_init_rect(juce_plutovg_span_buffer_t* span_buffer, int x, int y, int width, int height)
{
juce_plutovg_array_clear(span_buffer->spans);
juce_plutovg_array_ensure(span_buffer->spans, height);
juce_plutovg_span_t* spans = span_buffer->spans.data;
for(int i = 0; i < height; i++) {
spans[i].x = x;
spans[i].y = y + i;
spans[i].len = width;
spans[i].coverage = 255;
}
span_buffer->x = x;
span_buffer->y = y;
span_buffer->w = width;
span_buffer->h = height;
span_buffer->spans.size = height;
}
void juce_plutovg_span_buffer_reset(juce_plutovg_span_buffer_t* span_buffer)
{
juce_plutovg_array_clear(span_buffer->spans);
span_buffer->x = 0;
span_buffer->y = 0;
span_buffer->w = -1;
span_buffer->h = -1;
}
void juce_plutovg_span_buffer_destroy(juce_plutovg_span_buffer_t* span_buffer)
{
juce_plutovg_array_destroy(span_buffer->spans);
}
void juce_plutovg_span_buffer_copy(juce_plutovg_span_buffer_t* span_buffer, const juce_plutovg_span_buffer_t* source)
{
juce_plutovg_array_clear(span_buffer->spans);
juce_plutovg_array_append(span_buffer->spans, source->spans);
span_buffer->x = source->x;
span_buffer->y = source->y;
span_buffer->w = source->w;
span_buffer->h = source->h;
}
bool juce_plutovg_span_buffer_contains(const juce_plutovg_span_buffer_t* span_buffer, float x, float y)
{
const int ix = (int)floorf(x);
const int iy = (int)floorf(y);
for(int i = 0; i < span_buffer->spans.size; i++) {
juce_plutovg_span_t* span = &span_buffer->spans.data[i];
if(span->y != iy)
continue;
if(ix >= span->x && ix < (span->x + span->len)) {
return true;
}
}
return false;
}
static void juce_plutovg_span_buffer_update_extents(juce_plutovg_span_buffer_t* span_buffer)
{
if(span_buffer->w != -1 && span_buffer->h != -1)
return;
if(span_buffer->spans.size == 0) {
span_buffer->x = 0;
span_buffer->y = 0;
span_buffer->w = 0;
span_buffer->h = 0;
return;
}
juce_plutovg_span_t* spans = span_buffer->spans.data;
int x1 = INT_MAX;
int y1 = spans[0].y;
int x2 = 0;
int y2 = spans[span_buffer->spans.size - 1].y;
for(int i = 0; i < span_buffer->spans.size; i++) {
if(spans[i].x < x1) x1 = spans[i].x;
if(spans[i].x + spans[i].len > x2) x2 = spans[i].x + spans[i].len;
}
span_buffer->x = x1;
span_buffer->y = y1;
span_buffer->w = x2 - x1;
span_buffer->h = y2 - y1 + 1;
}
void juce_plutovg_span_buffer_extents(juce_plutovg_span_buffer_t* span_buffer, juce_plutovg_rect_t* extents)
{
juce_plutovg_span_buffer_update_extents(span_buffer);
extents->x = span_buffer->x;
extents->y = span_buffer->y;
extents->w = span_buffer->w;
extents->h = span_buffer->h;
}
void juce_plutovg_span_buffer_intersect(juce_plutovg_span_buffer_t* span_buffer, const juce_plutovg_span_buffer_t* a, const juce_plutovg_span_buffer_t* b)
{
juce_plutovg_span_buffer_reset(span_buffer);
juce_plutovg_array_ensure(span_buffer->spans, juce_plutovg_max(a->spans.size, b->spans.size));
juce_plutovg_span_t* a_spans = a->spans.data;
juce_plutovg_span_t* a_end = a_spans + a->spans.size;
juce_plutovg_span_t* b_spans = b->spans.data;
juce_plutovg_span_t* b_end = b_spans + b->spans.size;
while(a_spans < a_end && b_spans < b_end) {
if(b_spans->y > a_spans->y) {
++a_spans;
continue;
}
if(a_spans->y != b_spans->y) {
++b_spans;
continue;
}
int ax1 = a_spans->x;
int ax2 = ax1 + a_spans->len;
int bx1 = b_spans->x;
int bx2 = bx1 + b_spans->len;
if(bx1 < ax1 && bx2 < ax1) {
++b_spans;
continue;
}
if(ax1 < bx1 && ax2 < bx1) {
++a_spans;
continue;
}
int x = juce_plutovg_max(ax1, bx1);
int len = juce_plutovg_min(ax2, bx2) - x;
if(len) {
juce_plutovg_array_ensure(span_buffer->spans, 1);
juce_plutovg_span_t* span = span_buffer->spans.data + span_buffer->spans.size;
span->x = x;
span->len = len;
span->y = a_spans->y;
span->coverage = (a_spans->coverage * b_spans->coverage) / 255;
span_buffer->spans.size += 1;
}
if(ax2 < bx2) {
++a_spans;
} else {
++b_spans;
}
}
}
#define ALIGN_SIZE(size) (((size) + 7ul) & ~7ul)
static PVG_FT_Outline* ft_outline_create(int points, int contours)
{
size_t points_size = ALIGN_SIZE((points + contours) * sizeof(PVG_FT_Vector));
size_t tags_size = ALIGN_SIZE((points + contours) * sizeof(char));
size_t contours_size = ALIGN_SIZE(contours * sizeof(int));
size_t contours_flag_size = ALIGN_SIZE(contours * sizeof(char));
PVG_FT_Outline* outline = malloc(points_size + tags_size + contours_size + contours_flag_size + sizeof(PVG_FT_Outline));
PVG_FT_Byte* outline_data = (PVG_FT_Byte*)(outline + 1);
outline->points = (PVG_FT_Vector*)(outline_data);
outline->tags = (char*)(outline_data + points_size);
outline->contours = (int*)(outline_data + points_size + tags_size);
outline->contours_flag = (char*)(outline_data + points_size + tags_size + contours_size);
outline->n_points = 0;
outline->n_contours = 0;
outline->flags = 0x0;
return outline;
}
static void ft_outline_destroy(PVG_FT_Outline* outline)
{
free(outline);
}
#define FT_COORD(x) (PVG_FT_Pos)(roundf(x * 64))
static void ft_outline_move_to(PVG_FT_Outline* ft, float x, float y)
{
ft->points[ft->n_points].x = FT_COORD(x);
ft->points[ft->n_points].y = FT_COORD(y);
ft->tags[ft->n_points] = PVG_FT_CURVE_TAG_ON;
if(ft->n_points) {
ft->contours[ft->n_contours] = ft->n_points - 1;
ft->n_contours++;
}
ft->contours_flag[ft->n_contours] = 1;
ft->n_points++;
}
static void ft_outline_line_to(PVG_FT_Outline* ft, float x, float y)
{
ft->points[ft->n_points].x = FT_COORD(x);
ft->points[ft->n_points].y = FT_COORD(y);
ft->tags[ft->n_points] = PVG_FT_CURVE_TAG_ON;
ft->n_points++;
}
static void ft_outline_cubic_to(PVG_FT_Outline* ft, float x1, float y1, float x2, float y2, float x3, float y3)
{
ft->points[ft->n_points].x = FT_COORD(x1);
ft->points[ft->n_points].y = FT_COORD(y1);
ft->tags[ft->n_points] = PVG_FT_CURVE_TAG_CUBIC;
ft->n_points++;
ft->points[ft->n_points].x = FT_COORD(x2);
ft->points[ft->n_points].y = FT_COORD(y2);
ft->tags[ft->n_points] = PVG_FT_CURVE_TAG_CUBIC;
ft->n_points++;
ft->points[ft->n_points].x = FT_COORD(x3);
ft->points[ft->n_points].y = FT_COORD(y3);
ft->tags[ft->n_points] = PVG_FT_CURVE_TAG_ON;
ft->n_points++;
}
static void ft_outline_close(PVG_FT_Outline* ft)
{
ft->contours_flag[ft->n_contours] = 0;
int index = ft->n_contours ? ft->contours[ft->n_contours - 1] + 1 : 0;
if(index == ft->n_points)
return;
ft->points[ft->n_points].x = ft->points[index].x;
ft->points[ft->n_points].y = ft->points[index].y;
ft->tags[ft->n_points] = PVG_FT_CURVE_TAG_ON;
ft->n_points++;
}
static void ft_outline_end(PVG_FT_Outline* ft)
{
if(ft->n_points) {
ft->contours[ft->n_contours] = ft->n_points - 1;
ft->n_contours++;
}
}
static PVG_FT_Outline* ft_outline_convert_stroke(const juce_plutovg_path_t* path, const juce_plutovg_matrix_t* matrix, const juce_plutovg_stroke_data_t* stroke_data);
static PVG_FT_Outline* ft_outline_convert(const juce_plutovg_path_t* path, const juce_plutovg_matrix_t* matrix, const juce_plutovg_stroke_data_t* stroke_data)
{
if(stroke_data) {
return ft_outline_convert_stroke(path, matrix, stroke_data);
}
juce_plutovg_path_iterator_t it;
juce_plutovg_path_iterator_init(&it, path);
juce_plutovg_point_t points[3];
PVG_FT_Outline* outline = ft_outline_create(path->num_points, path->num_contours);
while(juce_plutovg_path_iterator_has_next(&it)) {
switch(juce_plutovg_path_iterator_next(&it, points)) {
case JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO:
juce_plutovg_matrix_map_points(matrix, points, points, 1);
ft_outline_move_to(outline, points[0].x, points[0].y);
break;
case JUCE_PLUTOVG_PATH_COMMAND_LINE_TO:
juce_plutovg_matrix_map_points(matrix, points, points, 1);
ft_outline_line_to(outline, points[0].x, points[0].y);
break;
case JUCE_PLUTOVG_PATH_COMMAND_CUBIC_TO:
juce_plutovg_matrix_map_points(matrix, points, points, 3);
ft_outline_cubic_to(outline, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y);
break;
case JUCE_PLUTOVG_PATH_COMMAND_CLOSE:
ft_outline_close(outline);
break;
}
}
ft_outline_end(outline);
return outline;
}
static PVG_FT_Outline* ft_outline_convert_dash(const juce_plutovg_path_t* path, const juce_plutovg_matrix_t* matrix, const juce_plutovg_stroke_dash_t* stroke_dash)
{
if(stroke_dash->array.size == 0)
return ft_outline_convert(path, matrix, NULL);
juce_plutovg_path_t* dashed = juce_plutovg_path_clone_dashed(path, stroke_dash->offset, stroke_dash->array.data, stroke_dash->array.size);
PVG_FT_Outline* outline = ft_outline_convert(dashed, matrix, NULL);
juce_plutovg_path_destroy(dashed);
return outline;
}
static PVG_FT_Outline* ft_outline_convert_stroke(const juce_plutovg_path_t* path, const juce_plutovg_matrix_t* matrix, const juce_plutovg_stroke_data_t* stroke_data)
{
double scale_x = sqrt(matrix->a * matrix->a + matrix->b * matrix->b);
double scale_y = sqrt(matrix->c * matrix->c + matrix->d * matrix->d);
double scale = hypot(scale_x, scale_y) / JUCE_PLUTOVG_SQRT2;
double width = stroke_data->style.width * scale;
PVG_FT_Fixed ftWidth = (PVG_FT_Fixed)(width * 0.5 * (1 << 6));
PVG_FT_Fixed ftMiterLimit = (PVG_FT_Fixed)(stroke_data->style.miter_limit * (1 << 16));
PVG_FT_Stroker_LineCap ftCap;
switch(stroke_data->style.cap) {
case JUCE_PLUTOVG_LINE_CAP_SQUARE:
ftCap = PVG_FT_STROKER_LINECAP_SQUARE;
break;
case JUCE_PLUTOVG_LINE_CAP_ROUND:
ftCap = PVG_FT_STROKER_LINECAP_ROUND;
break;
default:
ftCap = PVG_FT_STROKER_LINECAP_BUTT;
break;
}
PVG_FT_Stroker_LineJoin ftJoin;
switch(stroke_data->style.join) {
case JUCE_PLUTOVG_LINE_JOIN_BEVEL:
ftJoin = PVG_FT_STROKER_LINEJOIN_BEVEL;
break;
case JUCE_PLUTOVG_LINE_JOIN_ROUND:
ftJoin = PVG_FT_STROKER_LINEJOIN_ROUND;
break;
default:
ftJoin = PVG_FT_STROKER_LINEJOIN_MITER_FIXED;
break;
}
PVG_FT_Stroker stroker;
PVG_FT_Stroker_New(&stroker);
PVG_FT_Stroker_Set(stroker, ftWidth, ftCap, ftJoin, ftMiterLimit);
PVG_FT_Outline* outline = ft_outline_convert_dash(path, matrix, &stroke_data->dash);
PVG_FT_Stroker_ParseOutline(stroker, outline);
PVG_FT_UInt points;
PVG_FT_UInt contours;
PVG_FT_Stroker_GetCounts(stroker, &points, &contours);
PVG_FT_Outline* stroke_outline = ft_outline_create(points, contours);
PVG_FT_Stroker_Export(stroker, stroke_outline);
PVG_FT_Stroker_Done(stroker);
ft_outline_destroy(outline);
return stroke_outline;
}
static void spans_generation_callback(int count, const PVG_FT_Span* spans, void* user)
{
juce_plutovg_span_buffer_t* span_buffer = (juce_plutovg_span_buffer_t*)(user);
juce_plutovg_array_append_data(span_buffer->spans, spans, count);
}
void juce_plutovg_rasterize(juce_plutovg_span_buffer_t* span_buffer, const juce_plutovg_path_t* path, const juce_plutovg_matrix_t* matrix, const juce_plutovg_rect_t* clip_rect, const juce_plutovg_stroke_data_t* stroke_data, juce_plutovg_fill_rule_t winding)
{
PVG_FT_Outline* outline = ft_outline_convert(path, matrix, stroke_data);
if(stroke_data) {
outline->flags = PVG_FT_OUTLINE_NONE;
} else {
switch(winding) {
case JUCE_PLUTOVG_FILL_RULE_EVEN_ODD:
outline->flags = PVG_FT_OUTLINE_EVEN_ODD_FILL;
break;
default:
outline->flags = PVG_FT_OUTLINE_NONE;
break;
}
}
PVG_FT_Raster_Params params;
params.flags = PVG_FT_RASTER_FLAG_DIRECT | PVG_FT_RASTER_FLAG_AA;
params.gray_spans = spans_generation_callback;
params.user = span_buffer;
params.source = outline;
if(clip_rect) {
params.flags |= PVG_FT_RASTER_FLAG_CLIP;
params.clip_box.xMin = (PVG_FT_Pos)clip_rect->x;
params.clip_box.yMin = (PVG_FT_Pos)clip_rect->y;
params.clip_box.xMax = (PVG_FT_Pos)(clip_rect->x + clip_rect->w);
params.clip_box.yMax = (PVG_FT_Pos)(clip_rect->y + clip_rect->h);
}
juce_plutovg_span_buffer_reset(span_buffer);
PVG_FT_Raster_Render(&params);
ft_outline_destroy(outline);
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,295 @@
#include "plutovg-private.h"
#include "plutovg-utils.h"
#define STB_IMAGE_WRITE_STATIC
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "plutovg-stb-image-write.h"
#define STB_IMAGE_STATIC
#define STB_IMAGE_IMPLEMENTATION
#include "plutovg-stb-image.h"
static juce_plutovg_surface_t* juce_plutovg_surface_create_uninitialized(int width, int height)
{
static const int kMaxSize = 1 << 15;
if(width <= 0 || height <= 0 || width >= kMaxSize || height >= kMaxSize)
return NULL;
const size_t size = width * height * 4;
juce_plutovg_surface_t* surface = malloc(size + sizeof(juce_plutovg_surface_t));
if(surface == NULL)
return NULL;
juce_plutovg_init_reference(surface);
surface->width = width;
surface->height = height;
surface->stride = width * 4;
surface->data = (uint8_t*)(surface + 1);
return surface;
}
juce_plutovg_surface_t* juce_plutovg_surface_create(int width, int height)
{
juce_plutovg_surface_t* surface = juce_plutovg_surface_create_uninitialized(width, height);
if(surface)
memset(surface->data, 0, surface->height * surface->stride);
return surface;
}
juce_plutovg_surface_t* juce_plutovg_surface_create_for_data(unsigned char* data, int width, int height, int stride)
{
juce_plutovg_surface_t* surface = malloc(sizeof(juce_plutovg_surface_t));
juce_plutovg_init_reference(surface);
surface->width = width;
surface->height = height;
surface->stride = stride;
surface->data = data;
return surface;
}
static juce_plutovg_surface_t* juce_plutovg_surface_load_from_image(stbi_uc* image, int width, int height)
{
juce_plutovg_surface_t* surface = juce_plutovg_surface_create_uninitialized(width, height);
if(surface)
juce_plutovg_convert_rgba_to_argb(surface->data, image, surface->width, surface->height, surface->stride);
stbi_image_free(image);
return surface;
}
juce_plutovg_surface_t* juce_plutovg_surface_load_from_image_file(const char* filename)
{
int width, height, channels;
stbi_uc* image = stbi_load(filename, &width, &height, &channels, STBI_rgb_alpha);
if(image == NULL)
return NULL;
return juce_plutovg_surface_load_from_image(image, width, height);
}
juce_plutovg_surface_t* juce_plutovg_surface_load_from_image_data(const void* data, int length)
{
int width, height, channels;
stbi_uc* image = stbi_load_from_memory(data, length, &width, &height, &channels, STBI_rgb_alpha);
if(image == NULL)
return NULL;
return juce_plutovg_surface_load_from_image(image, width, height);
}
static const uint8_t base64_table[128] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x3F,
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B,
0x3C, 0x3D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
0x17, 0x18, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20,
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30,
0x31, 0x32, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00
};
juce_plutovg_surface_t* juce_plutovg_surface_load_from_image_base64(const char* data, int length)
{
juce_plutovg_surface_t* surface = NULL;
uint8_t* output_data = NULL;
size_t output_length = 0;
size_t equals_sign_count = 0;
size_t sidx = 0;
size_t didx = 0;
if(length == -1)
length = strlen(data);
output_data = malloc(length);
if(output_data == NULL)
return NULL;
for(int i = 0; i < length; ++i) {
uint8_t cc = data[i];
if(cc == '=') {
++equals_sign_count;
} else if(cc == '+' || cc == '/' || JUCE_PLUTOVG_IS_ALNUM(cc)) {
if(equals_sign_count > 0)
goto cleanup;
output_data[output_length++] = base64_table[cc];
} else if(!JUCE_PLUTOVG_IS_WS(cc)) {
goto cleanup;
}
}
if(output_length == 0 || equals_sign_count > 2 || (output_length % 4) == 1)
goto cleanup;
output_length -= (output_length + 3) / 4;
if(output_length == 0) {
goto cleanup;
}
if(output_length > 1) {
while(didx < output_length - 2) {
output_data[didx + 0] = (((output_data[sidx + 0] << 2) & 255) | ((output_data[sidx + 1] >> 4) & 003));
output_data[didx + 1] = (((output_data[sidx + 1] << 4) & 255) | ((output_data[sidx + 2] >> 2) & 017));
output_data[didx + 2] = (((output_data[sidx + 2] << 6) & 255) | ((output_data[sidx + 3] >> 0) & 077));
sidx += 4;
didx += 3;
}
}
if(didx < output_length)
output_data[didx] = (((output_data[sidx + 0] << 2) & 255) | ((output_data[sidx + 1] >> 4) & 003));
if(++didx < output_length) {
output_data[didx] = (((output_data[sidx + 1] << 4) & 255) | ((output_data[sidx + 2] >> 2) & 017));
}
surface = juce_plutovg_surface_load_from_image_data(output_data, output_length);
cleanup:
free(output_data);
return surface;
}
juce_plutovg_surface_t* juce_plutovg_surface_reference(juce_plutovg_surface_t* surface)
{
juce_plutovg_increment_reference(surface);
return surface;
}
void juce_plutovg_surface_destroy(juce_plutovg_surface_t* surface)
{
if(juce_plutovg_destroy_reference(surface)) {
free(surface);
}
}
int juce_plutovg_surface_get_reference_count(const juce_plutovg_surface_t* surface)
{
return juce_plutovg_get_reference_count(surface);
}
unsigned char* juce_plutovg_surface_get_data(const juce_plutovg_surface_t* surface)
{
return surface->data;
}
int juce_plutovg_surface_get_width(const juce_plutovg_surface_t* surface)
{
return surface->width;
}
int juce_plutovg_surface_get_height(const juce_plutovg_surface_t* surface)
{
return surface->height;
}
int juce_plutovg_surface_get_stride(const juce_plutovg_surface_t* surface)
{
return surface->stride;
}
void juce_plutovg_surface_clear(juce_plutovg_surface_t* surface, const juce_plutovg_color_t* color)
{
uint32_t pixel = juce_plutovg_premultiply_argb(juce_plutovg_color_to_argb32(color));
for(int y = 0; y < surface->height; y++) {
uint32_t* pixels = (uint32_t*)(surface->data + surface->stride * y);
juce_plutovg_memfill32(pixels, surface->width, pixel);
}
}
static void juce_plutovg_surface_write_begin(const juce_plutovg_surface_t* surface)
{
juce_plutovg_convert_argb_to_rgba(surface->data, surface->data, surface->width, surface->height, surface->stride);
}
static void juce_plutovg_surface_write_end(const juce_plutovg_surface_t* surface)
{
juce_plutovg_convert_rgba_to_argb(surface->data, surface->data, surface->width, surface->height, surface->stride);
}
bool juce_plutovg_surface_write_to_png(const juce_plutovg_surface_t* surface, const char* filename)
{
juce_plutovg_surface_write_begin(surface);
int success = stbi_write_png(filename, surface->width, surface->height, 4, surface->data, surface->stride);
juce_plutovg_surface_write_end(surface);
return success;
}
bool juce_plutovg_surface_write_to_jpg(const juce_plutovg_surface_t* surface, const char* filename, int quality)
{
juce_plutovg_surface_write_begin(surface);
int success = stbi_write_jpg(filename, surface->width, surface->height, 4, surface->data, quality);
juce_plutovg_surface_write_end(surface);
return success;
}
bool juce_plutovg_surface_write_to_png_stream(const juce_plutovg_surface_t* surface, juce_plutovg_write_func_t write_func, void* closure)
{
juce_plutovg_surface_write_begin(surface);
int success = stbi_write_png_to_func(write_func, closure, surface->width, surface->height, 4, surface->data, surface->stride);
juce_plutovg_surface_write_end(surface);
return success;
}
bool juce_plutovg_surface_write_to_jpg_stream(const juce_plutovg_surface_t* surface, juce_plutovg_write_func_t write_func, void* closure, int quality)
{
juce_plutovg_surface_write_begin(surface);
int success = stbi_write_jpg_to_func(write_func, closure, surface->width, surface->height, 4, surface->data, quality);
juce_plutovg_surface_write_end(surface);
return success;
}
void juce_plutovg_convert_argb_to_rgba(unsigned char* dst, const unsigned char* src, int width, int height, int stride)
{
for(int y = 0; y < height; y++) {
const uint32_t* src_row = (const uint32_t*)(src + stride * y);
unsigned char* dst_row = dst + stride * y;
for(int x = 0; x < width; x++) {
uint32_t pixel = src_row[x];
uint32_t a = (pixel >> 24) & 0xFF;
if(a == 0) {
*dst_row++ = 0;
*dst_row++ = 0;
*dst_row++ = 0;
*dst_row++ = 0;
} else {
uint32_t r = (pixel >> 16) & 0xFF;
uint32_t g = (pixel >> 8) & 0xFF;
uint32_t b = (pixel >> 0) & 0xFF;
if(a != 255) {
r = (r * 255) / a;
g = (g * 255) / a;
b = (b * 255) / a;
}
*dst_row++ = r;
*dst_row++ = g;
*dst_row++ = b;
*dst_row++ = a;
}
}
}
}
void juce_plutovg_convert_rgba_to_argb(unsigned char* dst, const unsigned char* src, int width, int height, int stride)
{
for(int y = 0; y < height; y++) {
const unsigned char* src_row = src + stride * y;
uint32_t* dst_row = (uint32_t*)(dst + stride * y);
for(int x = 0; x < width; x++) {
uint32_t a = src_row[4 * x + 3];
if(a == 0) {
dst_row[x] = 0x00000000;
} else {
uint32_t r = src_row[4 * x + 0];
uint32_t g = src_row[4 * x + 1];
uint32_t b = src_row[4 * x + 2];
if(a != 255) {
r = (r * a) / 255;
g = (g * a) / 255;
b = (b * a) / 255;
}
dst_row[x] = (a << 24) | (r << 16) | (g << 8) | b;
}
}
}
}
@@ -0,0 +1,211 @@
#ifndef JUCE_PLUTOVG_UTILS_H
#define JUCE_PLUTOVG_UTILS_H
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <float.h>
#include <math.h>
#define JUCE_PLUTOVG_IS_NUM(c) ((c) >= '0' && (c) <= '9')
#define JUCE_PLUTOVG_IS_ALPHA(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z'))
#define JUCE_PLUTOVG_IS_ALNUM(c) (JUCE_PLUTOVG_IS_ALPHA(c) || JUCE_PLUTOVG_IS_NUM(c))
#define JUCE_PLUTOVG_IS_WS(c) ((c) == ' ' || (c) == '\t' || (c) == '\n' || (c) == '\r')
#define juce_plutovg_min(a, b) ((a) < (b) ? (a) : (b))
#define juce_plutovg_max(a, b) ((a) > (b) ? (a) : (b))
#define juce_plutovg_clamp(v, lo, hi) ((v) < (lo) ? (lo) : ((v) > (hi) ? (hi) : (v)))
#define juce_plutovg_alpha(c) (((c) >> 24) & 0xff)
#define juce_plutovg_red(c) (((c) >> 16) & 0xff)
#define juce_plutovg_green(c) (((c) >> 8) & 0xff)
#define juce_plutovg_blue(c) (((c) >> 0) & 0xff)
#define juce_plutovg_array_init(array) \
do { \
(array).data = NULL; \
(array).size = 0; \
(array).capacity = 0; \
} while(0)
#define juce_plutovg_array_ensure(array, count) \
do { \
if((array).size + (count) > (array).capacity) { \
int capacity = (array).size + (count); \
int newcapacity = (array).capacity == 0 ? 8 : (array).capacity; \
while(newcapacity < capacity) { newcapacity *= 2; } \
(array).data = realloc((array).data, newcapacity * sizeof((array).data[0])); \
(array).capacity = newcapacity; \
} \
} while(0)
#define juce_plutovg_array_append_data(array, newdata, count) \
do { \
if(newdata && count > 0) { \
juce_plutovg_array_ensure(array, count); \
memcpy((array).data + (array).size, newdata, (count) * sizeof((newdata)[0])); \
(array).size += count; \
} \
} while(0)
#define juce_plutovg_array_append(array, other) juce_plutovg_array_append_data(array, (other).data, (other).size)
#define juce_plutovg_array_clear(array) ((array).size = 0)
#define juce_plutovg_array_destroy(array) free((array).data)
static inline uint32_t juce_plutovg_premultiply_argb(uint32_t color)
{
uint32_t a = juce_plutovg_alpha(color);
uint32_t r = juce_plutovg_red(color);
uint32_t g = juce_plutovg_green(color);
uint32_t b = juce_plutovg_blue(color);
if(a != 255) {
r = (r * a) / 255;
g = (g * a) / 255;
b = (b * a) / 255;
}
return (a << 24) | (r << 16) | (g << 8) | (b);
}
static inline bool juce_plutovg_parse_number(const char** begin, const char* end, float* number)
{
const char* it = *begin;
float integer = 0;
float fraction = 0;
float exponent = 0;
int sign = 1;
int expsign = 1;
if(it < end && *it == '+') {
++it;
} else if(it < end && *it == '-') {
++it;
sign = -1;
}
if(it >= end || (*it != '.' && !JUCE_PLUTOVG_IS_NUM(*it)))
return false;
if(JUCE_PLUTOVG_IS_NUM(*it)) {
do {
integer = 10.f * integer + (*it++ - '0');
} while(it < end && JUCE_PLUTOVG_IS_NUM(*it));
}
if(it < end && *it == '.') {
++it;
if(it >= end || !JUCE_PLUTOVG_IS_NUM(*it))
return false;
float divisor = 1.f;
do {
fraction = 10.f * fraction + (*it++ - '0');
divisor *= 10.f;
} while(it < end && JUCE_PLUTOVG_IS_NUM(*it));
fraction /= divisor;
}
if(it < end && (*it == 'e' || *it == 'E')) {
++it;
if(it < end && *it == '+') {
++it;
} else if(it < end && *it == '-') {
++it;
expsign = -1;
}
if(it >= end || !JUCE_PLUTOVG_IS_NUM(*it))
return false;
do {
exponent = 10 * exponent + (*it++ - '0');
} while(it < end && JUCE_PLUTOVG_IS_NUM(*it));
}
*begin = it;
*number = sign * (integer + fraction);
if(exponent)
*number *= powf(10.f, expsign * exponent);
return *number >= -FLT_MAX && *number <= FLT_MAX;
}
static inline bool juce_plutovg_skip_delim(const char** begin, const char* end, const char delim)
{
const char* it = *begin;
if(it < end && *it == delim) {
*begin = it + 1;
return true;
}
return false;
}
static inline bool juce_plutovg_skip_string(const char** begin, const char* end, const char* data)
{
const char* it = *begin;
while(it < end && *data && *it == *data) {
++data;
++it;
}
if(*data == '\0') {
*begin = it;
return true;
}
return false;
}
static inline bool juce_plutovg_skip_ws(const char** begin, const char* end)
{
const char* it = *begin;
while(it < end && JUCE_PLUTOVG_IS_WS(*it))
++it;
*begin = it;
return it < end;
}
static inline bool juce_plutovg_skip_ws_and_delim(const char** begin, const char* end, char delim)
{
const char* it = *begin;
if(juce_plutovg_skip_ws(&it, end)) {
if(!juce_plutovg_skip_delim(&it, end, delim))
return false;
juce_plutovg_skip_ws(&it, end);
} else {
return false;
}
*begin = it;
return it < end;
}
static inline bool juce_plutovg_skip_ws_and_comma(const char** begin, const char* end)
{
return juce_plutovg_skip_ws_and_delim(begin, end, ',');
}
static inline bool juce_plutovg_skip_ws_or_delim(const char** begin, const char* end, char delim, bool* has_delim)
{
const char* it = *begin;
if(has_delim)
*has_delim = false;
if(juce_plutovg_skip_ws(&it, end)) {
if(juce_plutovg_skip_delim(&it, end, delim)) {
if(has_delim)
*has_delim = true;
juce_plutovg_skip_ws(&it, end);
}
}
if(it == *begin)
return false;
*begin = it;
return it < end;
}
static inline bool juce_plutovg_skip_ws_or_comma(const char** begin, const char* end, bool* has_comma)
{
return juce_plutovg_skip_ws_or_delim(begin, end, ',', has_comma);
}
#endif // JUCE_PLUTOVG_UTILS_H
@@ -0,0 +1,687 @@
#include "graphics.h"
#include "../include/lunasvg.h"
#include <cfloat>
#include <cmath>
namespace {
namespace lunasvg {
const Color Color::Black(0xFF000000);
const Color Color::White(0xFFFFFFFF);
const Color Color::Transparent(0x00000000);
const Rect Rect::Empty(0, 0, 0, 0);
const Rect Rect::Invalid(0, 0, -1, -1);
const Rect Rect::Infinite(-FLT_MAX / 2.f, -FLT_MAX / 2.f, FLT_MAX, FLT_MAX);
Rect::Rect(const Box& box)
: x(box.x), y(box.y), w(box.w), h(box.h)
{
}
const Transform Transform::Identity(1, 0, 0, 1, 0, 0);
Transform::Transform()
{
juce_plutovg_matrix_init_identity(&m_matrix);
}
Transform::Transform(float a, float b, float c, float d, float e, float f)
{
juce_plutovg_matrix_init(&m_matrix, a, b, c, d, e, f);
}
Transform::Transform(const Matrix& matrix)
: Transform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f)
{
}
Transform Transform::operator*(const Transform& transform) const
{
juce_plutovg_matrix_t result;
juce_plutovg_matrix_multiply(&result, &transform.m_matrix, &m_matrix);
return result;
}
Transform& Transform::operator*=(const Transform& transform)
{
return (*this = *this * transform);
}
Transform& Transform::multiply(const Transform& transform)
{
return (*this *= transform);
}
Transform& Transform::translate(float tx, float ty)
{
return multiply(translated(tx, ty));
}
Transform& Transform::scale(float sx, float sy)
{
return multiply(scaled(sx, sy));
}
Transform& Transform::rotate(float angle, float cx, float cy)
{
return multiply(rotated(angle, cx, cy));
}
Transform& Transform::shear(float shx, float shy)
{
return multiply(sheared(shx, shy));
}
Transform& Transform::postMultiply(const Transform& transform)
{
return (*this = transform * *this);
}
Transform& Transform::postTranslate(float tx, float ty)
{
return postMultiply(translated(tx, ty));
}
Transform& Transform::postScale(float sx, float sy)
{
return postMultiply(scaled(sx, sy));
}
Transform& Transform::postRotate(float angle, float cx, float cy)
{
return postMultiply(rotated(angle, cx, cy));
}
Transform& Transform::postShear(float shx, float shy)
{
return postMultiply(sheared(shx, shy));
}
Transform Transform::inverse() const
{
juce_plutovg_matrix_t inverse;
juce_plutovg_matrix_invert(&m_matrix, &inverse);
return inverse;
}
Transform& Transform::invert()
{
juce_plutovg_matrix_invert(&m_matrix, &m_matrix);
return *this;
}
void Transform::reset()
{
juce_plutovg_matrix_init_identity(&m_matrix);
}
Point Transform::mapPoint(float x, float y) const
{
juce_plutovg_matrix_map(&m_matrix, x, y, &x, &y);
return Point(x, y);
}
Point Transform::mapPoint(const Point& point) const
{
return mapPoint(point.x, point.y);
}
Rect Transform::mapRect(const Rect& rect) const
{
if(!rect.isValid()) {
return Rect::Invalid;
}
juce_plutovg_rect_t result = {rect.x, rect.y, rect.w, rect.h};
juce_plutovg_matrix_map_rect(&m_matrix, &result, &result);
return result;
}
float Transform::xScale() const
{
return std::sqrt(m_matrix.a * m_matrix.a + m_matrix.b * m_matrix.b);
}
float Transform::yScale() const
{
return std::sqrt(m_matrix.c * m_matrix.c + m_matrix.d * m_matrix.d);
}
bool Transform::parse(const char* data, size_t length)
{
return juce_plutovg_matrix_parse(&m_matrix, data, length);
}
Transform Transform::rotated(float angle, float cx, float cy)
{
juce_plutovg_matrix_t matrix;
if(cx == 0.f && cy == 0.f) {
juce_plutovg_matrix_init_rotate(&matrix, JUCE_PLUTOVG_DEG2RAD(angle));
} else {
juce_plutovg_matrix_init_translate(&matrix, cx, cy);
juce_plutovg_matrix_rotate(&matrix, JUCE_PLUTOVG_DEG2RAD(angle));
juce_plutovg_matrix_translate(&matrix, -cx, -cy);
}
return matrix;
}
Transform Transform::scaled(float sx, float sy)
{
juce_plutovg_matrix_t matrix;
juce_plutovg_matrix_init_scale(&matrix, sx, sy);
return matrix;
}
Transform Transform::sheared(float shx, float shy)
{
juce_plutovg_matrix_t matrix;
juce_plutovg_matrix_init_shear(&matrix, JUCE_PLUTOVG_DEG2RAD(shx), JUCE_PLUTOVG_DEG2RAD(shy));
return matrix;
}
Transform Transform::translated(float tx, float ty)
{
juce_plutovg_matrix_t matrix;
juce_plutovg_matrix_init_translate(&matrix, tx, ty);
return matrix;
}
Path::Path(const Path& path)
: m_data(juce_plutovg_path_reference(path.data()))
{
}
Path::Path(Path&& path)
: m_data(path.release())
{
}
Path::~Path()
{
juce_plutovg_path_destroy(m_data);
}
Path& Path::operator=(const Path& path)
{
Path(path).swap(*this);
return *this;
}
Path& Path::operator=(Path&& path)
{
Path(std::move(path)).swap(*this);
return *this;
}
void Path::moveTo(float x, float y)
{
juce_plutovg_path_move_to(ensure(), x, y);
}
void Path::lineTo(float x, float y)
{
juce_plutovg_path_line_to(ensure(), x, y);
}
void Path::quadTo(float x1, float y1, float x2, float y2)
{
juce_plutovg_path_quad_to(ensure(), x1, y1, x2, y2);
}
void Path::cubicTo(float x1, float y1, float x2, float y2, float x3, float y3)
{
juce_plutovg_path_cubic_to(ensure(), x1, y1, x2, y2, x3, y3);
}
void Path::arcTo(float rx, float ry, float xAxisRotation, bool largeArcFlag, bool sweepFlag, float x, float y)
{
juce_plutovg_path_arc_to(ensure(), rx, ry, JUCE_PLUTOVG_DEG2RAD(xAxisRotation), largeArcFlag, sweepFlag, x, y);
}
void Path::close()
{
juce_plutovg_path_close(ensure());
}
void Path::addEllipse(float cx, float cy, float rx, float ry)
{
juce_plutovg_path_add_ellipse(ensure(), cx, cy, rx, ry);
}
void Path::addRoundRect(float x, float y, float w, float h, float rx, float ry)
{
juce_plutovg_path_add_round_rect(ensure(), x, y, w, h, rx, ry);
}
void Path::addRect(float x, float y, float w, float h)
{
juce_plutovg_path_add_rect(ensure(), x, y, w, h);
}
void Path::addEllipse(const Point& center, const Size& radii)
{
addEllipse(center.x, center.y, radii.w, radii.h);
}
void Path::addRoundRect(const Rect& rect, const Size& radii)
{
addRoundRect(rect.x, rect.y, rect.w, rect.h, radii.w, radii.h);
}
void Path::addRect(const Rect& rect)
{
addRect(rect.x, rect.y, rect.w, rect.h);
}
void Path::reset()
{
if(m_data == nullptr)
return;
if(isUnique()) {
juce_plutovg_path_reset(m_data);
} else {
juce_plutovg_path_destroy(m_data);
m_data = nullptr;
}
}
Rect Path::boundingRect() const
{
if(m_data == nullptr)
return Rect::Empty;
juce_plutovg_rect_t extents;
juce_plutovg_path_extents(m_data, &extents, false);
return extents;
}
bool Path::isEmpty() const
{
if(m_data)
return juce_plutovg_path_get_elements(m_data, nullptr) == 0;
return true;
}
bool Path::isUnique() const
{
return juce_plutovg_path_get_reference_count(m_data) == 1;
}
bool Path::parse(const char* data, size_t length)
{
juce_plutovg_path_reset(ensure());
return juce_plutovg_path_parse(m_data, data, length);
}
juce_plutovg_path_t* Path::ensure()
{
if(isNull()) {
m_data = juce_plutovg_path_create();
} else if(!isUnique()) {
juce_plutovg_path_destroy(m_data);
m_data = juce_plutovg_path_clone(m_data);
}
return m_data;
}
PathIterator::PathIterator(const Path& path)
: m_size(juce_plutovg_path_get_elements(path.data(), &m_elements))
, m_index(0)
{
}
PathCommand PathIterator::currentSegment(std::array<Point, 3>& points) const
{
auto command = m_elements[m_index].header.command;
switch(command) {
case JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO:
points[0] = m_elements[m_index + 1].point;
break;
case JUCE_PLUTOVG_PATH_COMMAND_LINE_TO:
points[0] = m_elements[m_index + 1].point;
break;
case JUCE_PLUTOVG_PATH_COMMAND_CUBIC_TO:
points[0] = m_elements[m_index + 1].point;
points[1] = m_elements[m_index + 2].point;
points[2] = m_elements[m_index + 3].point;
break;
case JUCE_PLUTOVG_PATH_COMMAND_CLOSE:
points[0] = m_elements[m_index + 1].point;
break;
}
return PathCommand(command);
}
void PathIterator::next()
{
m_index += m_elements[m_index].header.length;
}
FontFace::FontFace(juce_plutovg_font_face_t* face)
: m_face(juce_plutovg_font_face_reference(face))
{
}
FontFace::FontFace(const void* data, size_t length, juce_plutovg_destroy_func_t destroy_func, void* closure)
: m_face(juce_plutovg_font_face_load_from_data(data, length, 0, destroy_func, closure))
{
}
FontFace::FontFace(const char* filename)
: m_face(juce_plutovg_font_face_load_from_file(filename, 0))
{
}
FontFace::FontFace(const FontFace& face)
: m_face(juce_plutovg_font_face_reference(face.get()))
{
}
FontFace::FontFace(FontFace&& face)
: m_face(face.release())
{
}
FontFace::~FontFace()
{
juce_plutovg_font_face_destroy(m_face);
}
FontFace& FontFace::operator=(const FontFace& face)
{
FontFace(face).swap(*this);
return *this;
}
FontFace& FontFace::operator=(FontFace&& face)
{
FontFace(std::move(face)).swap(*this);
return *this;
}
void FontFace::swap(FontFace& face)
{
std::swap(m_face, face.m_face);
}
juce_plutovg_font_face_t* FontFace::release()
{
return std::exchange(m_face, nullptr);
}
bool FontFaceCache::addFontFace(const std::string& family, bool bold, bool italic, const FontFace& face)
{
if(!face.isNull())
juce_plutovg_font_face_cache_add(m_cache, family.data(), bold, italic, face.get());
return !face.isNull();
}
FontFace FontFaceCache::getFontFace(const std::string& family, bool bold, bool italic) const
{
if(auto face = juce_plutovg_font_face_cache_get(m_cache, family.data(), bold, italic)) {
return FontFace(face);
}
static const struct {
const char* generic;
const char* fallback;
} generic_fallbacks[] = {
#if defined(__linux__)
{"sans-serif", "DejaVu Sans"},
{"serif", "DejaVu Serif"},
{"monospace", "DejaVu Sans Mono"},
#else
{"sans-serif", "Arial"},
{"serif", "Times New Roman"},
{"monospace", "Courier New"},
#endif
{"cursive", "Comic Sans MS"},
{"fantasy", "Impact"}
};
for(auto value : generic_fallbacks) {
if(value.generic == family || family.empty()) {
return FontFace(juce_plutovg_font_face_cache_get(m_cache, value.fallback, bold, italic));
}
}
return FontFace();
}
FontFaceCache::FontFaceCache()
: m_cache(juce_plutovg_font_face_cache_create())
{
#ifndef LUNASVG_DISABLE_LOAD_SYSTEM_FONTS
juce_plutovg_font_face_cache_load_sys(m_cache);
#endif
}
FontFaceCache* fontFaceCache()
{
static FontFaceCache cache;
return &cache;
}
std::shared_ptr<Canvas> Canvas::create(const Bitmap& bitmap)
{
return createFromBitmap(bitmap);
}
std::shared_ptr<Canvas> Canvas::create(float x, float y, float width, float height)
{
constexpr int kMaxSize = 1 << 15;
if(width <= 0 || height <= 0 || width >= kMaxSize || height >= kMaxSize)
return createFromBounds(0, 0, 1, 1);
auto l = static_cast<int>(std::floor(x));
auto t = static_cast<int>(std::floor(y));
auto r = static_cast<int>(std::ceil(x + width));
auto b = static_cast<int>(std::ceil(y + height));
return createFromBounds(l, t, r - l, b - t);
}
std::shared_ptr<Canvas> Canvas::create(const Rect& extents)
{
return create(extents.x, extents.y, extents.w, extents.h);
}
std::shared_ptr<Canvas> CanvasImpl::createCanvasImpl(const Bitmap& bitmap)
{
return std::shared_ptr<Canvas>(new CanvasImpl(bitmap));
}
void CanvasImpl::setColor(const Color& color)
{
setColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
}
void CanvasImpl::setColor(float r, float g, float b, float a)
{
juce_plutovg_canvas_set_rgba(m_canvas, r, g, b, a);
}
void CanvasImpl::setLinearGradient(float x1, float y1, float x2, float y2, SpreadMethod spread, const GradientStops& stops, const Transform& transform)
{
juce_plutovg_canvas_set_linear_gradient(m_canvas, x1, y1, x2, y2, static_cast<juce_plutovg_spread_method_t>(spread), stops.data(), stops.size(), &transform.matrix());
}
void CanvasImpl::setRadialGradient(float cx, float cy, float r, float fx, float fy, SpreadMethod spread, const GradientStops& stops, const Transform& transform)
{
juce_plutovg_canvas_set_radial_gradient(m_canvas, cx, cy, r, fx, fy, 0.f, static_cast<juce_plutovg_spread_method_t>(spread), stops.data(), stops.size(), &transform.matrix());
}
void CanvasImpl::setTexture(const Canvas& source, TextureType type, float opacity, const Transform& transform)
{
juce_plutovg_canvas_set_texture(m_canvas, source.surface(), static_cast<juce_plutovg_texture_type_t>(type), opacity, &transform.matrix());
}
void CanvasImpl::fillPath(const Path& path, FillRule fillRule, const Transform& transform)
{
juce_plutovg_canvas_set_matrix(m_canvas, &m_translation);
juce_plutovg_canvas_transform(m_canvas, &transform.matrix());
juce_plutovg_canvas_set_fill_rule(m_canvas, static_cast<juce_plutovg_fill_rule_t>(fillRule));
juce_plutovg_canvas_set_operator(m_canvas, JUCE_PLUTOVG_OPERATOR_SRC_OVER);
juce_plutovg_canvas_fill_path(m_canvas, path.data());
}
void CanvasImpl::strokePath(const Path& path, const StrokeData& strokeData, const Transform& transform)
{
juce_plutovg_canvas_set_matrix(m_canvas, &m_translation);
juce_plutovg_canvas_transform(m_canvas, &transform.matrix());
juce_plutovg_canvas_set_line_width(m_canvas, strokeData.lineWidth());
juce_plutovg_canvas_set_miter_limit(m_canvas, strokeData.miterLimit());
juce_plutovg_canvas_set_line_cap(m_canvas, static_cast<juce_plutovg_line_cap_t>(strokeData.lineCap()));
juce_plutovg_canvas_set_line_join(m_canvas, static_cast<juce_plutovg_line_join_t>(strokeData.lineJoin()));
juce_plutovg_canvas_set_dash_offset(m_canvas, strokeData.dashOffset());
juce_plutovg_canvas_set_dash_array(m_canvas, strokeData.dashArray().data(), strokeData.dashArray().size());
juce_plutovg_canvas_set_operator(m_canvas, JUCE_PLUTOVG_OPERATOR_SRC_OVER);
juce_plutovg_canvas_stroke_path(m_canvas, path.data());
}
void CanvasImpl::fillText(const std::u32string_view& text, const Font& font, const Point& origin, const Transform& transform)
{
juce_plutovg_canvas_set_matrix(m_canvas, &m_translation);
juce_plutovg_canvas_transform(m_canvas, &transform.matrix());
juce_plutovg_canvas_set_fill_rule(m_canvas, JUCE_PLUTOVG_FILL_RULE_NON_ZERO);
juce_plutovg_canvas_set_operator(m_canvas, JUCE_PLUTOVG_OPERATOR_SRC_OVER);
// juce_plutovg_canvas_set_font(m_canvas, font.face().get(), font.size());
juce_plutovg_canvas_fill_text(m_canvas, text.data(), text.length(), JUCE_PLUTOVG_TEXT_ENCODING_UTF32, origin.x, origin.y);
}
void CanvasImpl::strokeText(const std::u32string_view& text, float strokeWidth, const Font& font, const Point& origin, const Transform& transform)
{
juce_plutovg_canvas_set_matrix(m_canvas, &m_translation);
juce_plutovg_canvas_transform(m_canvas, &transform.matrix());
juce_plutovg_canvas_set_line_width(m_canvas, strokeWidth);
juce_plutovg_canvas_set_miter_limit(m_canvas, 4.f);
juce_plutovg_canvas_set_line_cap(m_canvas, JUCE_PLUTOVG_LINE_CAP_BUTT);
juce_plutovg_canvas_set_line_join(m_canvas, JUCE_PLUTOVG_LINE_JOIN_MITER);
juce_plutovg_canvas_set_dash_offset(m_canvas, 0.f);
juce_plutovg_canvas_set_dash_array(m_canvas, nullptr, 0);
juce_plutovg_canvas_set_operator(m_canvas, JUCE_PLUTOVG_OPERATOR_SRC_OVER);
// juce_plutovg_canvas_set_font(m_canvas, font.face().get(), font.size());
juce_plutovg_canvas_stroke_text(m_canvas, text.data(), text.length(), JUCE_PLUTOVG_TEXT_ENCODING_UTF32, origin.x, origin.y);
}
void CanvasImpl::clipPath(const Path& path, FillRule clipRule, const Transform& transform)
{
juce_plutovg_canvas_set_matrix(m_canvas, &m_translation);
juce_plutovg_canvas_transform(m_canvas, &transform.matrix());
juce_plutovg_canvas_set_fill_rule(m_canvas, static_cast<juce_plutovg_fill_rule_t>(clipRule));
juce_plutovg_canvas_clip_path(m_canvas, path.data());
}
void CanvasImpl::clipRect(const Rect& rect, FillRule clipRule, const Transform& transform)
{
juce_plutovg_canvas_set_matrix(m_canvas, &m_translation);
juce_plutovg_canvas_transform(m_canvas, &transform.matrix());
juce_plutovg_canvas_set_fill_rule(m_canvas, static_cast<juce_plutovg_fill_rule_t>(clipRule));
juce_plutovg_canvas_clip_rect(m_canvas, rect.x, rect.y, rect.w, rect.h);
}
void CanvasImpl::drawImage(const Bitmap& image, const Rect& dstRect, const Rect& srcRect, const Transform& transform)
{
auto xScale = dstRect.w / srcRect.w;
auto yScale = dstRect.h / srcRect.h;
juce_plutovg_matrix_t matrix = { xScale, 0, 0, yScale, -srcRect.x * xScale, -srcRect.y * yScale };
juce_plutovg_canvas_set_matrix(m_canvas, &m_translation);
juce_plutovg_canvas_transform(m_canvas, &transform.matrix());
juce_plutovg_canvas_translate(m_canvas, dstRect.x, dstRect.y);
juce_plutovg_canvas_set_fill_rule(m_canvas, JUCE_PLUTOVG_FILL_RULE_NON_ZERO);
juce_plutovg_canvas_set_operator(m_canvas, JUCE_PLUTOVG_OPERATOR_SRC_OVER);
juce_plutovg_canvas_set_texture(m_canvas, image.surface(), JUCE_PLUTOVG_TEXTURE_TYPE_PLAIN, 1.f, &matrix);
juce_plutovg_canvas_fill_rect(m_canvas, 0, 0, dstRect.w, dstRect.h);
}
void CanvasImpl::blendCanvas(const Canvas& canvas, BlendMode blendMode, float opacity)
{
juce_plutovg_matrix_t matrix = { 1, 0, 0, 1, static_cast<float>(canvas.x()), static_cast<float>(canvas.y()) };
juce_plutovg_canvas_set_matrix(m_canvas, &m_translation);
juce_plutovg_canvas_set_operator(m_canvas, static_cast<juce_plutovg_operator_t>(blendMode));
juce_plutovg_canvas_set_texture(m_canvas, canvas.surface(), JUCE_PLUTOVG_TEXTURE_TYPE_PLAIN, opacity, &matrix);
juce_plutovg_canvas_paint(m_canvas);
}
void CanvasImpl::save()
{
juce_plutovg_canvas_save(m_canvas);
}
void CanvasImpl::restore()
{
juce_plutovg_canvas_restore(m_canvas);
}
int CanvasImpl::width() const
{
return juce_plutovg_surface_get_width(m_surface);
}
int CanvasImpl::height() const
{
return juce_plutovg_surface_get_height(m_surface);
}
void CanvasImpl::convertToLuminanceMask()
{
auto width = juce_plutovg_surface_get_width(m_surface);
auto height = juce_plutovg_surface_get_height(m_surface);
auto stride = juce_plutovg_surface_get_stride(m_surface);
auto data = juce_plutovg_surface_get_data(m_surface);
for(int y = 0; y < height; y++) {
auto pixels = reinterpret_cast<uint32_t*>(data + stride * y);
for(int x = 0; x < width; x++) {
auto pixel = pixels[x];
auto a = (pixel >> 24) & 0xFF;
auto r = (pixel >> 16) & 0xFF;
auto g = (pixel >> 8) & 0xFF;
auto b = (pixel >> 0) & 0xFF;
if(a) {
r = (r * 255) / a;
g = (g * 255) / a;
b = (b * 255) / a;
}
auto l = (r * 0.2125 + g * 0.7154 + b * 0.0721);
pixels[x] = static_cast<uint32_t>(l * (a / 255.0)) << 24;
}
}
}
CanvasImpl::~CanvasImpl()
{
juce_plutovg_canvas_destroy(m_canvas);
juce_plutovg_surface_destroy(m_surface);
}
CanvasImpl::CanvasImpl(const Bitmap& bitmap)
: m_surface(juce_plutovg_surface_reference(bitmap.surface()))
, m_canvas(juce_plutovg_canvas_create(m_surface))
, m_translation({1, 0, 0, 1, 0, 0})
, m_x(0), m_y(0)
{
}
CanvasImpl::CanvasImpl(int x, int y, int width, int height)
: m_surface(juce_plutovg_surface_create(width, height))
, m_canvas(juce_plutovg_canvas_create(m_surface))
, m_translation({1, 0, 0, 1, -static_cast<float>(x), -static_cast<float>(y)})
, m_x(x), m_y(y)
{
}
std::shared_ptr<Canvas> CanvasImpl::createFromBounds(int x, int y, int width, int height)
{
return std::shared_ptr<Canvas>(new CanvasImpl(x, y, width, height));
}
std::shared_ptr<Canvas> CanvasImpl::createFromBitmap(const Bitmap& bitmap)
{
return std::shared_ptr<Canvas>(new CanvasImpl(bitmap));
}
} // namespace lunasvg
}
@@ -0,0 +1,588 @@
#ifndef LUNASVG_GRAPHICS_H
#define LUNASVG_GRAPHICS_H
#include "../plutovg/include/plutovg.h"
#include <cstdint>
#include <algorithm>
#include <utility>
#include <memory>
#include <vector>
#include <array>
#include <string>
namespace {
namespace lunasvg {
enum class LineCap : uint8_t {
Butt = JUCE_PLUTOVG_LINE_CAP_BUTT,
Round = JUCE_PLUTOVG_LINE_CAP_ROUND,
Square = JUCE_PLUTOVG_LINE_CAP_SQUARE
};
enum class LineJoin : uint8_t {
Miter = JUCE_PLUTOVG_LINE_JOIN_MITER,
Round = JUCE_PLUTOVG_LINE_JOIN_ROUND,
Bevel = JUCE_PLUTOVG_LINE_JOIN_BEVEL
};
enum class FillRule : uint8_t {
NonZero = JUCE_PLUTOVG_FILL_RULE_NON_ZERO,
EvenOdd = JUCE_PLUTOVG_FILL_RULE_EVEN_ODD
};
enum class SpreadMethod : uint8_t {
Pad = JUCE_PLUTOVG_SPREAD_METHOD_PAD,
Reflect = JUCE_PLUTOVG_SPREAD_METHOD_REFLECT,
Repeat = JUCE_PLUTOVG_SPREAD_METHOD_REPEAT
};
class Color {
public:
constexpr Color() = default;
constexpr explicit Color(uint32_t value) : m_value(value) {}
constexpr Color(int r, int g, int b, int a = 255) : m_value(a << 24 | r << 16 | g << 8 | b) {}
constexpr uint8_t alpha() const { return (m_value >> 24) & 0xff; }
constexpr uint8_t red() const { return (m_value >> 16) & 0xff; }
constexpr uint8_t green() const { return (m_value >> 8) & 0xff; }
constexpr uint8_t blue() const { return (m_value >> 0) & 0xff; }
constexpr float alphaF() const { return alpha() / 255.f; }
constexpr float redF() const { return red() / 255.f; }
constexpr float greenF() const { return green() / 255.f; }
constexpr float blueF() const { return blue() / 255.f; }
constexpr uint32_t value() const { return m_value; }
constexpr bool isOpaque() const { return alpha() == 255; }
constexpr bool isVisible() const { return alpha() > 0; }
constexpr Color opaqueColor() const { return Color(m_value | 0xFF000000); }
constexpr Color colorWithAlpha(float opacity) const;
static const Color Transparent;
static const Color Black;
static const Color White;
private:
uint32_t m_value = 0;
};
constexpr Color Color::colorWithAlpha(float opacity) const
{
auto rgb = m_value & 0x00FFFFFF;
auto a = static_cast<int>(alpha() * std::clamp(opacity, 0.f, 1.f));
return Color(rgb | a << 24);
}
class Point {
public:
constexpr Point() = default;
constexpr Point(const juce_plutovg_point_t& point) : Point(point.x, point.y) {}
constexpr Point(float x, float y) : x(x), y(y) {}
constexpr void move(float dx, float dy) { x += dx; y += dy; }
constexpr void move(float d) { move(d, d); }
constexpr void move(const Point& p) { move(p.x, p.y); }
constexpr void scale(float sx, float sy) { x *= sx; y *= sy; }
constexpr void scale(float s) { scale(s, s); }
constexpr float dot(const Point& p) const { return x * p.x + y * p.y; }
public:
float x{0};
float y{0};
};
constexpr Point operator+(const Point& a, const Point& b)
{
return Point(a.x + b.x, a.y + b.y);
}
constexpr Point operator-(const Point& a, const Point& b)
{
return Point(a.x - b.x, a.y - b.y);
}
constexpr Point operator-(const Point& a)
{
return Point(-a.x, -a.y);
}
constexpr Point& operator+=(Point& a, const Point& b)
{
a.move(b);
return a;
}
constexpr Point& operator-=(Point& a, const Point& b)
{
a.move(-b);
return a;
}
constexpr float operator*(const Point& a, const Point& b)
{
return a.dot(b);
}
class Size {
public:
constexpr Size() = default;
constexpr Size(float w, float h) : w(w), h(h) {}
constexpr void expand(float dw, float dh) { w += dw; h += dh; }
constexpr void expand(float d) { expand(d, d); }
constexpr void expand(const Size& s) { expand(s.w, s.h); }
constexpr void scale(float sw, float sh) { w *= sw; h *= sh; }
constexpr void scale(float s) { scale(s, s); }
constexpr bool isEmpty() const { return w <= 0.f || h <= 0.f; }
constexpr bool isZero() const { return w <= 0.f && h <= 0.f; }
constexpr bool isValid() const { return w >= 0.f && h >= 0.f; }
public:
float w{0};
float h{0};
};
constexpr Size operator+(const Size& a, const Size& b)
{
return Size(a.w + b.w, a.h + b.h);
}
constexpr Size operator-(const Size& a, const Size& b)
{
return Size(a.w - b.w, a.h - b.h);
}
constexpr Size operator-(const Size& a)
{
return Size(-a.w, -a.h);
}
constexpr Size& operator+=(Size& a, const Size& b)
{
a.expand(b);
return a;
}
constexpr Size& operator-=(Size& a, const Size& b)
{
a.expand(-b);
return a;
}
class Box;
class Rect {
public:
constexpr Rect() = default;
constexpr explicit Rect(const Size& size) : Rect(size.w, size.h) {}
constexpr Rect(float width, float height) : Rect(0, 0, width, height) {}
constexpr Rect(const Point& origin, const Size& size) : Rect(origin.x, origin.y, size.w, size.h) {}
constexpr Rect(const juce_plutovg_rect_t& rect) : Rect(rect.x, rect.y, rect.w, rect.h) {}
constexpr Rect(float x, float y, float w, float h) : x(x), y(y), w(w), h(h) {}
Rect(const Box& box);
constexpr void move(float dx, float dy) { x += dx; y += dy; }
constexpr void move(float d) { move(d, d); }
constexpr void move(const Point& p) { move(p.x, p.y); }
constexpr void scale(float sx, float sy) { x *= sx; y *= sy; w *= sx; h *= sy; }
constexpr void scale(float s) { scale(s, s); }
constexpr void inflate(float dx, float dy) { x -= dx; y -= dy; w += dx * 2.f; h += dy * 2.f; }
constexpr void inflate(float d) { inflate(d, d); }
constexpr bool contains(float px, float py) const { return px >= x && px <= x + w && py >= y && py <= y + h; }
constexpr bool contains(const Point& p) const { return contains(p.x, p.y); }
constexpr Rect intersected(const Rect& rect) const;
constexpr Rect united(const Rect& rect) const;
constexpr Rect& intersect(const Rect& o);
constexpr Rect& unite(const Rect& o);
constexpr Point origin() const { return Point(x, y); }
constexpr Size size() const { return Size(w, h); }
constexpr float right() const { return x + w; }
constexpr float bottom() const { return y + h; }
constexpr bool isEmpty() const { return w <= 0.f || h <= 0.f; }
constexpr bool isZero() const { return w <= 0.f && h <= 0.f; }
constexpr bool isValid() const { return w >= 0.f && h >= 0.f; }
static const Rect Empty;
static const Rect Invalid;
static const Rect Infinite;
public:
float x{0};
float y{0};
float w{0};
float h{0};
};
constexpr Rect Rect::intersected(const Rect& rect) const
{
if(!rect.isValid())
return *this;
if(!isValid())
return rect;
auto l = std::max(x, rect.x);
auto t = std::max(y, rect.y);
auto r = std::min(x + w, rect.x + rect.w);
auto b = std::min(y + h, rect.y + rect.h);
if(l >= r || t >= b)
return Rect::Empty;
return Rect(l, t, r - l, b - t);
}
constexpr Rect Rect::united(const Rect& rect) const
{
if(!rect.isValid())
return *this;
if(!isValid())
return rect;
auto l = std::min(x, rect.x);
auto t = std::min(y, rect.y);
auto r = std::max(x + w, rect.x + rect.w);
auto b = std::max(y + h, rect.y + rect.h);
return Rect(l, t, r - l, b - t);
}
constexpr Rect& Rect::intersect(const Rect& o)
{
*this = intersected(o);
return *this;
}
constexpr Rect& Rect::unite(const Rect& o)
{
*this = united(o);
return *this;
}
class Matrix;
class Transform {
public:
Transform();
Transform(const Matrix& matrix);
Transform(float a, float b, float c, float d, float e, float f);
Transform(const juce_plutovg_matrix_t& matrix) : m_matrix(matrix) {}
Transform operator*(const Transform& transform) const;
Transform& operator*=(const Transform& transform);
Transform& multiply(const Transform& transform);
Transform& translate(float tx, float ty);
Transform& scale(float sx, float sy);
Transform& rotate(float angle, float cx = 0.f, float cy = 0.f);
Transform& shear(float shx, float shy);
Transform& postMultiply(const Transform& transform);
Transform& postTranslate(float tx, float ty);
Transform& postScale(float sx, float sy);
Transform& postRotate(float angle, float cx = 0.f, float cy = 0.f);
Transform& postShear(float shx, float shy);
Transform inverse() const;
Transform& invert();
void reset();
Point mapPoint(float x, float y) const;
Point mapPoint(const Point& point) const;
Rect mapRect(const Rect& rect) const;
float xScale() const;
float yScale() const;
const juce_plutovg_matrix_t& matrix() const { return m_matrix; }
juce_plutovg_matrix_t& matrix() { return m_matrix; }
bool parse(const char* data, size_t length);
static Transform translated(float tx, float ty);
static Transform scaled(float sx, float sy);
static Transform rotated(float angle, float cx, float cy);
static Transform sheared(float shx, float shy);
static const Transform Identity;
private:
juce_plutovg_matrix_t m_matrix;
};
enum class PathCommand {
MoveTo = JUCE_PLUTOVG_PATH_COMMAND_MOVE_TO,
LineTo = JUCE_PLUTOVG_PATH_COMMAND_LINE_TO,
CubicTo = JUCE_PLUTOVG_PATH_COMMAND_CUBIC_TO,
Close = JUCE_PLUTOVG_PATH_COMMAND_CLOSE
};
class Path {
public:
Path() = default;
Path(const Path& path);
Path(Path&& path);
~Path();
Path& operator=(const Path& path);
Path& operator=(Path&& path);
void swap(Path& path);
void moveTo(float x, float y);
void lineTo(float x, float y);
void quadTo(float x1, float y1, float x2, float y2);
void cubicTo(float x1, float y1, float x2, float y2, float x3, float y3);
void arcTo(float rx, float ry, float xAxisRotation, bool largeArcFlag, bool sweepFlag, float x, float y);
void close();
void addEllipse(float cx, float cy, float rx, float ry);
void addRoundRect(float x, float y, float w, float h, float rx, float ry);
void addRect(float x, float y, float w, float h);
void addEllipse(const Point& center, const Size& radii);
void addRoundRect(const Rect& rect, const Size& radii);
void addRect(const Rect& rect);
void reset();
Rect boundingRect() const;
bool isEmpty() const;
bool isUnique() const;
bool isNull() const { return m_data == nullptr; }
juce_plutovg_path_t* data() const { return m_data; }
bool parse(const char* data, size_t length);
private:
juce_plutovg_path_t* release();
juce_plutovg_path_t* ensure();
juce_plutovg_path_t* m_data = nullptr;
};
inline void Path::swap(Path& path)
{
std::swap(m_data, path.m_data);
}
inline juce_plutovg_path_t* Path::release()
{
return std::exchange(m_data, nullptr);
}
class PathIterator {
public:
PathIterator(const Path& path);
PathCommand currentSegment(std::array<Point, 3>& points) const;
bool isDone() const { return m_index >= m_size; }
void next();
private:
const juce_plutovg_path_element_t* m_elements;
const int m_size;
int m_index;
};
class FontFace {
public:
FontFace() = default;
explicit FontFace(juce_plutovg_font_face_t* face);
FontFace(const void* data, size_t length, juce_plutovg_destroy_func_t destroy_func, void* closure);
FontFace(const char* filename);
FontFace(const FontFace& face);
FontFace(FontFace&& face);
~FontFace();
FontFace& operator=(const FontFace& face);
FontFace& operator=(FontFace&& face);
void swap(FontFace& face);
bool isNull() const { return m_face == nullptr; }
juce_plutovg_font_face_t* get() const { return m_face; }
private:
juce_plutovg_font_face_t* release();
juce_plutovg_font_face_t* m_face = nullptr;
};
class FontFaceCache {
public:
bool addFontFace(const std::string& family, bool bold, bool italic, const FontFace& face);
FontFace getFontFace(const std::string& family, bool bold, bool italic) const;
private:
FontFaceCache();
juce_plutovg_font_face_cache_t* m_cache;
friend FontFaceCache* fontFaceCache();
};
FontFaceCache* fontFaceCache();
using Font = juce::detail::LunaSvgFontReplacement;
enum class TextureType {
Plain = JUCE_PLUTOVG_TEXTURE_TYPE_PLAIN,
Tiled = JUCE_PLUTOVG_TEXTURE_TYPE_TILED
};
enum class BlendMode {
Src = JUCE_PLUTOVG_OPERATOR_SRC,
Src_Over = JUCE_PLUTOVG_OPERATOR_SRC_OVER,
Dst_In = JUCE_PLUTOVG_OPERATOR_DST_IN,
Dst_Out = JUCE_PLUTOVG_OPERATOR_DST_OUT
};
using DashArray = std::vector<float>;
class StrokeData {
public:
explicit StrokeData(float lineWidth = 1.f) : m_lineWidth(lineWidth) {}
void setLineWidth(float lineWidth) { m_lineWidth = lineWidth; }
float lineWidth() const { return m_lineWidth; }
void setMiterLimit(float miterLimit) { m_miterLimit = miterLimit; }
float miterLimit() const { return m_miterLimit; }
void setDashOffset(float dashOffset) { m_dashOffset = dashOffset; }
float dashOffset() const { return m_dashOffset; }
void setDashArray(DashArray dashArray) { m_dashArray = std::move(dashArray); }
const DashArray& dashArray() const { return m_dashArray; }
void setLineCap(LineCap lineCap) { m_lineCap = lineCap; }
LineCap lineCap() const { return m_lineCap; }
void setLineJoin(LineJoin lineJoin) { m_lineJoin = lineJoin; }
LineJoin lineJoin() const { return m_lineJoin; }
private:
float m_lineWidth;
float m_miterLimit{4.f};
float m_dashOffset{0.f};
LineCap m_lineCap{LineCap::Butt};
LineJoin m_lineJoin{LineJoin::Miter};
DashArray m_dashArray;
};
using GradientStop = juce_plutovg_gradient_stop_t;
using GradientStops = std::vector<GradientStop>;
class Bitmap;
class Canvas {
public:
std::shared_ptr<Canvas> create(const Bitmap& bitmap);
std::shared_ptr<Canvas> create(float x, float y, float width, float height);
std::shared_ptr<Canvas> create(const Rect& extents);
virtual void setColor(const Color& color) = 0;
virtual void setColor(float r, float g, float b, float a) = 0;
virtual void setLinearGradient(float x1, float y1, float x2, float y2, SpreadMethod spread, const GradientStops& stops, const Transform& transform) = 0;
virtual void setRadialGradient(float cx, float cy, float r, float fx, float fy, SpreadMethod spread, const GradientStops& stops, const Transform& transform) = 0;
virtual void setTexture(const Canvas& source, TextureType type, float opacity, const Transform& transform) = 0;
virtual void fillPath(const Path& path, FillRule fillRule, const Transform& transform) = 0;
virtual void strokePath(const Path& path, const StrokeData& strokeData, const Transform& transform) = 0;
virtual void fillText(const std::u32string_view& text, const Font& font, const Point& origin, const Transform& transform) = 0;
virtual void strokeText(const std::u32string_view& text, float strokeWidth, const Font& font, const Point& origin, const Transform& transform) = 0;
virtual void clipPath(const Path& path, FillRule clipRule, const Transform& transform) = 0;
virtual void clipRect(const Rect& rect, FillRule clipRule, const Transform& transform) = 0;
virtual void drawImage(const Bitmap& image, const Rect& dstRect, const Rect& srcRect, const Transform& transform) = 0;
virtual void blendCanvas(const Canvas& canvas, BlendMode blendMode, float opacity) = 0;
virtual void save() = 0;
virtual void restore() = 0;
virtual void convertToLuminanceMask() = 0;
virtual int x() const = 0;
virtual int y() const = 0;
virtual int width() const = 0;
virtual int height() const = 0;
virtual Rect extents() const = 0;
virtual juce_plutovg_surface_t* surface() const = 0;
virtual juce_plutovg_canvas_t* canvas() const = 0;
virtual ~Canvas() = default;
protected:
virtual std::shared_ptr<Canvas> createFromBounds(int x, int y, int width, int height) = 0;
virtual std::shared_ptr<Canvas> createFromBitmap(const Bitmap& bitmap) = 0;
};
class CanvasImpl : public Canvas {
public:
static std::shared_ptr<Canvas> createCanvasImpl(const Bitmap& bitmap);
void setColor(const Color& color) override;
void setColor(float r, float g, float b, float a) override;
void setLinearGradient(float x1, float y1, float x2, float y2, SpreadMethod spread, const GradientStops& stops, const Transform& transform) override;
void setRadialGradient(float cx, float cy, float r, float fx, float fy, SpreadMethod spread, const GradientStops& stops, const Transform& transform) override;
void setTexture(const Canvas& source, TextureType type, float opacity, const Transform& transform) override;
void fillPath(const Path& path, FillRule fillRule, const Transform& transform) override;
void strokePath(const Path& path, const StrokeData& strokeData, const Transform& transform) override;
void fillText(const std::u32string_view& text, const Font& font, const Point& origin, const Transform& transform) override;
void strokeText(const std::u32string_view& text, float strokeWidth, const Font& font, const Point& origin, const Transform& transform) override;
void clipPath(const Path& path, FillRule clipRule, const Transform& transform) override;
void clipRect(const Rect& rect, FillRule clipRule, const Transform& transform) override;
void drawImage(const Bitmap& image, const Rect& dstRect, const Rect& srcRect, const Transform& transform) override;
void blendCanvas(const Canvas& canvas, BlendMode blendMode, float opacity) override;
void save() override;
void restore() override;
void convertToLuminanceMask() override;
int x() const override { return m_x; }
int y() const override { return m_y; }
int width() const override;
int height() const override;
Rect extents() const override { return Rect(m_x, m_y, width(), height()); }
juce_plutovg_surface_t* surface() const override { return m_surface; }
juce_plutovg_canvas_t* canvas() const override { return m_canvas; }
~CanvasImpl() override;
protected:
std::shared_ptr<Canvas> createFromBounds(int x, int y, int width, int height) override;
std::shared_ptr<Canvas> createFromBitmap(const Bitmap& bitmap) override;
private:
CanvasImpl(const Bitmap& bitmap);
CanvasImpl(int x, int y, int width, int height);
juce_plutovg_surface_t* m_surface;
juce_plutovg_canvas_t* m_canvas;
juce_plutovg_matrix_t m_translation;
const int m_x;
const int m_y;
};
} // namespace lunasvg
}
#endif // LUNASVG_GRAPHICS_H
@@ -0,0 +1,543 @@
#include "../include/lunasvg.h"
#include "svgelement.h"
#include "svgrenderstate.h"
#include <cstring>
#include <fstream>
#include <cmath>
namespace {
int lunasvg_version()
{
return LUNASVG_VERSION;
}
const char* lunasvg_version_string()
{
return LUNASVG_VERSION_STRING;
}
bool lunasvg_add_font_face_from_file(const char* family, bool bold, bool italic, const char* filename)
{
return lunasvg::fontFaceCache()->addFontFace(family, bold, italic, lunasvg::FontFace(filename));
}
bool lunasvg_add_font_face_from_data(const char* family, bool bold, bool italic, const void* data, size_t length, lunasvg_destroy_func_t destroy_func, void* closure)
{
return lunasvg::fontFaceCache()->addFontFace(family, bold, italic, lunasvg::FontFace(data, length, destroy_func, closure));
}
namespace lunasvg {
Bitmap::Bitmap(int width, int height)
: m_surface(juce_plutovg_surface_create(width, height))
{
}
Bitmap::Bitmap(uint8_t* data, int width, int height, int stride)
: m_surface(juce_plutovg_surface_create_for_data(data, width, height, stride))
{
}
Bitmap::Bitmap(const Bitmap& bitmap)
: m_surface(juce_plutovg_surface_reference(bitmap.surface()))
{
}
Bitmap::Bitmap(Bitmap&& bitmap)
: m_surface(bitmap.release())
{
}
Bitmap::~Bitmap()
{
juce_plutovg_surface_destroy(m_surface);
}
Bitmap& Bitmap::operator=(const Bitmap& bitmap)
{
Bitmap(bitmap).swap(*this);
return *this;
}
void Bitmap::swap(Bitmap& bitmap)
{
std::swap(m_surface, bitmap.m_surface);
}
uint8_t* Bitmap::data() const
{
if(m_surface)
return juce_plutovg_surface_get_data(m_surface);
return nullptr;
}
int Bitmap::width() const
{
if(m_surface)
return juce_plutovg_surface_get_width(m_surface);
return 0;
}
int Bitmap::height() const
{
if(m_surface)
return juce_plutovg_surface_get_height(m_surface);
return 0;
}
int Bitmap::stride() const
{
if(m_surface)
return juce_plutovg_surface_get_stride(m_surface);
return 0;
}
void Bitmap::clear(uint32_t value)
{
if(m_surface == nullptr)
return;
juce_plutovg_color_t color;
juce_plutovg_color_init_rgba32(&color, value);
juce_plutovg_surface_clear(m_surface, &color);
}
void Bitmap::convertToRGBA()
{
if(m_surface == nullptr)
return;
auto data = juce_plutovg_surface_get_data(m_surface);
auto width = juce_plutovg_surface_get_width(m_surface);
auto height = juce_plutovg_surface_get_height(m_surface);
auto stride = juce_plutovg_surface_get_stride(m_surface);
juce_plutovg_convert_argb_to_rgba(data, data, width, height, stride);
}
Bitmap& Bitmap::operator=(Bitmap&& bitmap)
{
Bitmap(std::move(bitmap)).swap(*this);
return *this;
}
bool Bitmap::writeToPng(const std::string& filename) const
{
if(m_surface)
return juce_plutovg_surface_write_to_png(m_surface, filename.data());
return false;
}
bool Bitmap::writeToPng(lunasvg_write_func_t callback, void* closure) const
{
if(m_surface)
return juce_plutovg_surface_write_to_png_stream(m_surface, callback, closure);
return false;
}
juce_plutovg_surface_t* Bitmap::release()
{
return std::exchange(m_surface, nullptr);
}
Box::Box(float x, float y, float w, float h)
: x(x), y(y), w(w), h(h)
{
}
Box::Box(const Rect& rect)
: x(rect.x), y(rect.y), w(rect.w), h(rect.h)
{
}
Box& Box::transform(const Matrix &matrix)
{
*this = transformed(matrix);
return *this;
}
Box Box::transformed(const Matrix& matrix) const
{
return Transform(matrix).mapRect(*this);
}
Matrix::Matrix(float a, float b, float c, float d, float e, float f)
: a(a), b(b), c(c), d(d), e(e), f(f)
{
}
Matrix::Matrix(const juce_plutovg_matrix_t& matrix)
: a(matrix.a), b(matrix.b), c(matrix.c), d(matrix.d), e(matrix.e), f(matrix.f)
{
}
Matrix::Matrix(const Transform& transform)
: Matrix(transform.matrix())
{
}
Matrix Matrix::operator*(const Matrix& matrix) const
{
return Transform(*this) * Transform(matrix);
}
Matrix& Matrix::operator*=(const Matrix &matrix)
{
return (*this = *this * matrix);
}
Matrix& Matrix::multiply(const Matrix& matrix)
{
return (*this *= matrix);
}
Matrix& Matrix::scale(float sx, float sy)
{
return multiply(scaled(sx, sy));
}
Matrix& Matrix::translate(float tx, float ty)
{
return multiply(translated(tx, ty));
}
Matrix& Matrix::rotate(float angle, float cx, float cy)
{
return multiply(rotated(angle, cx, cy));
}
Matrix& Matrix::shear(float shx, float shy)
{
return multiply(sheared(shx, shy));
}
Matrix Matrix::inverse() const
{
return Transform(*this).inverse();
}
Matrix& Matrix::invert()
{
return (*this = inverse());
}
void Matrix::reset()
{
*this = Matrix(1, 0, 0, 1, 0, 0);
}
Matrix Matrix::translated(float tx, float ty)
{
return Transform::translated(tx, ty);
}
Matrix Matrix::scaled(float sx, float sy)
{
return Transform::scaled(sx, sy);
}
Matrix Matrix::rotated(float angle, float cx, float cy)
{
return Transform::rotated(angle, cx, cy);
}
Matrix Matrix::sheared(float shx, float shy)
{
return Transform::sheared(shx, shy);
}
Node::Node(SVGNode* node)
: m_node(node)
{
}
bool Node::isTextNode() const
{
return m_node && m_node->isTextNode();
}
bool Node::isElement() const
{
return m_node && m_node->isElement();
}
TextNode Node::toTextNode() const
{
if(m_node && m_node->isTextNode())
return static_cast<SVGTextNode*>(m_node);
return TextNode();
}
Element Node::toElement() const
{
if(m_node && m_node->isElement())
return static_cast<SVGElement*>(m_node);
return Element();
}
Element Node::parentElement() const
{
if(m_node)
return m_node->parentElement();
return Element();
}
TextNode::TextNode(SVGTextNode* text)
: Node(text)
{
}
const std::string& TextNode::data() const
{
if(m_node)
return text()->data();
return emptyString;
}
void TextNode::setData(const std::string& data)
{
if(m_node) {
text()->setData(data);
}
}
SVGTextNode* TextNode::text() const
{
return static_cast<SVGTextNode*>(m_node);
}
Element::Element(SVGElement* element)
: Node(element)
{
}
bool Element::hasAttribute(const std::string& name) const
{
if(m_node)
return element()->hasAttribute(name);
return false;
}
const std::string& Element::getAttribute(const std::string& name) const
{
if(m_node)
return element()->getAttribute(name);
return emptyString;
}
void Element::setAttribute(const std::string& name, const std::string& value)
{
if(m_node) {
element()->setAttribute(name, value);
}
}
void Element::render(Bitmap& bitmap, const Matrix& matrix) const
{
if(m_node == nullptr || bitmap.isNull())
return;
auto canvas = CanvasImpl::createCanvasImpl(bitmap);
SVGRenderState state(nullptr, nullptr, matrix, SVGRenderMode::Painting, canvas);
element(true)->render(state);
}
Bitmap Element::renderToBitmap(int width, int height, uint32_t backgroundColor) const
{
if(m_node == nullptr)
return Bitmap();
auto elementBounds = element(true)->localTransform().mapRect(element()->paintBoundingBox());
if(elementBounds.isEmpty())
return Bitmap();
if(width <= 0 && height <= 0) {
width = static_cast<int>(std::ceil(elementBounds.w));
height = static_cast<int>(std::ceil(elementBounds.h));
} else if(width > 0 && height <= 0) {
height = static_cast<int>(std::ceil(width * elementBounds.h / elementBounds.w));
} else if(height > 0 && width <= 0) {
width = static_cast<int>(std::ceil(height * elementBounds.w / elementBounds.h));
}
auto xScale = width / elementBounds.w;
auto yScale = height / elementBounds.h;
Matrix matrix(xScale, 0, 0, yScale, -elementBounds.x * xScale, -elementBounds.y * yScale);
Bitmap bitmap(width, height);
if(backgroundColor) bitmap.clear(backgroundColor);
render(bitmap, matrix);
return bitmap;
}
Matrix Element::getLocalMatrix() const
{
if(m_node)
return element(true)->localTransform();
return Matrix();
}
Matrix Element::getGlobalMatrix() const
{
if(m_node == nullptr)
return Matrix();
auto transform = element(true)->localTransform();
for(auto parent = element()->parentElement(); parent; parent = parent->parentElement())
transform.postMultiply(parent->localTransform());
return transform;
}
Box Element::getLocalBoundingBox() const
{
return getBoundingBox().transformed(getLocalMatrix());
}
Box Element::getGlobalBoundingBox() const
{
return getBoundingBox().transformed(getGlobalMatrix());
}
Box Element::getBoundingBox() const
{
if(m_node)
return element(true)->paintBoundingBox();
return Box();
}
NodeList Element::children() const
{
if(m_node == nullptr)
return NodeList();
NodeList children;
for(const auto& child : element()->children())
children.push_back(child.get());
return children;
}
SVGElement* Element::element(bool layoutIfNeeded) const
{
auto element = static_cast<SVGElement*>(m_node);
if(element && layoutIfNeeded)
element->rootElement()->layoutIfNeeded();
return element;
}
std::unique_ptr<Document> Document::loadFromFile(const std::string& filename)
{
std::ifstream fs;
fs.open(filename);
if(!fs.is_open())
return nullptr;
std::string content;
std::getline(fs, content, '\0');
fs.close();
return loadFromData(content);
}
std::unique_ptr<Document> Document::loadFromData(const std::string& string)
{
return loadFromData(string.data(), string.size());
}
std::unique_ptr<Document> Document::loadFromData(const char* data)
{
return loadFromData(data, std::strlen(data));
}
std::unique_ptr<Document> Document::loadFromData(const char* data, size_t length)
{
std::unique_ptr<Document> document(new Document);
if(!document->parse(data, length))
return nullptr;
return document;
}
float Document::width() const
{
return rootElement(true)->intrinsicWidth();
}
float Document::height() const
{
return rootElement(true)->intrinsicHeight();
}
Box Document::boundingBox() const
{
return rootElement(true)->localTransform().mapRect(rootElement()->paintBoundingBox());
}
void Document::updateLayout()
{
m_rootElement->layoutIfNeeded();
}
void Document::forceLayout()
{
m_rootElement->forceLayout();
}
void Document::renderToCanvas(std::shared_ptr<Canvas> canvas, const Matrix& matrix) const
{
SVGRenderState state(nullptr, nullptr, matrix, SVGRenderMode::Painting, canvas);
rootElement(true)->render(state);
}
void Document::render(Bitmap& bitmap, const Matrix& matrix) const
{
if(bitmap.isNull())
return;
auto canvas = CanvasImpl::createCanvasImpl(bitmap);
renderToCanvas(canvas, matrix);
}
Bitmap Document::renderToBitmap(int width, int height, uint32_t backgroundColor) const
{
auto intrinsicWidth = rootElement(true)->intrinsicWidth();
auto intrinsicHeight = rootElement()->intrinsicHeight();
if(intrinsicWidth == 0.f || intrinsicHeight == 0.f)
return Bitmap();
if(width <= 0 && height <= 0) {
width = static_cast<int>(std::ceil(intrinsicWidth));
height = static_cast<int>(std::ceil(intrinsicHeight));
} else if(width > 0 && height <= 0) {
height = static_cast<int>(std::ceil(width * intrinsicHeight / intrinsicWidth));
} else if(height > 0 && width <= 0) {
width = static_cast<int>(std::ceil(height * intrinsicWidth / intrinsicHeight));
}
auto xScale = width / intrinsicWidth;
auto yScale = height / intrinsicHeight;
Matrix matrix(xScale, 0, 0, yScale, 0, 0);
Bitmap bitmap(width, height);
if(backgroundColor) bitmap.clear(backgroundColor);
render(bitmap, matrix);
return bitmap;
}
Element Document::elementFromPoint(float x, float y) const
{
return rootElement(true)->elementFromPoint(x, y);
}
Element Document::getElementById(const std::string& id) const
{
return m_rootElement->getElementById(id);
}
Element Document::documentElement() const
{
return m_rootElement.get();
}
SVGRootElement* Document::rootElement(bool layoutIfNeeded) const
{
if(layoutIfNeeded)
m_rootElement->layoutIfNeeded();
return m_rootElement.get();
}
Document::Document(Document&&) = default;
Document& Document::operator=(Document&&) = default;
Document::Document() = default;
Document::~Document() = default;
} // namespace lunasvg
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,500 @@
#ifndef LUNASVG_SVGELEMENT_H
#define LUNASVG_SVGELEMENT_H
#include "../include/lunasvg.h"
#include "svgproperty.h"
#include <string>
#include <forward_list>
#include <list>
#include <map>
namespace {
namespace lunasvg {
class Document;
class SVGElement;
class SVGRootElement;
class SVGNode {
public:
SVGNode(Document* document)
: m_document(document)
{}
virtual ~SVGNode() = default;
virtual bool isTextNode() const { return false; }
virtual bool isElement() const { return false; }
virtual bool isPaintElement() const { return false; }
virtual bool isGraphicsElement() const { return false; }
virtual bool isGeometryElement() const { return false; }
virtual bool isTextPositioningElement() const { return false; }
Document* document() const { return m_document; }
SVGRootElement* rootElement() const { return m_document->rootElement(); }
SVGElement* parentElement() const { return m_parentElement; }
void setParentElement(SVGElement* parent) { m_parentElement = parent; }
bool isRootElement() const { return m_parentElement == nullptr; }
virtual std::unique_ptr<SVGNode> clone(bool deep) const = 0;
private:
SVGNode(const SVGNode&) = delete;
SVGNode& operator=(const SVGNode&) = delete;
Document* m_document;
SVGElement* m_parentElement = nullptr;
};
class SVGTextNode final : public SVGNode {
public:
SVGTextNode(Document* document);
bool isTextNode() const final { return true; }
const std::string& data() const { return m_data; }
void setData(const std::string& data);
std::unique_ptr<SVGNode> clone(bool deep) const final;
private:
std::string m_data;
};
class Attribute {
public:
Attribute() = default;
Attribute(int specificity, PropertyID id, std::string value)
: m_specificity(specificity), m_id(id), m_value(std::move(value))
{}
int specificity() const { return m_specificity; }
PropertyID id() const { return m_id; }
const std::string& value() const { return m_value; }
private:
int m_specificity;
PropertyID m_id;
std::string m_value;
};
using AttributeList = std::forward_list<Attribute>;
enum class ElementID : uint8_t {
Unknown = 0,
Star,
Circle,
ClipPath,
Defs,
Ellipse,
G,
Image,
Line,
LinearGradient,
Marker,
Mask,
Path,
Pattern,
Polygon,
Polyline,
RadialGradient,
Rect,
Stop,
Style,
Svg,
Symbol,
Text,
Tspan,
Use
};
ElementID elementid(const std::string_view& name);
using SVGNodeList = std::list<std::unique_ptr<SVGNode>>;
using SVGPropertyList = std::forward_list<SVGProperty*>;
class SVGMarkerElement;
class SVGClipPathElement;
class SVGMaskElement;
class SVGPaintElement;
class SVGLayoutState;
class SVGRenderState;
extern const std::string emptyString;
class SVGElement : public SVGNode {
public:
static std::unique_ptr<SVGElement> create(Document* document, ElementID id);
SVGElement(Document* document, ElementID id);
virtual ~SVGElement() = default;
bool hasAttribute(const std::string_view& name) const;
const std::string& getAttribute(const std::string_view& name) const;
bool setAttribute(const std::string_view& name, const std::string& value);
const Attribute* findAttribute(PropertyID id) const;
bool hasAttribute(PropertyID id) const;
const std::string& getAttribute(PropertyID id) const;
bool setAttribute(int specificity, PropertyID id, const std::string& value);
void setAttributes(const AttributeList& attributes);
bool setAttribute(const Attribute& attribute);
virtual void parseAttribute(PropertyID id, const std::string& value);
SVGElement* previousElement() const;
SVGElement* nextElement() const;
SVGNode* addChild(std::unique_ptr<SVGNode> child);
SVGNode* firstChild() const;
SVGNode* lastChild() const;
ElementID id() const { return m_id; }
const AttributeList& attributes() const { return m_attributes; }
const SVGPropertyList& properties() const { return m_properties; }
const SVGNodeList& children() const { return m_children; }
virtual Transform localTransform() const { return Transform::Identity; }
virtual Rect fillBoundingBox() const;
virtual Rect strokeBoundingBox() const;
virtual Rect paintBoundingBox() const;
SVGMarkerElement* getMarker(const std::string_view& id) const;
SVGClipPathElement* getClipper(const std::string_view& id) const;
SVGMaskElement* getMasker(const std::string_view& id) const;
SVGPaintElement* getPainter(const std::string_view& id) const;
SVGElement* elementFromPoint(float x, float y);
template<typename T>
void transverse(T callback);
void addProperty(SVGProperty& value);
SVGProperty* getProperty(PropertyID id) const;
Size currentViewportSize() const;
float font_size() const { return m_font_size; }
void cloneChildren(SVGElement* parentElement) const;
std::unique_ptr<SVGNode> clone(bool deep) const final;
virtual void build();
virtual void layoutElement(const SVGLayoutState& state);
void layoutChildren(SVGLayoutState& state);
virtual void layout(SVGLayoutState& state);
void renderChildren(SVGRenderState& state) const;
virtual void render(SVGRenderState& state) const;
bool isDisplayNone() const { return m_display == Display::None; }
bool isOverflowHidden() const { return m_overflow == Overflow::Hidden; }
bool isVisibilityHidden() const { return m_visibility != Visibility::Visible; }
bool isHiddenElement() const;
bool isPointableElement() const;
const SVGClipPathElement* clipper() const { return m_clipper; }
const SVGMaskElement* masker() const { return m_masker; }
float opacity() const { return m_opacity; }
bool isElement() const final { return true; }
private:
mutable Rect m_paintBoundingBox = Rect::Invalid;
const SVGClipPathElement* m_clipper = nullptr;
const SVGMaskElement* m_masker = nullptr;
float m_opacity = 1.f;
float m_font_size = 12.f;
Display m_display = Display::Inline;
Overflow m_overflow = Overflow::Visible;
Visibility m_visibility = Visibility::Visible;
PointerEvents m_pointer_events = PointerEvents::Auto;
ElementID m_id;
AttributeList m_attributes;
SVGPropertyList m_properties;
SVGNodeList m_children;
};
inline const SVGElement* toSVGElement(const SVGNode* node)
{
if(node && node->isElement())
return static_cast<const SVGElement*>(node);
return nullptr;
}
inline SVGElement* toSVGElement(SVGNode* node)
{
if(node && node->isElement())
return static_cast<SVGElement*>(node);
return nullptr;
}
inline SVGElement* toSVGElement(const std::unique_ptr<SVGNode>& node)
{
return toSVGElement(node.get());
}
template<typename T>
inline void SVGElement::transverse(T callback)
{
callback(this);
for(const auto& child : m_children) {
if(auto element = toSVGElement(child)) {
element->transverse(callback);
}
}
}
class SVGStyleElement final : public SVGElement {
public:
SVGStyleElement(Document* document);
};
class SVGFitToViewBox {
public:
SVGFitToViewBox(SVGElement* element);
const SVGRect& viewBox() const { return m_viewBox; }
const SVGPreserveAspectRatio& preserveAspectRatio() const { return m_preserveAspectRatio; }
Transform viewBoxToViewTransform(const Size& viewportSize) const;
Rect getClipRect(const Size& viewportSize) const;
private:
SVGRect m_viewBox;
SVGPreserveAspectRatio m_preserveAspectRatio;
};
class SVGURIReference {
public:
SVGURIReference(SVGElement* element);
const SVGString& href() const { return m_href; }
const std::string& hrefString() const { return m_href.value(); }
SVGElement* getTargetElement(const Document* document) const;
private:
SVGString m_href;
};
class SVGPaintServer {
public:
SVGPaintServer() = default;
SVGPaintServer(const SVGPaintElement* element, const Color& color, float opacity)
: m_element(element), m_color(color), m_opacity(opacity)
{}
bool isRenderable() const { return m_opacity > 0.f && (m_element || m_color.alpha() > 0); }
const SVGPaintElement* element() const { return m_element; }
const Color& color() const { return m_color; }
float opacity() const { return m_opacity; }
bool applyPaint(SVGRenderState& state) const;
private:
const SVGPaintElement* m_element = nullptr;
Color m_color = Color::Transparent;
float m_opacity = 0.f;
};
class SVGGraphicsElement : public SVGElement {
public:
SVGGraphicsElement(Document* document, ElementID id);
bool isGraphicsElement() const final { return true; }
const SVGTransform& transform() const { return m_transform; }
Transform localTransform() const override { return m_transform.value(); }
SVGPaintServer getPaintServer(const Paint& paint, float opacity) const;
StrokeData getStrokeData(const SVGLayoutState& state) const;
private:
SVGTransform m_transform;
};
class SVGSVGElement : public SVGGraphicsElement, public SVGFitToViewBox {
public:
SVGSVGElement(Document* document);
const SVGLength& x() const { return m_x; }
const SVGLength& y() const { return m_y; }
const SVGLength& width() const { return m_width; }
const SVGLength& height() const { return m_height; }
Transform localTransform() const override;
void render(SVGRenderState& state) const override;
private:
SVGLength m_x;
SVGLength m_y;
SVGLength m_width;
SVGLength m_height;
};
class SVGRootElement final : public SVGSVGElement {
public:
SVGRootElement(Document* document);
float intrinsicWidth() const { return m_intrinsicWidth; }
float intrinsicHeight() const { return m_intrinsicHeight; }
void setNeedsLayout() { m_intrinsicWidth = -1.f; }
bool needsLayout() const { return m_intrinsicWidth == -1.f; }
SVGRootElement* layoutIfNeeded();
SVGElement* getElementById(const std::string_view& id) const;
void addElementById(const std::string& id, SVGElement* element);
void layout(SVGLayoutState& state) final;
void forceLayout();
private:
std::map<std::string, SVGElement*, std::less<>> m_idCache;
float m_intrinsicWidth{-1.f};
float m_intrinsicHeight{-1.f};
};
class SVGUseElement final : public SVGGraphicsElement, public SVGURIReference {
public:
SVGUseElement(Document* document);
const SVGLength& x() const { return m_x; }
const SVGLength& y() const { return m_y; }
const SVGLength& width() const { return m_width; }
const SVGLength& height() const { return m_height; }
Transform localTransform() const final;
void render(SVGRenderState& state) const final;
void build() final;
private:
std::unique_ptr<SVGElement> cloneTargetElement(SVGElement* targetElement);
SVGLength m_x;
SVGLength m_y;
SVGLength m_width;
SVGLength m_height;
};
class SVGImageElement final : public SVGGraphicsElement {
public:
SVGImageElement(Document* document);
const SVGLength& x() const { return m_x; }
const SVGLength& y() const { return m_y; }
const SVGLength& width() const { return m_width; }
const SVGLength& height() const { return m_height; }
const SVGPreserveAspectRatio& preserveAspectRatio() const { return m_preserveAspectRatio; }
const Bitmap& image() const { return m_image; }
Rect fillBoundingBox() const final;
Rect strokeBoundingBox() const final;
void render(SVGRenderState& state) const final;
void parseAttribute(PropertyID id, const std::string& value) final;
private:
SVGLength m_x;
SVGLength m_y;
SVGLength m_width;
SVGLength m_height;
SVGPreserveAspectRatio m_preserveAspectRatio;
Bitmap m_image;
};
class SVGSymbolElement final : public SVGGraphicsElement, public SVGFitToViewBox {
public:
SVGSymbolElement(Document* document);
};
class SVGGElement final : public SVGGraphicsElement {
public:
SVGGElement(Document* document);
void render(SVGRenderState& state) const final;
};
class SVGDefsElement final : public SVGGraphicsElement {
public:
SVGDefsElement(Document* document);
};
class SVGMarkerElement final : public SVGElement, public SVGFitToViewBox {
public:
SVGMarkerElement(Document* document);
const SVGLength& refX() const { return m_refX; }
const SVGLength& refY() const { return m_refY; }
const SVGLength& markerWidth() const { return m_markerWidth; }
const SVGLength& markerHeight() const { return m_markerHeight; }
const SVGEnumeration<MarkerUnits>& markerUnits() const { return m_markerUnits; }
const SVGAngle& orient() const { return m_orient; }
Point refPoint() const;
Size markerSize() const;
Transform markerTransform(const Point& origin, float angle, float strokeWidth) const;
Rect markerBoundingBox(const Point& origin, float angle, float strokeWidth) const;
void renderMarker(SVGRenderState& state, const Point& origin, float angle, float strokeWidth) const;
Transform localTransform() const final;
private:
SVGLength m_refX;
SVGLength m_refY;
SVGLength m_markerWidth;
SVGLength m_markerHeight;
SVGEnumeration<MarkerUnits> m_markerUnits;
SVGAngle m_orient;
};
class SVGClipPathElement final : public SVGGraphicsElement {
public:
SVGClipPathElement(Document* document);
const SVGEnumeration<Units>& clipPathUnits() const { return m_clipPathUnits; }
Rect clipBoundingBox(const SVGElement* element) const;
void applyClipMask(SVGRenderState& state) const;
void applyClipPath(SVGRenderState& state) const;
bool requiresMasking() const;
private:
SVGEnumeration<Units> m_clipPathUnits;
};
class SVGMaskElement final : public SVGElement {
public:
SVGMaskElement(Document* document);
const SVGLength& x() const { return m_x; }
const SVGLength& y() const { return m_y; }
const SVGLength& width() const { return m_width; }
const SVGLength& height() const { return m_height; }
const SVGEnumeration<Units>& maskUnits() const { return m_maskUnits; }
const SVGEnumeration<Units>& maskContentUnits() const { return m_maskContentUnits; }
Rect maskRect(const SVGElement* element) const;
Rect maskBoundingBox(const SVGElement* element) const;
void applyMask(SVGRenderState& state) const;
void layoutElement(const SVGLayoutState& state) final;
private:
SVGLength m_x;
SVGLength m_y;
SVGLength m_width;
SVGLength m_height;
SVGEnumeration<Units> m_maskUnits;
SVGEnumeration<Units> m_maskContentUnits;
MaskType m_mask_type = MaskType::Luminance;
};
} // namespace lunasvg
}
#endif // LUNASVG_SVGELEMENT_H
@@ -0,0 +1,326 @@
#include "svggeometryelement.h"
#include "svglayoutstate.h"
#include "svgrenderstate.h"
#include <cmath>
namespace {
namespace lunasvg {
Rect SVGMarkerPosition::markerBoundingBox(float strokeWidth) const
{
return m_element->markerBoundingBox(m_origin, m_angle, strokeWidth);
}
void SVGMarkerPosition::renderMarker(SVGRenderState& state, float strokeWidth) const
{
m_element->renderMarker(state, m_origin, m_angle, strokeWidth);
}
SVGGeometryElement::SVGGeometryElement(Document* document, ElementID id)
: SVGGraphicsElement(document, id)
{
}
Rect SVGGeometryElement::strokeBoundingBox() const
{
auto strokeBoundingBox = fillBoundingBox();
if(m_stroke.isRenderable()) {
float capLimit = m_strokeData.lineWidth() / 2.f;
if(m_strokeData.lineCap() == LineCap::Square)
capLimit *= JUCE_PLUTOVG_SQRT2;
float joinLimit = m_strokeData.lineWidth() / 2.f;
if(m_strokeData.lineJoin() == LineJoin::Miter) {
joinLimit *= m_strokeData.miterLimit();
}
strokeBoundingBox.inflate(std::max(capLimit, joinLimit));
}
for(const auto& markerPosition : m_markerPositions)
strokeBoundingBox.unite(markerPosition.markerBoundingBox(m_strokeData.lineWidth()));
return strokeBoundingBox;
}
void SVGGeometryElement::layoutElement(const SVGLayoutState& state)
{
m_fill_rule = state.fill_rule();
m_clip_rule = state.clip_rule();
m_fill = getPaintServer(state.fill(), state.fill_opacity());
m_stroke = getPaintServer(state.stroke(), state.stroke_opacity());
m_strokeData = getStrokeData(state);
SVGGraphicsElement::layoutElement(state);
m_path.reset();
m_markerPositions.clear();
m_fillBoundingBox = updateShape(m_path);
updateMarkerPositions(m_markerPositions, state);
}
void SVGGeometryElement::updateMarkerPositions(SVGMarkerPositionList& positions, const SVGLayoutState& state)
{
if(m_path.isEmpty())
return;
auto markerStart = getMarker(state.marker_start());
auto markerMid = getMarker(state.marker_mid());
auto markerEnd = getMarker(state.marker_end());
if(markerStart == nullptr && markerMid == nullptr && markerEnd == nullptr) {
return;
}
Point origin;
Point startPoint;
Point inslopePoints[2];
Point outslopePoints[2];
int index = 0;
std::array<Point, 3> points;
PathIterator it(m_path);
while(!it.isDone()) {
switch(it.currentSegment(points)) {
case PathCommand::MoveTo:
startPoint = points[0];
inslopePoints[0] = origin;
inslopePoints[1] = points[0];
origin = points[0];
break;
case PathCommand::LineTo:
inslopePoints[0] = origin;
inslopePoints[1] = points[0];
origin = points[0];
break;
case PathCommand::CubicTo:
inslopePoints[0] = points[1];
inslopePoints[1] = points[2];
origin = points[2];
break;
case PathCommand::Close:
inslopePoints[0] = origin;
inslopePoints[1] = points[0];
origin = startPoint;
startPoint = Point();
break;
}
it.next();
if(!it.isDone() && (markerStart || markerMid)) {
it.currentSegment(points);
outslopePoints[0] = origin;
outslopePoints[1] = points[0];
if(index == 0 && markerStart) {
auto slope = outslopePoints[1] - outslopePoints[0];
auto angle = 180.f * std::atan2(slope.y, slope.x) / JUCE_PLUTOVG_PI;
const auto& orient = markerStart->orient();
if(orient.orientType() == SVGAngle::OrientType::AutoStartReverse)
angle -= 180.f;
positions.emplace_back(markerStart, origin, angle);
}
if(index > 0 && markerMid) {
auto inslope = inslopePoints[1] - inslopePoints[0];
auto outslope = outslopePoints[1] - outslopePoints[0];
auto inangle = 180.f * std::atan2(inslope.y, inslope.x) / JUCE_PLUTOVG_PI;
auto outangle = 180.f * std::atan2(outslope.y, outslope.x) / JUCE_PLUTOVG_PI;
if(std::abs(inangle - outangle) > 180.f)
inangle += 360.f;
auto angle = (inangle + outangle) * 0.5f;
positions.emplace_back(markerMid, origin, angle);
}
}
if(markerEnd && it.isDone()) {
auto slope = inslopePoints[1] - inslopePoints[0];
auto angle = 180.f * std::atan2(slope.y, slope.x) / JUCE_PLUTOVG_PI;
positions.emplace_back(markerEnd, origin, angle);
}
index += 1;
}
}
void SVGGeometryElement::render(SVGRenderState& state) const
{
if(!isRenderable())
return;
SVGBlendInfo blendInfo(this);
SVGRenderState newState(this, state, localTransform());
newState.beginGroup(blendInfo);
if(newState.mode() == SVGRenderMode::Clipping) {
newState->setColor(Color::White);
newState->fillPath(m_path, m_clip_rule, newState.currentTransform());
} else {
if(m_fill.applyPaint(newState))
newState->fillPath(m_path, m_fill_rule, newState.currentTransform());
if(m_stroke.applyPaint(newState)) {
newState->strokePath(m_path, m_strokeData, newState.currentTransform());
}
for(const auto& markerPosition : m_markerPositions) {
markerPosition.renderMarker(newState, m_strokeData.lineWidth());
}
}
newState.endGroup(blendInfo);
}
SVGLineElement::SVGLineElement(Document* document)
: SVGGeometryElement(document, ElementID::Line)
, m_x1(PropertyID::X1, LengthDirection::Horizontal, LengthNegativeMode::Allow)
, m_y1(PropertyID::Y1, LengthDirection::Vertical, LengthNegativeMode::Allow)
, m_x2(PropertyID::X2, LengthDirection::Horizontal, LengthNegativeMode::Allow)
, m_y2(PropertyID::Y2, LengthDirection::Vertical, LengthNegativeMode::Allow)
{
addProperty(m_x1);
addProperty(m_y1);
addProperty(m_x2);
addProperty(m_y2);
}
Rect SVGLineElement::updateShape(Path& path)
{
LengthContext lengthContext(this);
auto x1 = lengthContext.valueForLength(m_x1);
auto y1 = lengthContext.valueForLength(m_y1);
auto x2 = lengthContext.valueForLength(m_x2);
auto y2 = lengthContext.valueForLength(m_y2);
path.moveTo(x1, y1);
path.lineTo(x2, y2);
return Rect(x1, y1, x2 - x1, y2 - y1);
}
SVGRectElement::SVGRectElement(Document* document)
: SVGGeometryElement(document, ElementID::Rect)
, m_x(PropertyID::X, LengthDirection::Horizontal, LengthNegativeMode::Allow)
, m_y(PropertyID::Y, LengthDirection::Vertical, LengthNegativeMode::Allow)
, m_width(PropertyID::Width, LengthDirection::Horizontal, LengthNegativeMode::Forbid)
, m_height(PropertyID::Height, LengthDirection::Vertical, LengthNegativeMode::Forbid)
, m_rx(PropertyID::Rx, LengthDirection::Horizontal, LengthNegativeMode::Forbid)
, m_ry(PropertyID::Ry, LengthDirection::Vertical, LengthNegativeMode::Forbid)
{
addProperty(m_x);
addProperty(m_y);
addProperty(m_width);
addProperty(m_height);
addProperty(m_rx);
addProperty(m_ry);
}
Rect SVGRectElement::updateShape(Path& path)
{
LengthContext lengthContext(this);
auto width = lengthContext.valueForLength(m_width);
auto height = lengthContext.valueForLength(m_height);
if(width <= 0.f || height <= 0.f) {
return Rect::Empty;
}
auto x = lengthContext.valueForLength(m_x);
auto y = lengthContext.valueForLength(m_y);
auto rx = lengthContext.valueForLength(m_rx);
auto ry = lengthContext.valueForLength(m_ry);
if(rx <= 0.f) rx = ry;
if(ry <= 0.f) ry = rx;
rx = std::min(rx, width / 2.f);
ry = std::min(ry, height / 2.f);
path.addRoundRect(x, y, width, height, rx, ry);
return Rect(x, y, width, height);
}
SVGEllipseElement::SVGEllipseElement(Document* document)
: SVGGeometryElement(document, ElementID::Ellipse)
, m_cx(PropertyID::Cx, LengthDirection::Horizontal, LengthNegativeMode::Allow)
, m_cy(PropertyID::Cy, LengthDirection::Vertical, LengthNegativeMode::Allow)
, m_rx(PropertyID::Rx, LengthDirection::Diagonal, LengthNegativeMode::Forbid)
, m_ry(PropertyID::Ry, LengthDirection::Diagonal, LengthNegativeMode::Forbid)
{
addProperty(m_cx);
addProperty(m_cy);
addProperty(m_rx);
addProperty(m_ry);
}
Rect SVGEllipseElement::updateShape(Path& path)
{
LengthContext lengthContext(this);
auto rx = lengthContext.valueForLength(m_rx);
auto ry = lengthContext.valueForLength(m_ry);
if(rx <= 0.f || ry <= 0.f) {
return Rect::Empty;
}
auto cx = lengthContext.valueForLength(m_cx);
auto cy = lengthContext.valueForLength(m_cy);
path.addEllipse(cx, cy, rx, ry);
return Rect(cx - rx, cy - ry, rx + rx, ry + ry);
}
SVGCircleElement::SVGCircleElement(Document* document)
: SVGGeometryElement(document, ElementID::Circle)
, m_cx(PropertyID::Cx, LengthDirection::Horizontal, LengthNegativeMode::Allow)
, m_cy(PropertyID::Cy, LengthDirection::Vertical, LengthNegativeMode::Allow)
, m_r(PropertyID::R, LengthDirection::Diagonal, LengthNegativeMode::Forbid)
{
addProperty(m_cx);
addProperty(m_cy);
addProperty(m_r);
}
Rect SVGCircleElement::updateShape(Path& path)
{
LengthContext lengthContext(this);
auto r = lengthContext.valueForLength(m_r);
if(r <= 0.f) {
return Rect::Empty;
}
auto cx = lengthContext.valueForLength(m_cx);
auto cy = lengthContext.valueForLength(m_cy);
path.addEllipse(cx, cy, r, r);
return Rect(cx - r, cy - r, r + r, r + r);
}
SVGPolyElement::SVGPolyElement(Document* document, ElementID id)
: SVGGeometryElement(document, id)
, m_points(PropertyID::Points)
{
addProperty(m_points);
}
Rect SVGPolyElement::updateShape(Path& path)
{
const auto& points = m_points.values();
if(points.empty()) {
return Rect::Empty;
}
path.moveTo(points[0].x, points[0].y);
for(size_t i = 1; i < points.size(); i++) {
path.lineTo(points[i].x, points[i].y);
}
if(id() == ElementID::Polygon)
path.close();
return path.boundingRect();
}
SVGPathElement::SVGPathElement(Document* document)
: SVGGeometryElement(document, ElementID::Path)
, m_d(PropertyID::D)
{
addProperty(m_d);
}
Rect SVGPathElement::updateShape(Path& path)
{
path = m_d.value();
return path.boundingRect();
}
} // namespace lunasvg
}
@@ -0,0 +1,141 @@
#ifndef LUNASVG_SVGGEOMETRYELEMENT_H
#define LUNASVG_SVGGEOMETRYELEMENT_H
#include "svgelement.h"
namespace {
namespace lunasvg {
class SVGMarkerPosition {
public:
SVGMarkerPosition(const SVGMarkerElement* element, const Point& origin, float angle)
: m_element(element), m_origin(origin), m_angle(angle)
{}
const SVGMarkerElement* element() const { return m_element; }
const Point& origin() const { return m_origin; }
float angle() const { return m_angle; }
Rect markerBoundingBox(float strokeWidth) const;
void renderMarker(SVGRenderState& state, float strokeWidth) const;
private:
const SVGMarkerElement* m_element;
Point m_origin;
float m_angle;
};
using SVGMarkerPositionList = std::vector<SVGMarkerPosition>;
class SVGGeometryElement : public SVGGraphicsElement {
public:
SVGGeometryElement(Document* document, ElementID id);
bool isGeometryElement() const final { return true; }
Rect fillBoundingBox() const override { return m_fillBoundingBox; }
Rect strokeBoundingBox() const override;
void layoutElement(const SVGLayoutState& state) override;
bool isRenderable() const { return !m_path.isNull() && !isDisplayNone() && !isVisibilityHidden(); }
FillRule fill_rule() const { return m_fill_rule; }
FillRule clip_rule() const { return m_clip_rule; }
virtual Rect updateShape(Path& path) = 0;
void updateMarkerPositions(SVGMarkerPositionList& positions, const SVGLayoutState& state);
void render(SVGRenderState& state) const override;
const Path& path() const { return m_path; }
private:
Path m_path;
Rect m_fillBoundingBox;
StrokeData m_strokeData;
SVGPaintServer m_fill;
SVGPaintServer m_stroke;
SVGMarkerPositionList m_markerPositions;
FillRule m_fill_rule = FillRule::NonZero;
FillRule m_clip_rule = FillRule::NonZero;
};
class SVGLineElement final : public SVGGeometryElement {
public:
SVGLineElement(Document* document);
Rect updateShape(Path& path) final;
private:
SVGLength m_x1;
SVGLength m_y1;
SVGLength m_x2;
SVGLength m_y2;
};
class SVGRectElement final : public SVGGeometryElement {
public:
SVGRectElement(Document* document);
Rect updateShape(Path& path) final;
private:
SVGLength m_x;
SVGLength m_y;
SVGLength m_width;
SVGLength m_height;
SVGLength m_rx;
SVGLength m_ry;
};
class SVGEllipseElement final : public SVGGeometryElement {
public:
SVGEllipseElement(Document* document);
Rect updateShape(Path& path) final;
private:
SVGLength m_cx;
SVGLength m_cy;
SVGLength m_rx;
SVGLength m_ry;
};
class SVGCircleElement final : public SVGGeometryElement {
public:
SVGCircleElement(Document* document);
Rect updateShape(Path& path) final;
private:
SVGLength m_cx;
SVGLength m_cy;
SVGLength m_r;
};
class SVGPolyElement final : public SVGGeometryElement {
public:
SVGPolyElement(Document* document, ElementID id);
Rect updateShape(Path& path) final;
private:
SVGPointList m_points;
};
class SVGPathElement final : public SVGGeometryElement {
public:
SVGPathElement(Document* document);
Rect updateShape(Path& path) final;
private:
SVGPath m_d;
};
} // namespace lunasvg
}
#endif // LUNASVG_SVGGEOMETRYELEMENT_H
@@ -0,0 +1,609 @@
#include "svglayoutstate.h"
#include "svgelement.h"
#include "svgparserutils.h"
#include <optional>
namespace {
namespace lunasvg {
static std::optional<Color> parseColorValue(std::string_view& input, const SVGLayoutState* state)
{
if(skipString(input, "currentColor")) {
return state->color();
}
juce_plutovg_color_t color;
int length = juce_plutovg_color_parse(&color, input.data(), input.length());
if(length == 0)
return std::nullopt;
input.remove_prefix(length);
return Color(juce_plutovg_color_to_argb32(&color));
}
static Color parseColor(std::string_view input, const SVGLayoutState* state, const Color& defaultValue)
{
auto color = parseColorValue(input, state);
if(!color || !input.empty())
color = defaultValue;
return *color;
}
static Color parseColorOrNone(std::string_view input, const SVGLayoutState* state, const Color& defaultValue)
{
if(input.compare("none") == 0)
return Color::Transparent;
return parseColor(input, state, defaultValue);
}
static bool parseUrlValue(std::string_view& input, std::string& value)
{
if(!skipString(input, "url")
|| !skipOptionalSpaces(input)
|| !skipDelimiter(input, '(')
|| !skipOptionalSpaces(input)) {
return false;
}
switch(input.front()) {
case '\'':
case '\"': {
auto delim = input.front();
input.remove_prefix(1);
skipOptionalSpaces(input);
if(!skipDelimiter(input, '#'))
return false;
while(!input.empty() && input.front() != delim) {
value += input.front();
input.remove_prefix(1);
}
skipOptionalSpaces(input);
if(!skipDelimiter(input, delim))
return false;
break;
} case '#': {
input.remove_prefix(1);
while(!input.empty() && input.front() != ')') {
value += input.front();
input.remove_prefix(1);
}
break;
} default:
return false;
}
return skipOptionalSpaces(input) && skipDelimiter(input, ')');
}
static std::string parseUrl(std::string_view input)
{
std::string value;
if(!parseUrlValue(input, value) || !input.empty())
value.clear();
return value;
}
static Paint parsePaint(std::string_view input, const SVGLayoutState* state, const Color& defaultValue)
{
std::string id;
if(!parseUrlValue(input, id))
return Paint(parseColorOrNone(input, state, defaultValue));
if(skipOptionalSpaces(input))
return Paint(id, parseColorOrNone(input, state, defaultValue));
return Paint(id, Color::Transparent);
}
static float parseNumberOrPercentage(std::string_view input, bool allowPercentage, float defaultValue)
{
float value;
if(!parseNumber(input, value))
return defaultValue;
if(allowPercentage) {
if(skipDelimiter(input, '%'))
value /= 100.f;
value = std::clamp(value, 0.f, 1.f);
}
if(!input.empty())
return defaultValue;
return value;
}
static Length parseLength(const std::string_view& input, LengthNegativeMode mode, const Length& defaultValue)
{
Length value;
if(!value.parse(input, mode))
value = defaultValue;
return value;
}
static BaselineShift parseBaselineShift(const std::string_view& input)
{
if(input.compare("baseline") == 0)
return BaselineShift::Type::Baseline;
if(input.compare("sub") == 0)
return BaselineShift::Type::Sub;
if(input.compare("super") == 0)
return BaselineShift::Type::Super;
return parseLength(input, LengthNegativeMode::Allow, Length(0.f, LengthUnits::None));
}
static LengthList parseDashArray(std::string_view input)
{
if(input.compare("none") == 0)
return LengthList();
LengthList values;
do {
size_t count = 0;
while(count < input.length() && input[count] != ',' && !IS_WS(input[count]))
++count;
Length value(0, LengthUnits::None);
if(!value.parse(input.substr(0, count), LengthNegativeMode::Forbid))
return LengthList();
input.remove_prefix(count);
values.push_back(std::move(value));
} while(skipOptionalSpacesOrComma(input));
return values;
}
static Length parseLengthOrNormal(std::string_view input)
{
if(input.compare("normal") == 0)
return Length(0, LengthUnits::None);
return parseLength(input, LengthNegativeMode::Allow, Length(0, LengthUnits::None));
}
static float parseFontSize(std::string_view input, const SVGLayoutState* state)
{
auto length = parseLength(input, LengthNegativeMode::Forbid, Length(12, LengthUnits::None));
if(length.units() == LengthUnits::Percent)
return length.value() * state->font_size() / 100.f;
if(length.units() == LengthUnits::Ex)
return length.value() * state->font_size() / 2.f;
if(length.units() == LengthUnits::Em)
return length.value() * state->font_size();
return length.value();
}
template<typename Enum, unsigned int N>
static Enum parseEnumValue(const std::string_view& input, const SVGEnumerationEntry<Enum>(&entries)[N], Enum defaultValue)
{
for(const auto& entry : entries) {
if(input == entry.second) {
return entry.first;
}
}
return defaultValue;
}
static Display parseDisplay(const std::string_view& input)
{
static const SVGEnumerationEntry<Display> entries[] = {
{Display::Inline, "inline"},
{Display::None, "none"}
};
return parseEnumValue(input, entries, Display::Inline);
}
static Visibility parseVisibility(const std::string_view& input)
{
static const SVGEnumerationEntry<Visibility> entries[] = {
{Visibility::Visible, "visible"},
{Visibility::Hidden, "hidden"},
{Visibility::Collapse, "collapse"}
};
return parseEnumValue(input, entries, Visibility::Visible);
}
static Overflow parseOverflow(const std::string_view& input)
{
static const SVGEnumerationEntry<Overflow> entries[] = {
{Overflow::Visible, "visible"},
{Overflow::Hidden, "hidden"}
};
return parseEnumValue(input, entries, Overflow::Visible);
}
static PointerEvents parsePointerEvents(const std::string_view& input)
{
static const SVGEnumerationEntry<PointerEvents> entries[] = {
{PointerEvents::None,"none"},
{PointerEvents::Auto,"auto"},
{PointerEvents::Stroke,"stroke"},
{PointerEvents::Fill,"fill"},
{PointerEvents::Painted,"painted"},
{PointerEvents::Visible,"visible"},
{PointerEvents::VisibleStroke,"visibleStroke"},
{PointerEvents::VisibleFill,"visibleFill"},
{PointerEvents::VisiblePainted,"visiblePainted"},
{PointerEvents::BoundingBox,"bounding-box"},
{PointerEvents::All,"all"},
};
return parseEnumValue(input, entries, PointerEvents::Auto);
}
static FontWeight parseFontWeight(const std::string_view& input)
{
static const SVGEnumerationEntry<FontWeight> entries[] = {
{FontWeight::Normal, "normal"},
{FontWeight::Bold, "bold"},
{FontWeight::Bold, "bolder"},
{FontWeight::Normal, "lighter"},
{FontWeight::Normal, "100"},
{FontWeight::Normal, "200"},
{FontWeight::Normal, "300"},
{FontWeight::Normal, "400"},
{FontWeight::Normal, "500"},
{FontWeight::Bold, "600"},
{FontWeight::Bold, "700"},
{FontWeight::Bold, "800"},
{FontWeight::Bold, "900"}
};
return parseEnumValue(input, entries, FontWeight::Normal);
}
static FontStyle parseFontStyle(const std::string_view& input)
{
static const SVGEnumerationEntry<FontStyle> entries[] = {
{FontStyle::Normal, "normal"},
{FontStyle::Italic, "italic"},
{FontStyle::Italic, "oblique"}
};
return parseEnumValue(input, entries, FontStyle::Normal);
}
static AlignmentBaseline parseAlignmentBaseline(const std::string_view& input)
{
static const SVGEnumerationEntry<AlignmentBaseline> entries[] = {
{AlignmentBaseline::Auto, "auto"},
{AlignmentBaseline::Baseline, "baseline"},
{AlignmentBaseline::BeforeEdge, "before-edge"},
{AlignmentBaseline::TextBeforeEdge, "text-before-edge"},
{AlignmentBaseline::Middle, "middle"},
{AlignmentBaseline::Central, "central"},
{AlignmentBaseline::AfterEdge, "after-edge"},
{AlignmentBaseline::TextAfterEdge, "text-after-edge"},
{AlignmentBaseline::Ideographic, "ideographic"},
{AlignmentBaseline::Alphabetic, "alphabetic"},
{AlignmentBaseline::Hanging, "hanging"},
{AlignmentBaseline::Mathematical, "mathematical"}
};
return parseEnumValue(input, entries, AlignmentBaseline::Auto);
}
static DominantBaseline parseDominantBaseline(const std::string_view& input)
{
static const SVGEnumerationEntry<DominantBaseline> entries[] = {
{DominantBaseline::Auto, "auto"},
{DominantBaseline::UseScript, "use-script"},
{DominantBaseline::NoChange, "no-change"},
{DominantBaseline::ResetSize, "reset-size"},
{DominantBaseline::Ideographic, "ideographic"},
{DominantBaseline::Alphabetic, "alphabetic"},
{DominantBaseline::Hanging, "hanging"},
{DominantBaseline::Mathematical, "mathematical"},
{DominantBaseline::Central, "central"},
{DominantBaseline::Middle, "middle"},
{DominantBaseline::TextAfterEdge, "text-after-edge"},
{DominantBaseline::TextBeforeEdge, "text-before-edge"}
};
return parseEnumValue(input, entries, DominantBaseline::Auto);
}
static Direction parseDirection(const std::string_view& input)
{
static const SVGEnumerationEntry<Direction> entries[] = {
{Direction::Ltr, "ltr"},
{Direction::Rtl, "rtl"}
};
return parseEnumValue(input, entries, Direction::Ltr);
}
static WritingMode parseWritingMode(const std::string_view& input)
{
static const SVGEnumerationEntry<WritingMode> entries[] = {
{WritingMode::Horizontal, "horizontal-tb"},
{WritingMode::Vertical, "vertical-rl"},
{WritingMode::Vertical, "vertical-lr"},
{WritingMode::Horizontal, "lr-tb"},
{WritingMode::Horizontal, "lr"},
{WritingMode::Horizontal, "rl-tb"},
{WritingMode::Horizontal, "rl"},
{WritingMode::Vertical, "tb-rl"},
{WritingMode::Vertical, "tb"}
};
return parseEnumValue(input, entries, WritingMode::Horizontal);
}
static TextOrientation parseTextOrientation(const std::string_view& input)
{
static const SVGEnumerationEntry<TextOrientation> entries[] = {
{TextOrientation::Mixed, "mixed"},
{TextOrientation::Upright, "upright"}
};
return parseEnumValue(input, entries, TextOrientation::Mixed);
}
static TextAnchor parseTextAnchor(const std::string_view& input)
{
static const SVGEnumerationEntry<TextAnchor> entries[] = {
{TextAnchor::Start, "start"},
{TextAnchor::Middle, "middle"},
{TextAnchor::End, "end"}
};
return parseEnumValue(input, entries, TextAnchor::Start);
}
static WhiteSpace parseWhiteSpace(const std::string_view& input)
{
static const SVGEnumerationEntry<WhiteSpace> entries[] = {
{WhiteSpace::Default, "default"},
{WhiteSpace::Preserve, "preserve"},
{WhiteSpace::Default, "normal"},
{WhiteSpace::Default, "nowrap"},
{WhiteSpace::Default, "pre-line"},
{WhiteSpace::Preserve, "pre-wrap"},
{WhiteSpace::Preserve, "pre"}
};
return parseEnumValue(input, entries, WhiteSpace::Default);
}
static MaskType parseMaskType(const std::string_view& input)
{
static const SVGEnumerationEntry<MaskType> entries[] = {
{MaskType::Luminance, "luminance"},
{MaskType::Alpha, "alpha"}
};
return parseEnumValue(input, entries, MaskType::Luminance);
}
static FillRule parseFillRule(const std::string_view& input)
{
static const SVGEnumerationEntry<FillRule> entries[] = {
{FillRule::NonZero, "nonzero"},
{FillRule::EvenOdd, "evenodd"}
};
return parseEnumValue(input, entries, FillRule::NonZero);
}
static LineCap parseLineCap(const std::string_view& input)
{
static const SVGEnumerationEntry<LineCap> entries[] = {
{LineCap::Butt, "butt"},
{LineCap::Round, "round"},
{LineCap::Square, "square"}
};
return parseEnumValue(input, entries, LineCap::Butt);
}
static LineJoin parseLineJoin(const std::string_view& input)
{
static const SVGEnumerationEntry<LineJoin> entries[] = {
{LineJoin::Miter, "miter"},
{LineJoin::Round, "round"},
{LineJoin::Bevel, "bevel"}
};
return parseEnumValue(input, entries, LineJoin::Miter);
}
SVGLayoutState::SVGLayoutState(const SVGLayoutState& parent, const SVGElement* element)
: m_parent(&parent)
, m_element(element)
, m_fill(parent.fill())
, m_stroke(parent.stroke())
, m_color(parent.color())
, m_fill_opacity(parent.fill_opacity())
, m_stroke_opacity(parent.stroke_opacity())
, m_stroke_miterlimit(parent.stroke_miterlimit())
, m_font_size(parent.font_size())
, m_letter_spacing(parent.letter_spacing())
, m_word_spacing(parent.word_spacing())
, m_stroke_width(parent.stroke_width())
, m_stroke_dashoffset(parent.stroke_dashoffset())
, m_stroke_dasharray(parent.stroke_dasharray())
, m_stroke_linecap(parent.stroke_linecap())
, m_stroke_linejoin(parent.stroke_linejoin())
, m_fill_rule(parent.fill_rule())
, m_clip_rule(parent.clip_rule())
, m_font_weight(parent.font_weight())
, m_font_style(parent.font_style())
, m_dominant_baseline(parent.dominant_baseline())
, m_text_anchor(parent.text_anchor())
, m_white_space(parent.white_space())
, m_writing_mode(parent.writing_mode())
, m_text_orientation(parent.text_orientation())
, m_direction(parent.direction())
, m_visibility(parent.visibility())
, m_overflow(element->isRootElement() ? Overflow::Visible : Overflow::Hidden)
, m_pointer_events(parent.pointer_events())
, m_marker_start(parent.marker_start())
, m_marker_mid(parent.marker_mid())
, m_marker_end(parent.marker_end())
, m_font_family(parent.font_family())
{
for(const auto& attribute : element->attributes()) {
std::string_view input(attribute.value());
stripLeadingAndTrailingSpaces(input);
if(input.empty() || input.compare("inherit") == 0)
continue;
switch(attribute.id()) {
case PropertyID::Fill:
m_fill = parsePaint(input, this, Color::Black);
break;
case PropertyID::Stroke:
m_stroke = parsePaint(input, this, Color::Transparent);
break;
case PropertyID::Color:
m_color = parseColor(input, this, Color::Black);
break;
case PropertyID::Stop_Color:
m_stop_color = parseColor(input, this, Color::Black);
break;
case PropertyID::Opacity:
m_opacity = parseNumberOrPercentage(input, true, 1.f);
break;
case PropertyID::Fill_Opacity:
m_fill_opacity = parseNumberOrPercentage(input, true, 1.f);
break;
case PropertyID::Stroke_Opacity:
m_stroke_opacity = parseNumberOrPercentage(input, true, 1.f);
break;
case PropertyID::Stop_Opacity:
m_stop_opacity = parseNumberOrPercentage(input, true, 1.f);
break;
case PropertyID::Stroke_Miterlimit:
m_stroke_miterlimit = parseNumberOrPercentage(input, false, 4.f);
break;
case PropertyID::Font_Size:
m_font_size = parseFontSize(input, this);
break;
case PropertyID::Letter_Spacing:
m_letter_spacing = parseLengthOrNormal(input);
break;
case PropertyID::Word_Spacing:
m_word_spacing = parseLengthOrNormal(input);
break;
case PropertyID::Baseline_Shift:
m_baseline_shit = parseBaselineShift(input);
break;
case PropertyID::Stroke_Width:
m_stroke_width = parseLength(input, LengthNegativeMode::Forbid, Length(1.f, LengthUnits::None));
break;
case PropertyID::Stroke_Dashoffset:
m_stroke_dashoffset = parseLength(input, LengthNegativeMode::Allow, Length(0.f, LengthUnits::None));
break;
case PropertyID::Stroke_Dasharray:
m_stroke_dasharray = parseDashArray(input);
break;
case PropertyID::Stroke_Linecap:
m_stroke_linecap = parseLineCap(input);
break;
case PropertyID::Stroke_Linejoin:
m_stroke_linejoin = parseLineJoin(input);
break;
case PropertyID::Fill_Rule:
m_fill_rule = parseFillRule(input);
break;
case PropertyID::Clip_Rule:
m_clip_rule = parseFillRule(input);
break;
case PropertyID::Font_Weight:
m_font_weight = parseFontWeight(input);
break;
case PropertyID::Font_Style:
m_font_style = parseFontStyle(input);
break;
case PropertyID::Alignment_Baseline:
m_alignment_baseline = parseAlignmentBaseline(input);
break;
case PropertyID::Dominant_Baseline:
m_dominant_baseline = parseDominantBaseline(input);
break;
case PropertyID::Direction:
m_direction = parseDirection(input);
break;
case PropertyID::Text_Anchor:
m_text_anchor = parseTextAnchor(input);
break;
case PropertyID::White_Space:
m_white_space = parseWhiteSpace(input);
break;
case PropertyID::Writing_Mode:
m_writing_mode = parseWritingMode(input);
break;
case PropertyID::Text_Orientation:
m_text_orientation = parseTextOrientation(input);
break;
case PropertyID::Display:
m_display = parseDisplay(input);
break;
case PropertyID::Visibility:
m_visibility = parseVisibility(input);
break;
case PropertyID::Overflow:
m_overflow = parseOverflow(input);
break;
case PropertyID::Pointer_Events:
m_pointer_events = parsePointerEvents(input);
break;
case PropertyID::Mask_Type:
m_mask_type = parseMaskType(input);
break;
case PropertyID::Mask:
m_mask = parseUrl(input);
break;
case PropertyID::Clip_Path:
m_clip_path = parseUrl(input);
break;
case PropertyID::Marker_Start:
m_marker_start = parseUrl(input);
break;
case PropertyID::Marker_Mid:
m_marker_mid = parseUrl(input);
break;
case PropertyID::Marker_End:
m_marker_end = parseUrl(input);
break;
case PropertyID::Font_Family:
m_font_family.assign(input);
break;
default:
break;
}
}
}
Font SVGLayoutState::font() const
{
auto bold = m_font_weight == FontWeight::Bold;
auto italic = m_font_style == FontStyle::Italic;
FontFace face;
std::string_view input(m_font_family);
while(!input.empty() && face.isNull()) {
auto family = input.substr(0, input.find(','));
input.remove_prefix(family.length());
if(!input.empty() && input.front() == ',')
input.remove_prefix(1);
stripLeadingAndTrailingSpaces(family);
if(!family.empty() && (family.front() == '\'' || family.front() == '"')) {
auto quote = family.front();
family.remove_prefix(1);
if(!family.empty() && family.back() == quote)
family.remove_suffix(1);
stripLeadingAndTrailingSpaces(family);
}
std::string font_family(family);
if(!font_family.empty()) {
face = fontFaceCache()->getFontFace(font_family, bold, italic);
}
}
if(face.isNull())
face = fontFaceCache()->getFontFace(emptyString, bold, italic);
return Font(m_font_size, face.isNull() ? "" : font_family(), bold, italic);
}
} // namespace lunasvg
}
@@ -0,0 +1,131 @@
#ifndef LUNASVG_SVGLAYOUTSTATE_H
#define LUNASVG_SVGLAYOUTSTATE_H
#include "svgproperty.h"
namespace {
namespace lunasvg {
class SVGLayoutState {
public:
SVGLayoutState() = default;
SVGLayoutState(const SVGLayoutState& parent, const SVGElement* element);
const SVGLayoutState* parent() const { return m_parent; }
const SVGElement* element() const { return m_element; }
const Paint& fill() const { return m_fill; }
const Paint& stroke() const { return m_stroke; }
const Color& color() const { return m_color; }
const Color& stop_color() const { return m_stop_color; }
float opacity() const { return m_opacity; }
float stop_opacity() const { return m_stop_opacity; }
float fill_opacity() const { return m_fill_opacity; }
float stroke_opacity() const { return m_stroke_opacity; }
float stroke_miterlimit() const { return m_stroke_miterlimit; }
float font_size() const { return m_font_size; }
const Length& letter_spacing() const { return m_letter_spacing; }
const Length& word_spacing() const { return m_word_spacing; }
const BaselineShift& baseline_shit() const { return m_baseline_shit; }
const Length& stroke_width() const { return m_stroke_width; }
const Length& stroke_dashoffset() const { return m_stroke_dashoffset; }
const LengthList& stroke_dasharray() const { return m_stroke_dasharray; }
LineCap stroke_linecap() const { return m_stroke_linecap; }
LineJoin stroke_linejoin() const { return m_stroke_linejoin; }
FillRule fill_rule() const { return m_fill_rule; }
FillRule clip_rule() const { return m_clip_rule; }
FontWeight font_weight() const { return m_font_weight; }
FontStyle font_style() const { return m_font_style; }
AlignmentBaseline alignment_baseline() const { return m_alignment_baseline; }
DominantBaseline dominant_baseline() const { return m_dominant_baseline; }
TextAnchor text_anchor() const { return m_text_anchor; }
WhiteSpace white_space() const { return m_white_space; }
WritingMode writing_mode() const { return m_writing_mode; }
TextOrientation text_orientation() const { return m_text_orientation; }
Direction direction() const { return m_direction; }
Display display() const { return m_display; }
Visibility visibility() const { return m_visibility; }
Overflow overflow() const { return m_overflow; }
PointerEvents pointer_events() const { return m_pointer_events; }
MaskType mask_type() const { return m_mask_type; }
const std::string& mask() const { return m_mask; }
const std::string& clip_path() const { return m_clip_path; }
const std::string& marker_start() const { return m_marker_start; }
const std::string& marker_mid() const { return m_marker_mid; }
const std::string& marker_end() const { return m_marker_end; }
const std::string& font_family() const { return m_font_family; }
Font font() const;
private:
const SVGLayoutState* m_parent = nullptr;
const SVGElement* m_element = nullptr;
Paint m_fill{Color::Black};
Paint m_stroke{Color::Transparent};
Color m_color = Color::Black;
Color m_stop_color = Color::Black;
float m_opacity = 1.f;
float m_fill_opacity = 1.f;
float m_stroke_opacity = 1.f;
float m_stop_opacity = 1.f;
float m_stroke_miterlimit = 4.f;
float m_font_size = 12.f;
Length m_letter_spacing{0.f, LengthUnits::None};
Length m_word_spacing{0.f, LengthUnits::None};
BaselineShift m_baseline_shit;
Length m_stroke_width{1.f, LengthUnits::None};
Length m_stroke_dashoffset{0.f, LengthUnits::None};
LengthList m_stroke_dasharray;
LineCap m_stroke_linecap = LineCap::Butt;
LineJoin m_stroke_linejoin = LineJoin::Miter;
FillRule m_fill_rule = FillRule::NonZero;
FillRule m_clip_rule = FillRule::NonZero;
FontWeight m_font_weight = FontWeight::Normal;
FontStyle m_font_style = FontStyle::Normal;
AlignmentBaseline m_alignment_baseline = AlignmentBaseline::Auto;
DominantBaseline m_dominant_baseline = DominantBaseline::Auto;
TextAnchor m_text_anchor = TextAnchor::Start;
WhiteSpace m_white_space = WhiteSpace::Default;
WritingMode m_writing_mode = WritingMode::Horizontal;
TextOrientation m_text_orientation = TextOrientation::Mixed;
Direction m_direction = Direction::Ltr;
Display m_display = Display::Inline;
Visibility m_visibility = Visibility::Visible;
Overflow m_overflow = Overflow::Visible;
PointerEvents m_pointer_events = PointerEvents::Auto;
MaskType m_mask_type = MaskType::Luminance;
std::string m_mask;
std::string m_clip_path;
std::string m_marker_start;
std::string m_marker_mid;
std::string m_marker_end;
std::string m_font_family;
};
} // namespace lunasvg
}
#endif // LUNASVG_SVGLAYOUTSTATE_H
@@ -0,0 +1,366 @@
#include "svgpaintelement.h"
#include "svglayoutstate.h"
#include "svgrenderstate.h"
#include <cmath>
#include <set>
namespace {
namespace lunasvg {
SVGPaintElement::SVGPaintElement(Document* document, ElementID id)
: SVGElement(document, id)
{
}
SVGStopElement::SVGStopElement(Document* document)
: SVGElement(document, ElementID::Stop)
, m_offset(PropertyID::Offset, 0.f)
{
addProperty(m_offset);
}
void SVGStopElement::layoutElement(const SVGLayoutState& state)
{
m_stop_color = state.stop_color();
m_stop_opacity = state.stop_opacity();
SVGElement::layoutElement(state);
}
GradientStop SVGStopElement::gradientStop(float opacity) const
{
Color stopColor = m_stop_color.colorWithAlpha(m_stop_opacity * opacity);
GradientStop gradientStop = {
m_offset.value(), { stopColor.redF(), stopColor.greenF(), stopColor.blueF(), stopColor.alphaF() }
};
return gradientStop;
}
SVGGradientElement::SVGGradientElement(Document* document, ElementID id)
: SVGPaintElement(document, id)
, SVGURIReference(this)
, m_gradientTransform(PropertyID::GradientTransform)
, m_gradientUnits(PropertyID::GradientUnits, Units::ObjectBoundingBox)
, m_spreadMethod(PropertyID::SpreadMethod, SpreadMethod::Pad)
{
addProperty(m_gradientTransform);
addProperty(m_gradientUnits);
addProperty(m_spreadMethod);
}
void SVGGradientElement::collectGradientAttributes(SVGGradientAttributes& attributes) const
{
if(!attributes.hasGradientTransform() && hasAttribute(PropertyID::GradientTransform))
attributes.setGradientTransform(this);
if(!attributes.hasSpreadMethod() && hasAttribute(PropertyID::SpreadMethod))
attributes.setSpreadMethod(this);
if(!attributes.hasGradientUnits() && hasAttribute(PropertyID::GradientUnits))
attributes.setGradientUnits(this);
if(!attributes.hasGradientContentElement()) {
for(const auto& child : children()) {
if(auto element = toSVGElement(child); element && element->id() == ElementID::Stop) {
attributes.setGradientContentElement(this);
break;
}
}
}
}
SVGLinearGradientElement::SVGLinearGradientElement(Document* document)
: SVGGradientElement(document, ElementID::LinearGradient)
, m_x1(PropertyID::X1, LengthDirection::Horizontal, LengthNegativeMode::Allow, 0.f, LengthUnits::Percent)
, m_y1(PropertyID::Y1, LengthDirection::Vertical, LengthNegativeMode::Allow, 0.f, LengthUnits::Percent)
, m_x2(PropertyID::X2, LengthDirection::Horizontal, LengthNegativeMode::Allow, 100.f, LengthUnits::Percent)
, m_y2(PropertyID::Y2, LengthDirection::Vertical, LengthNegativeMode::Allow, 0.f, LengthUnits::Percent)
{
addProperty(m_x1);
addProperty(m_y1);
addProperty(m_x2);
addProperty(m_y2);
}
SVGLinearGradientAttributes SVGLinearGradientElement::collectGradientAttributes() const
{
SVGLinearGradientAttributes attributes;
std::set<const SVGGradientElement*> processedGradients;
const SVGGradientElement* current = this;
while(true) {
current->collectGradientAttributes(attributes);
if(current->id() == ElementID::LinearGradient) {
auto element = static_cast<const SVGLinearGradientElement*>(current);
if(!attributes.hasX1() && element->hasAttribute(PropertyID::X1))
attributes.setX1(element);
if(!attributes.hasY1() && element->hasAttribute(PropertyID::Y1))
attributes.setY1(element);
if(!attributes.hasX2() && element->hasAttribute(PropertyID::X2))
attributes.setX2(element);
if(!attributes.hasY2() && element->hasAttribute(PropertyID::Y2)) {
attributes.setY2(element);
}
}
auto targetElement = current->getTargetElement(document());
if(!targetElement || !(targetElement->id() == ElementID::LinearGradient || targetElement->id() == ElementID::RadialGradient))
break;
processedGradients.insert(current);
current = static_cast<const SVGGradientElement*>(targetElement);
if(processedGradients.count(current) > 0) {
break;
}
}
attributes.setDefaultValues(this);
return attributes;
}
static GradientStops buildGradientStops(const SVGGradientElement* element, float opacity)
{
GradientStops gradientStops;
const auto& children = element->children();
gradientStops.reserve(children.size());
for(const auto& child : children) {
auto childElement = toSVGElement(child);
if(childElement && childElement->id() == ElementID::Stop) {
auto stopElement = static_cast<SVGStopElement*>(childElement);
gradientStops.push_back(stopElement->gradientStop(opacity));
}
}
return gradientStops;
}
bool SVGLinearGradientElement::applyPaint(SVGRenderState& state, float opacity) const
{
auto attributes = collectGradientAttributes();
auto gradientContentElement = attributes.gradientContentElement();
auto gradientStops = buildGradientStops(gradientContentElement, opacity);
if(gradientStops.empty())
return false;
LengthContext lengthContext(this, attributes.gradientUnits());
auto x1 = lengthContext.valueForLength(attributes.x1());
auto y1 = lengthContext.valueForLength(attributes.y1());
auto x2 = lengthContext.valueForLength(attributes.x2());
auto y2 = lengthContext.valueForLength(attributes.y2());
if(gradientStops.size() == 1 || (x1 == x2 && y1 == y2)) {
const auto& lastStop = gradientStops.back();
state->setColor(lastStop.color.r, lastStop.color.g, lastStop.color.b, lastStop.color.a);
return true;
}
auto spreadMethod = attributes.spreadMethod();
auto gradientUnits = attributes.gradientUnits();
auto gradientTransform = attributes.gradientTransform();
if(gradientUnits == Units::ObjectBoundingBox) {
auto bbox = state.fillBoundingBox();
gradientTransform.postMultiply(Transform(bbox.w, 0, 0, bbox.h, bbox.x, bbox.y));
}
state->setLinearGradient(x1, y1, x2, y2, spreadMethod, gradientStops, gradientTransform);
return true;
}
SVGRadialGradientElement::SVGRadialGradientElement(Document* document)
: SVGGradientElement(document, ElementID::RadialGradient)
, m_cx(PropertyID::Cx, LengthDirection::Horizontal, LengthNegativeMode::Allow, 50.f, LengthUnits::Percent)
, m_cy(PropertyID::Cy, LengthDirection::Vertical, LengthNegativeMode::Allow, 50.f, LengthUnits::Percent)
, m_r(PropertyID::R, LengthDirection::Diagonal, LengthNegativeMode::Forbid, 50.f, LengthUnits::Percent)
, m_fx(PropertyID::Fx, LengthDirection::Horizontal, LengthNegativeMode::Allow, 0.f, LengthUnits::None)
, m_fy(PropertyID::Fy, LengthDirection::Vertical, LengthNegativeMode::Allow, 0.f, LengthUnits::None)
{
addProperty(m_cx);
addProperty(m_cy);
addProperty(m_r);
addProperty(m_fx);
addProperty(m_fy);
}
bool SVGRadialGradientElement::applyPaint(SVGRenderState& state, float opacity) const
{
auto attributes = collectGradientAttributes();
auto gradientContentElement = attributes.gradientContentElement();
auto gradientStops = buildGradientStops(gradientContentElement, opacity);
if(gradientStops.empty())
return false;
LengthContext lengthContext(this, attributes.gradientUnits());
auto r = lengthContext.valueForLength(attributes.r());
if(r == 0.f || gradientStops.size() == 1) {
const auto& lastStop = gradientStops.back();
state->setColor(lastStop.color.r, lastStop.color.g, lastStop.color.b, lastStop.color.a);
return true;
}
auto fx = lengthContext.valueForLength(attributes.fx());
auto fy = lengthContext.valueForLength(attributes.fy());
auto cx = lengthContext.valueForLength(attributes.cx());
auto cy = lengthContext.valueForLength(attributes.cy());
auto spreadMethod = attributes.spreadMethod();
auto gradientUnits = attributes.gradientUnits();
auto gradientTransform = attributes.gradientTransform();
if(gradientUnits == Units::ObjectBoundingBox) {
auto bbox = state.fillBoundingBox();
gradientTransform.postMultiply(Transform(bbox.w, 0, 0, bbox.h, bbox.x, bbox.y));
}
state->setRadialGradient(cx, cy, r, fx, fy, spreadMethod, gradientStops, gradientTransform);
return true;
}
SVGRadialGradientAttributes SVGRadialGradientElement::collectGradientAttributes() const
{
SVGRadialGradientAttributes attributes;
std::set<const SVGGradientElement*> processedGradients;
const SVGGradientElement* current = this;
while(true) {
current->collectGradientAttributes(attributes);
if(current->id() == ElementID::RadialGradient) {
auto element = static_cast<const SVGRadialGradientElement*>(current);
if(!attributes.hasCx() && element->hasAttribute(PropertyID::Cx))
attributes.setCx(element);
if(!attributes.hasCy() && element->hasAttribute(PropertyID::Cy))
attributes.setCy(element);
if(!attributes.hasR() && element->hasAttribute(PropertyID::R))
attributes.setR(element);
if(!attributes.hasFx() && element->hasAttribute(PropertyID::Fx))
attributes.setFx(element);
if(!attributes.hasFy() && element->hasAttribute(PropertyID::Fy)) {
attributes.setFy(element);
}
}
auto targetElement = current->getTargetElement(document());
if(!targetElement || !(targetElement->id() == ElementID::LinearGradient || targetElement->id() == ElementID::RadialGradient))
break;
processedGradients.insert(current);
current = static_cast<const SVGGradientElement*>(targetElement);
if(processedGradients.count(current) > 0) {
break;
}
}
attributes.setDefaultValues(this);
return attributes;
}
SVGPatternElement::SVGPatternElement(Document* document)
: SVGPaintElement(document, ElementID::Pattern)
, SVGURIReference(this)
, SVGFitToViewBox(this)
, m_x(PropertyID::X, LengthDirection::Horizontal, LengthNegativeMode::Allow)
, m_y(PropertyID::Y, LengthDirection::Vertical, LengthNegativeMode::Allow)
, m_width(PropertyID::Width, LengthDirection::Horizontal, LengthNegativeMode::Forbid)
, m_height(PropertyID::Height, LengthDirection::Vertical, LengthNegativeMode::Forbid)
, m_patternTransform(PropertyID::PatternTransform)
, m_patternUnits(PropertyID::PatternUnits, Units::ObjectBoundingBox)
, m_patternContentUnits(PropertyID::PatternContentUnits, Units::UserSpaceOnUse)
{
addProperty(m_x);
addProperty(m_y);
addProperty(m_width);
addProperty(m_height);
addProperty(m_patternTransform);
addProperty(m_patternUnits);
addProperty(m_patternContentUnits);
}
bool SVGPatternElement::applyPaint(SVGRenderState& state, float opacity) const
{
if(state.hasCycleReference(this))
return false;
auto attributes = collectPatternAttributes();
auto patternContentElement = attributes.patternContentElement();
if(patternContentElement == nullptr)
return false;
LengthContext lengthContext(this, attributes.patternUnits());
Rect patternRect = {
lengthContext.valueForLength(attributes.x()),
lengthContext.valueForLength(attributes.y()),
lengthContext.valueForLength(attributes.width()),
lengthContext.valueForLength(attributes.height())
};
if(attributes.patternUnits() == Units::ObjectBoundingBox) {
auto bbox = state.fillBoundingBox();
patternRect.x = patternRect.x * bbox.w + bbox.x;
patternRect.y = patternRect.y * bbox.h + bbox.y;
patternRect.w = patternRect.w * bbox.w;
patternRect.h = patternRect.h * bbox.h;
}
auto currentTransform = attributes.patternTransform() * state.currentTransform();
auto xScale = currentTransform.xScale();
auto yScale = currentTransform.yScale();
auto patternImage = state->create(0, 0, patternRect.w * xScale, patternRect.h * yScale);
auto patternImageTransform = Transform::scaled(xScale, yScale);
const auto& viewBoxRect = attributes.viewBox();
if(viewBoxRect.isValid()) {
const auto& preserveAspectRatio = attributes.preserveAspectRatio();
patternImageTransform.multiply(preserveAspectRatio.getTransform(viewBoxRect, patternRect.size()));
} else if(attributes.patternContentUnits() == Units::ObjectBoundingBox) {
auto bbox = state.fillBoundingBox();
patternImageTransform.scale(bbox.w, bbox.h);
}
SVGRenderState newState(this, &state, patternImageTransform, SVGRenderMode::Painting, patternImage);
patternContentElement->renderChildren(newState);
auto patternTransform = attributes.patternTransform();
patternTransform.translate(patternRect.x, patternRect.y);
patternTransform.scale(patternRect.w / patternImage->width(), patternRect.h / patternImage->height());
state->setTexture(*patternImage, TextureType::Tiled, opacity, patternTransform);
return true;
}
SVGPatternAttributes SVGPatternElement::collectPatternAttributes() const
{
SVGPatternAttributes attributes;
std::set<const SVGPatternElement*> processedPatterns;
const SVGPatternElement* current = this;
while(true) {
if(!attributes.hasX() && current->hasAttribute(PropertyID::X))
attributes.setX(current);
if(!attributes.hasY() && current->hasAttribute(PropertyID::Y))
attributes.setY(current);
if(!attributes.hasWidth() && current->hasAttribute(PropertyID::Width))
attributes.setWidth(current);
if(!attributes.hasHeight() && current->hasAttribute(PropertyID::Height))
attributes.setHeight(current);
if(!attributes.hasPatternTransform() && current->hasAttribute(PropertyID::PatternTransform))
attributes.setPatternTransform(current);
if(!attributes.hasPatternUnits() && current->hasAttribute(PropertyID::PatternUnits))
attributes.setPatternUnits(current);
if(!attributes.hasPatternContentUnits() && current->hasAttribute(PropertyID::PatternContentUnits))
attributes.setPatternContentUnits(current);
if(!attributes.hasViewBox() && current->hasAttribute(PropertyID::ViewBox))
attributes.setViewBox(current);
if(!attributes.hasPreserveAspectRatio() && current->hasAttribute(PropertyID::PreserveAspectRatio))
attributes.setPreserveAspectRatio(current);
if(!attributes.hasPatternContentElement()) {
for(const auto& child : current->children()) {
if(child->isElement()) {
attributes.setPatternContentElement(current);
break;
}
}
}
auto targetElement = current->getTargetElement(document());
if(!targetElement || targetElement->id() != ElementID::Pattern)
break;
processedPatterns.insert(current);
current = static_cast<const SVGPatternElement*>(targetElement);
if(processedPatterns.count(current) > 0) {
break;
}
}
attributes.setDefaultValues(this);
return attributes;
}
} // namespace lunasvg
}
@@ -0,0 +1,290 @@
#ifndef LUNASVG_SVGPAINTELEMENT_H
#define LUNASVG_SVGPAINTELEMENT_H
#include "svgelement.h"
namespace {
namespace lunasvg {
class SVGPaintElement : public SVGElement {
public:
SVGPaintElement(Document* document, ElementID id);
bool isPaintElement() const final { return true; }
virtual bool applyPaint(SVGRenderState& state, float opacity) const = 0;
};
class SVGStopElement final : public SVGElement {
public:
SVGStopElement(Document* document);
void layoutElement(const SVGLayoutState& state) final;
const SVGNumberPercentage& offset() const { return m_offset; }
GradientStop gradientStop(float opacity) const;
private:
SVGNumberPercentage m_offset;
Color m_stop_color = Color::Black;
float m_stop_opacity = 1.f;
};
class SVGGradientAttributes;
class SVGGradientElement : public SVGPaintElement, public SVGURIReference {
public:
SVGGradientElement(Document* document, ElementID id);
const SVGTransform& gradientTransform() const { return m_gradientTransform; }
const SVGEnumeration<Units>& gradientUnits() const { return m_gradientUnits; }
const SVGEnumeration<SpreadMethod>& spreadMethod() const { return m_spreadMethod; }
void collectGradientAttributes(SVGGradientAttributes& attributes) const;
private:
SVGTransform m_gradientTransform;
SVGEnumeration<Units> m_gradientUnits;
SVGEnumeration<SpreadMethod> m_spreadMethod;
};
class SVGGradientAttributes {
public:
SVGGradientAttributes() = default;
const Transform& gradientTransform() const { return m_gradientTransform->gradientTransform().value(); }
SpreadMethod spreadMethod() const { return m_spreadMethod->spreadMethod().value(); }
Units gradientUnits() const { return m_gradientUnits->gradientUnits().value(); }
const SVGGradientElement* gradientContentElement() const { return m_gradientContentElement; }
bool hasGradientTransform() const { return m_gradientTransform; }
bool hasSpreadMethod() const { return m_spreadMethod; }
bool hasGradientUnits() const { return m_gradientUnits; }
bool hasGradientContentElement() const { return m_gradientContentElement; }
void setGradientTransform(const SVGGradientElement* value) { m_gradientTransform = value; }
void setSpreadMethod(const SVGGradientElement* value) { m_spreadMethod = value; }
void setGradientUnits(const SVGGradientElement* value) { m_gradientUnits = value; }
void setGradientContentElement(const SVGGradientElement* value) { m_gradientContentElement = value; }
void setDefaultValues(const SVGGradientElement* element) {
if(!m_gradientTransform) { m_gradientTransform = element; }
if(!m_spreadMethod) { m_spreadMethod = element; }
if(!m_gradientUnits) { m_gradientUnits = element; }
if(!m_gradientContentElement) { m_gradientContentElement = element; }
}
private:
const SVGGradientElement* m_gradientTransform{nullptr};
const SVGGradientElement* m_spreadMethod{nullptr};
const SVGGradientElement* m_gradientUnits{nullptr};
const SVGGradientElement* m_gradientContentElement{nullptr};
};
class SVGLinearGradientAttributes;
class SVGLinearGradientElement final : public SVGGradientElement {
public:
SVGLinearGradientElement(Document* document);
const SVGLength& x1() const { return m_x1; }
const SVGLength& y1() const { return m_y1; }
const SVGLength& x2() const { return m_x2; }
const SVGLength& y2() const { return m_y2; }
bool applyPaint(SVGRenderState& state, float opacity) const final;
private:
SVGLinearGradientAttributes collectGradientAttributes() const;
SVGLength m_x1;
SVGLength m_y1;
SVGLength m_x2;
SVGLength m_y2;
};
class SVGLinearGradientAttributes : public SVGGradientAttributes {
public:
SVGLinearGradientAttributes() = default;
const SVGLength& x1() const { return m_x1->x1(); }
const SVGLength& y1() const { return m_y1->y1(); }
const SVGLength& x2() const { return m_x2->x2(); }
const SVGLength& y2() const { return m_y2->y2(); }
bool hasX1() const { return m_x1; }
bool hasY1() const { return m_y1; }
bool hasX2() const { return m_x2; }
bool hasY2() const { return m_y2; }
void setX1(const SVGLinearGradientElement* value) { m_x1 = value; }
void setY1(const SVGLinearGradientElement* value) { m_y1 = value; }
void setX2(const SVGLinearGradientElement* value) { m_x2 = value; }
void setY2(const SVGLinearGradientElement* value) { m_y2 = value; }
void setDefaultValues(const SVGLinearGradientElement* element) {
SVGGradientAttributes::setDefaultValues(element);
if(!m_x1) { m_x1 = element; }
if(!m_y1) { m_y1 = element; }
if(!m_x2) { m_x2 = element; }
if(!m_y2) { m_y2 = element; }
}
private:
const SVGLinearGradientElement* m_x1{nullptr};
const SVGLinearGradientElement* m_y1{nullptr};
const SVGLinearGradientElement* m_x2{nullptr};
const SVGLinearGradientElement* m_y2{nullptr};
};
class SVGRadialGradientAttributes;
class SVGRadialGradientElement final : public SVGGradientElement {
public:
SVGRadialGradientElement(Document* document);
const SVGLength& cx() const { return m_cx; }
const SVGLength& cy() const { return m_cy; }
const SVGLength& r() const { return m_r; }
const SVGLength& fx() const { return m_fx; }
const SVGLength& fy() const { return m_fy; }
bool applyPaint(SVGRenderState& state, float opacity) const final;
private:
SVGRadialGradientAttributes collectGradientAttributes() const;
SVGLength m_cx;
SVGLength m_cy;
SVGLength m_r;
SVGLength m_fx;
SVGLength m_fy;
};
class SVGRadialGradientAttributes : public SVGGradientAttributes {
public:
SVGRadialGradientAttributes() = default;
const SVGLength& cx() const { return m_cx->cx(); }
const SVGLength& cy() const { return m_cy->cy(); }
const SVGLength& r() const { return m_r->r(); }
const SVGLength& fx() const { return m_fx ? m_fx->fx() : m_cx->cx(); }
const SVGLength& fy() const { return m_fy ? m_fy->fy() : m_cy->cy(); }
bool hasCx() const { return m_cx; }
bool hasCy() const { return m_cy; }
bool hasR() const { return m_r; }
bool hasFx() const { return m_fx; }
bool hasFy() const { return m_fy; }
void setCx(const SVGRadialGradientElement* value) { m_cx = value; }
void setCy(const SVGRadialGradientElement* value) { m_cy = value; }
void setR(const SVGRadialGradientElement* value) { m_r = value; }
void setFx(const SVGRadialGradientElement* value) { m_fx = value; }
void setFy(const SVGRadialGradientElement* value) { m_fy = value; }
void setDefaultValues(const SVGRadialGradientElement* element) {
SVGGradientAttributes::setDefaultValues(element);
if(!m_cx) { m_cx = element; }
if(!m_cy) { m_cy = element; }
if(!m_r) { m_r = element; }
}
private:
const SVGRadialGradientElement* m_cx{nullptr};
const SVGRadialGradientElement* m_cy{nullptr};
const SVGRadialGradientElement* m_r{nullptr};
const SVGRadialGradientElement* m_fx{nullptr};
const SVGRadialGradientElement* m_fy{nullptr};
};
class SVGPatternAttributes;
class SVGPatternElement final : public SVGPaintElement, public SVGURIReference, public SVGFitToViewBox {
public:
SVGPatternElement(Document* document);
const SVGLength& x() const { return m_x; }
const SVGLength& y() const { return m_y; }
const SVGLength& width() const { return m_width; }
const SVGLength& height() const { return m_height; }
const SVGTransform& patternTransform() const { return m_patternTransform; }
const SVGEnumeration<Units>& patternUnits() const { return m_patternUnits; }
const SVGEnumeration<Units>& patternContentUnits() const { return m_patternContentUnits; }
bool applyPaint(SVGRenderState& state, float opacity) const final;
private:
SVGPatternAttributes collectPatternAttributes() const;
SVGLength m_x;
SVGLength m_y;
SVGLength m_width;
SVGLength m_height;
SVGTransform m_patternTransform;
SVGEnumeration<Units> m_patternUnits;
SVGEnumeration<Units> m_patternContentUnits;
};
class SVGPatternAttributes {
public:
SVGPatternAttributes() = default;
const SVGLength& x() const { return m_x->x(); }
const SVGLength& y() const { return m_y->y(); }
const SVGLength& width() const { return m_width->width(); }
const SVGLength& height() const { return m_height->height(); }
const Transform& patternTransform() const { return m_patternTransform->patternTransform().value(); }
Units patternUnits() const { return m_patternUnits->patternUnits().value(); }
Units patternContentUnits() const { return m_patternContentUnits->patternContentUnits().value(); }
const Rect& viewBox() const { return m_viewBox->viewBox().value(); }
const SVGPreserveAspectRatio& preserveAspectRatio() const { return m_preserveAspectRatio->preserveAspectRatio(); }
const SVGPatternElement* patternContentElement() const { return m_patternContentElement; }
bool hasX() const { return m_x; }
bool hasY() const { return m_y; }
bool hasWidth() const { return m_width; }
bool hasHeight() const { return m_height; }
bool hasPatternTransform() const { return m_patternTransform; }
bool hasPatternUnits() const { return m_patternUnits; }
bool hasPatternContentUnits() const { return m_patternContentUnits; }
bool hasViewBox() const { return m_viewBox; }
bool hasPreserveAspectRatio() const { return m_preserveAspectRatio; }
bool hasPatternContentElement() const { return m_patternContentElement; }
void setX(const SVGPatternElement* value) { m_x = value; }
void setY(const SVGPatternElement* value) { m_y = value; }
void setWidth(const SVGPatternElement* value) { m_width = value; }
void setHeight(const SVGPatternElement* value) { m_height = value; }
void setPatternTransform(const SVGPatternElement* value) { m_patternTransform = value; }
void setPatternUnits(const SVGPatternElement* value) { m_patternUnits = value; }
void setPatternContentUnits(const SVGPatternElement* value) { m_patternContentUnits = value; }
void setViewBox(const SVGPatternElement* value) { m_viewBox = value; }
void setPreserveAspectRatio(const SVGPatternElement* value) { m_preserveAspectRatio = value; }
void setPatternContentElement(const SVGPatternElement* value) { m_patternContentElement = value; }
void setDefaultValues(const SVGPatternElement* element) {
if(!m_x) { m_x = element; }
if(!m_y) { m_y = element; }
if(!m_width) { m_width = element; }
if(!m_height) { m_height = element; }
if(!m_patternTransform) { m_patternTransform = element; }
if(!m_patternUnits) { m_patternUnits = element; }
if(!m_patternContentUnits) { m_patternContentUnits = element; }
if(!m_viewBox) { m_viewBox = element; }
if(!m_preserveAspectRatio) { m_preserveAspectRatio = element; }
if(!m_patternContentElement) { m_patternContentElement = element; }
}
private:
const SVGPatternElement* m_x{nullptr};
const SVGPatternElement* m_y{nullptr};
const SVGPatternElement* m_width{nullptr};
const SVGPatternElement* m_height{nullptr};
const SVGPatternElement* m_patternTransform{nullptr};
const SVGPatternElement* m_patternUnits{nullptr};
const SVGPatternElement* m_patternContentUnits{nullptr};
const SVGPatternElement* m_viewBox{nullptr};
const SVGPatternElement* m_preserveAspectRatio{nullptr};
const SVGPatternElement* m_patternContentElement{nullptr};
};
} // namespace lunasvg
}
#endif // LUNASVG_SVGPAINTELEMENT_H
@@ -0,0 +1,944 @@
#include "../include/lunasvg.h"
#include "svgelement.h"
#include "svgparserutils.h"
#include <cassert>
namespace {
namespace lunasvg {
struct SimpleSelector;
using Selector = std::vector<SimpleSelector>;
using SelectorList = std::vector<Selector>;
struct AttributeSelector {
enum class MatchType {
None,
Equals,
Contains,
Includes,
StartsWith,
EndsWith,
DashEquals
};
MatchType matchType{MatchType::None};
PropertyID id{PropertyID::Unknown};
std::string value;
};
struct PseudoClassSelector {
enum class Type {
Unknown,
Empty,
Root,
Is,
Not,
FirstChild,
LastChild,
OnlyChild,
FirstOfType,
LastOfType,
OnlyOfType
};
Type type{Type::Unknown};
SelectorList subSelectors;
};
struct SimpleSelector {
enum class Combinator {
None,
Descendant,
Child,
DirectAdjacent,
InDirectAdjacent
};
explicit SimpleSelector(Combinator combinator) : combinator(combinator) {}
Combinator combinator{Combinator::Descendant};
ElementID id{ElementID::Star};
std::vector<AttributeSelector> attributeSelectors;
std::vector<PseudoClassSelector> pseudoClassSelectors;
};
struct Declaration {
int specificity;
PropertyID id;
std::string value;
};
using DeclarationList = std::vector<Declaration>;
struct Rule {
SelectorList selectors;
DeclarationList declarations;
};
class RuleData {
public:
RuleData(const Selector& selector, const DeclarationList& declarations, size_t specificity, size_t position)
: m_selector(selector), m_declarations(declarations), m_specificity(specificity), m_position(position)
{}
bool isLessThan(const RuleData& rule) const { return std::tie(m_specificity, m_position) < std::tie(rule.m_specificity, rule.m_position); }
const Selector& selector() const { return m_selector; }
const DeclarationList& declarations() const { return m_declarations; }
size_t specificity() const { return m_specificity; }
size_t position() const { return m_position; }
bool match(const SVGElement* element) const;
private:
Selector m_selector;
DeclarationList m_declarations;
size_t m_specificity;
size_t m_position;
};
inline bool operator<(const RuleData& a, const RuleData& b) { return a.isLessThan(b); }
using RuleDataList = std::vector<RuleData>;
constexpr bool equals(const std::string_view& value, const std::string_view& subvalue)
{
return value.compare(subvalue) == 0;
}
constexpr bool contains(const std::string_view& value, const std::string_view& subvalue)
{
return value.find(subvalue) != std::string_view::npos;
}
constexpr bool includes(const std::string_view& value, const std::string_view& subvalue)
{
if(subvalue.empty() || subvalue.length() > value.length())
return false;
std::string_view input(value);
while(!input.empty()) {
skipOptionalSpaces(input);
std::string_view start(input);
while(!input.empty() && !IS_WS(input.front()))
input.remove_prefix(1);
if(subvalue == start.substr(0, start.length() - input.length())) {
return true;
}
}
return false;
}
constexpr bool startswith(const std::string_view& value, const std::string_view& subvalue)
{
if(subvalue.empty() || subvalue.length() > value.length())
return false;
return subvalue == value.substr(0, subvalue.size());
}
constexpr bool endswith(const std::string_view& value, const std::string_view& subvalue)
{
if(subvalue.empty() || subvalue.length() > value.length())
return false;
return subvalue == value.substr(value.size() - subvalue.size(), subvalue.size());
}
constexpr bool dashequals(const std::string_view& value, const std::string_view& subvalue)
{
if(startswith(value, subvalue))
return (value.length() == subvalue.length() || value.at(subvalue.length()) == '-');
return false;
}
static bool matchAttributeSelector(const AttributeSelector& selector, const SVGElement* element)
{
const auto& value = element->getAttribute(selector.id);
if(selector.matchType == AttributeSelector::MatchType::None)
return !value.empty();
if(selector.matchType == AttributeSelector::MatchType::Equals)
return equals(value, selector.value);
if(selector.matchType == AttributeSelector::MatchType::Contains)
return contains(value, selector.value);
if(selector.matchType == AttributeSelector::MatchType::Includes)
return includes(value, selector.value);
if(selector.matchType == AttributeSelector::MatchType::StartsWith)
return startswith(value, selector.value);
if(selector.matchType == AttributeSelector::MatchType::EndsWith)
return endswith(value, selector.value);
if(selector.matchType == AttributeSelector::MatchType::DashEquals)
return dashequals(value, selector.value);
return false;
}
static bool matchSimpleSelector(const SimpleSelector& selector, const SVGElement* element);
static bool matchPseudoClassSelector(const PseudoClassSelector& selector, const SVGElement* element)
{
if(selector.type == PseudoClassSelector::Type::Empty)
return element->children().empty();
if(selector.type == PseudoClassSelector::Type::Root)
return element->isRootElement();
if(selector.type == PseudoClassSelector::Type::Is) {
for(const auto& subSelector : selector.subSelectors) {
for(const auto& simpleSelector : subSelector) {
if(!matchSimpleSelector(simpleSelector, element)) {
return false;
}
}
}
return true;
}
if(selector.type == PseudoClassSelector::Type::Not) {
for(const auto& subSelector : selector.subSelectors) {
for(const auto& simpleSelector : subSelector) {
if(matchSimpleSelector(simpleSelector, element)) {
return false;
}
}
}
return true;
}
if(selector.type == PseudoClassSelector::Type::FirstChild)
return !element->previousElement();
if(selector.type == PseudoClassSelector::Type::LastChild)
return !element->nextElement();
if(selector.type == PseudoClassSelector::Type::OnlyChild)
return !(element->previousElement() || element->nextElement());
if(selector.type == PseudoClassSelector::Type::FirstOfType) {
auto sibling = element->previousElement();
while(sibling) {
if(sibling->id() == element->id())
return false;
sibling = element->previousElement();
}
return true;
}
if(selector.type == PseudoClassSelector::Type::LastOfType) {
auto sibling = element->nextElement();
while(sibling) {
if(sibling->id() == element->id())
return false;
sibling = element->nextElement();
}
return true;
}
return false;
}
static bool matchSimpleSelector(const SimpleSelector& selector, const SVGElement* element)
{
if(selector.id != ElementID::Star && selector.id != element->id())
return false;
for(const auto& sel : selector.attributeSelectors) {
if(!matchAttributeSelector(sel, element)) {
return false;
}
}
for(const auto& sel : selector.pseudoClassSelectors) {
if(!matchPseudoClassSelector(sel, element)) {
return false;
}
}
return true;
}
static bool matchSelector(const Selector& selector, const SVGElement* element)
{
if(selector.empty())
return false;
auto it = selector.rbegin();
auto end = selector.rend();
if(!matchSimpleSelector(*it, element)) {
return false;
}
auto combinator = it->combinator;
++it;
while(it != end) {
switch(combinator) {
case SimpleSelector::Combinator::Child:
case SimpleSelector::Combinator::Descendant:
element = element->parentElement();
break;
case SimpleSelector::Combinator::DirectAdjacent:
case SimpleSelector::Combinator::InDirectAdjacent:
element = element->previousElement();
break;
case SimpleSelector::Combinator::None:
assert(false);
}
if(element == nullptr)
return false;
if(matchSimpleSelector(*it, element)) {
combinator = it->combinator;
++it;
} else if(combinator != SimpleSelector::Combinator::Descendant
&& combinator != SimpleSelector::Combinator::InDirectAdjacent) {
return false;
}
}
return true;
}
bool RuleData::match(const SVGElement* element) const
{
return matchSelector(m_selector, element);
}
constexpr bool IS_CSS_STARTNAMECHAR(int c) { return IS_ALPHA(c) || c == '_' || c == '-'; }
constexpr bool IS_CSS_NAMECHAR(int c) { return IS_CSS_STARTNAMECHAR(c) || IS_NUM(c); }
inline bool readCSSIdentifier(std::string_view& input, std::string& output)
{
if(input.empty() || !IS_CSS_STARTNAMECHAR(input.front()))
return false;
output.clear();
do {
output.push_back(input.front());
input.remove_prefix(1);
} while(!input.empty() && IS_CSS_NAMECHAR(input.front()));
return true;
}
static bool parseTagSelector(std::string_view& input, SimpleSelector& simpleSelector)
{
std::string name;
if(skipDelimiter(input, '*'))
simpleSelector.id = ElementID::Star;
else if(readCSSIdentifier(input, name))
simpleSelector.id = elementid(name);
else
return false;
return true;
}
static bool parseIdSelector(std::string_view& input, SimpleSelector& simpleSelector)
{
AttributeSelector a;
a.id = PropertyID::Id;
a.matchType = AttributeSelector::MatchType::Equals;
if(!readCSSIdentifier(input, a.value))
return false;
simpleSelector.attributeSelectors.push_back(std::move(a));
return true;
}
static bool parseClassSelector(std::string_view& input, SimpleSelector& simpleSelector)
{
AttributeSelector a;
a.id = PropertyID::Class;
a.matchType = AttributeSelector::MatchType::Includes;
if(!readCSSIdentifier(input, a.value))
return false;
simpleSelector.attributeSelectors.push_back(std::move(a));
return true;
}
static bool parseAttributeSelector(std::string_view& input, SimpleSelector& simpleSelector)
{
std::string name;
skipOptionalSpaces(input);
if(!readCSSIdentifier(input, name))
return false;
AttributeSelector a;
a.id = propertyid(name);
a.matchType = AttributeSelector::MatchType::None;
if(skipDelimiter(input, '='))
a.matchType = AttributeSelector::MatchType::Equals;
else if(skipString(input, "*="))
a.matchType = AttributeSelector::MatchType::Contains;
else if(skipString(input, "~="))
a.matchType = AttributeSelector::MatchType::Includes;
else if(skipString(input, "^="))
a.matchType = AttributeSelector::MatchType::StartsWith;
else if(skipString(input, "$="))
a.matchType = AttributeSelector::MatchType::EndsWith;
else if(skipString(input, "|="))
a.matchType = AttributeSelector::MatchType::DashEquals;
if(a.matchType != AttributeSelector::MatchType::None) {
skipOptionalSpaces(input);
if(!readCSSIdentifier(input, a.value)) {
if(input.empty() || !(input.front() == '\"' || input.front() == '\''))
return false;
auto quote = input.front();
input.remove_prefix(1);
auto n = input.find(quote);
if(n == std::string_view::npos)
return false;
a.value.assign(input.substr(0, n));
input.remove_prefix(n + 1);
}
}
skipOptionalSpaces(input);
if(!skipDelimiter(input, ']'))
return false;
simpleSelector.attributeSelectors.push_back(std::move(a));
return true;
}
static bool parseSelectors(std::string_view& input, SelectorList& selectors);
static bool parsePseudoClassSelector(std::string_view& input, SimpleSelector& simpleSelector)
{
std::string name;
if(!readCSSIdentifier(input, name))
return false;
PseudoClassSelector selector;
if(name.compare("empty") == 0)
selector.type = PseudoClassSelector::Type::Empty;
else if(name.compare("root") == 0)
selector.type = PseudoClassSelector::Type::Root;
else if(name.compare("not") == 0)
selector.type = PseudoClassSelector::Type::Not;
else if(name.compare("first-child") == 0)
selector.type = PseudoClassSelector::Type::FirstChild;
else if(name.compare("last-child") == 0)
selector.type = PseudoClassSelector::Type::LastChild;
else if(name.compare("only-child") == 0)
selector.type = PseudoClassSelector::Type::OnlyChild;
else if(name.compare("first-of-type") == 0)
selector.type = PseudoClassSelector::Type::FirstOfType;
else if(name.compare("last-of-type") == 0)
selector.type = PseudoClassSelector::Type::LastOfType;
else if(name.compare("only-of-type") == 0)
selector.type = PseudoClassSelector::Type::OnlyOfType;
if(selector.type == PseudoClassSelector::Type::Is || selector.type == PseudoClassSelector::Type::Not) {
skipOptionalSpaces(input);
if(!skipDelimiter(input, '('))
return false;
skipOptionalSpaces(input);
if(!parseSelectors(input, selector.subSelectors))
return false;
skipOptionalSpaces(input);
if(!skipDelimiter(input, ')')) {
return false;
}
}
simpleSelector.pseudoClassSelectors.push_back(std::move(selector));
return true;
}
static bool parseSimpleSelector(std::string_view& input, SimpleSelector& simpleSelector, bool& failed)
{
auto consumed = parseTagSelector(input, simpleSelector);
do {
if(skipDelimiter(input, '#'))
failed = !parseIdSelector(input, simpleSelector);
else if(skipDelimiter(input, '.'))
failed = !parseClassSelector(input, simpleSelector);
else if(skipDelimiter(input, '['))
failed = !parseAttributeSelector(input, simpleSelector);
else if(skipDelimiter(input, ':'))
failed = !parsePseudoClassSelector(input, simpleSelector);
else
break;
consumed = true;
} while(!failed);
return consumed && !failed;
}
static bool parseCombinator(std::string_view& input, SimpleSelector::Combinator& combinator)
{
combinator = SimpleSelector::Combinator::None;
while(!input.empty() && IS_WS(input.front())) {
combinator = SimpleSelector::Combinator::Descendant;
input.remove_prefix(1);
}
if(skipDelimiterAndOptionalSpaces(input, '>'))
combinator = SimpleSelector::Combinator::Child;
else if(skipDelimiterAndOptionalSpaces(input, '+'))
combinator = SimpleSelector::Combinator::DirectAdjacent;
else if(skipDelimiterAndOptionalSpaces(input, '~'))
combinator = SimpleSelector::Combinator::InDirectAdjacent;
return combinator != SimpleSelector::Combinator::None;
}
static bool parseSelector(std::string_view& input, Selector& selector)
{
auto combinator = SimpleSelector::Combinator::None;
do {
bool failed = false;
SimpleSelector simpleSelector(combinator);
if(!parseSimpleSelector(input, simpleSelector, failed))
return !failed && (combinator == SimpleSelector::Combinator::Descendant);
selector.push_back(std::move(simpleSelector));
} while(parseCombinator(input, combinator));
return true;
}
static bool parseSelectors(std::string_view& input, SelectorList& selectors)
{
do {
Selector selector;
if(!parseSelector(input, selector))
return false;
selectors.push_back(std::move(selector));
} while(skipDelimiterAndOptionalSpaces(input, ','));
return true;
}
static bool parseDeclarations(std::string_view& input, DeclarationList& declarations)
{
if(!skipDelimiter(input, '{'))
return false;
skipOptionalSpaces(input);
do {
std::string name;
if(!readCSSIdentifier(input, name))
return false;
skipOptionalSpaces(input);
if(!skipDelimiter(input, ':'))
return false;
skipOptionalSpaces(input);
std::string_view value(input);
while(!input.empty() && !(input.front() == '!' || input.front() == ';' || input.front() == '}'))
input.remove_prefix(1);
value.remove_suffix(input.length());
stripTrailingSpaces(value);
Declaration declaration;
declaration.specificity = 0x10;
declaration.id = csspropertyid(name);
declaration.value.assign(value);
if(skipDelimiter(input, '!')) {
skipOptionalSpaces(input);
if(!skipString(input, "important"))
return false;
declaration.specificity = 0x1000;
}
if(declaration.id != PropertyID::Unknown)
declarations.push_back(std::move(declaration));
skipOptionalSpacesOrDelimiter(input, ';');
} while(!input.empty() && input.front() != '}');
return skipDelimiter(input, '}');
}
static bool parseRule(std::string_view& input, Rule& rule)
{
if(!parseSelectors(input, rule.selectors))
return false;
return parseDeclarations(input, rule.declarations);
}
static RuleDataList parseStyleSheet(std::string_view input)
{
RuleDataList rules;
while(!input.empty()) {
skipOptionalSpaces(input);
if(skipDelimiter(input, '@')) {
int depth = 0;
while(!input.empty()) {
auto ch = input.front();
input.remove_prefix(1);
if(ch == ';' && depth == 0)
break;
if(ch == '{') ++depth;
else if(ch == '}' && depth > 0) {
if(depth == 1)
break;
--depth;
}
}
continue;
}
Rule rule;
if(!parseRule(input, rule))
break;
for(const auto& selector : rule.selectors) {
size_t specificity = 0;
for(const auto& simpleSelector : selector) {
specificity += (simpleSelector.id == ElementID::Star) ? 0x0 : 0x1;
for(const auto& attributeSelector : simpleSelector.attributeSelectors) {
specificity += (attributeSelector.id == PropertyID::Id) ? 0x10000 : 0x100;
}
}
rules.emplace_back(selector, rule.declarations, specificity, rules.size());
}
}
return rules;
}
static SelectorList parseQuerySelectors(std::string_view input)
{
SelectorList selectors;
stripLeadingAndTrailingSpaces(input);
if(!parseSelectors(input, selectors)
|| !input.empty()) {
return SelectorList();
}
return selectors;
}
inline void parseInlineStyle(std::string_view input, SVGElement* element)
{
std::string name;
skipOptionalSpaces(input);
while(readCSSIdentifier(input, name)) {
skipOptionalSpaces(input);
if(!skipDelimiter(input, ':'))
return;
std::string value;
while(!input.empty() && input.front() != ';') {
value.push_back(input.front());
input.remove_prefix(1);
}
auto id = csspropertyid(name);
if(id != PropertyID::Unknown)
element->setAttribute(0x100, id, value);
skipOptionalSpacesOrDelimiter(input, ';');
}
}
inline void removeStyleComments(std::string& value)
{
auto start = value.find("/*");
while(start != std::string::npos) {
auto end = value.find("*/", start + 2);
value.erase(start, end - start + 2);
start = value.find("/*");
}
}
inline bool decodeText(std::string_view input, std::string& output)
{
output.clear();
while(!input.empty()) {
auto ch = input.front();
input.remove_prefix(1);
if(ch != '&') {
output.push_back(ch);
continue;
}
if(skipDelimiter(input, '#')) {
int base = 10;
if(skipDelimiter(input, 'x'))
base = 16;
unsigned int cp;
if(!parseInteger(input, cp, base))
return false;
char c[5] = {0, 0, 0, 0, 0};
if(cp < 0x80) {
c[1] = 0;
c[0] = char(cp);
} else if(cp < 0x800) {
c[2] = 0;
c[1] = char((cp & 0x3F) | 0x80);
cp >>= 6;
c[0] = char(cp | 0xC0);
} else if(cp < 0x10000) {
c[3] = 0;
c[2] = char((cp & 0x3F) | 0x80);
cp >>= 6;
c[1] = char((cp & 0x3F) | 0x80);
cp >>= 6;
c[0] = char(cp | 0xE0);
} else if(cp < 0x200000) {
c[4] = 0;
c[3] = char((cp & 0x3F) | 0x80);
cp >>= 6;
c[2] = char((cp & 0x3F) | 0x80);
cp >>= 6;
c[1] = char((cp & 0x3F) | 0x80);
cp >>= 6;
c[0] = char(cp | 0xF0);
}
output.append(c);
} else {
if(skipString(input, "amp")) {
output.push_back('&');
} else if(skipString(input, "lt")) {
output.push_back('<');
} else if(skipString(input, "gt")) {
output.push_back('>');
} else if(skipString(input, "quot")) {
output.push_back('\"');
} else if(skipString(input, "apos")) {
output.push_back('\'');
} else {
return false;
}
}
if(!skipDelimiter(input, ';')) {
return false;
}
}
return true;
}
constexpr bool IS_STARTNAMECHAR(int c) { return IS_ALPHA(c) || c == '_' || c == ':'; }
constexpr bool IS_NAMECHAR(int c) { return IS_STARTNAMECHAR(c) || IS_NUM(c) || c == '-' || c == '.'; }
inline bool readIdentifier(std::string_view& input, std::string& output)
{
if(input.empty() || !IS_STARTNAMECHAR(input.front()))
return false;
output.clear();
do {
output.push_back(input.front());
input.remove_prefix(1);
} while(!input.empty() && IS_NAMECHAR(input.front()));
return true;
}
bool Document::parse(const char* data, size_t length)
{
std::string buffer;
std::string styleSheet;
SVGElement* currentElement = nullptr;
int ignoring = 0;
auto handleText = [&](const std::string_view& text, bool in_cdata) {
if(text.empty() || currentElement == nullptr || ignoring > 0)
return;
if(currentElement->id() != ElementID::Text && currentElement->id() != ElementID::Tspan && currentElement->id() != ElementID::Style) {
return;
}
if(in_cdata) {
buffer.assign(text);
} else {
decodeText(text, buffer);
}
if(currentElement->id() == ElementID::Style) {
removeStyleComments(buffer);
styleSheet.append(buffer);
} else {
auto node = std::make_unique<SVGTextNode>(this);
node->setData(buffer);
currentElement->addChild(std::move(node));
}
};
std::string_view input(data, length);
while(!input.empty()) {
if(currentElement) {
auto text = input.substr(0, input.find('<'));
handleText(text, false);
input.remove_prefix(text.length());
} else {
if(!skipOptionalSpaces(input)) {
break;
}
}
if(!skipDelimiter(input, '<'))
return false;
if(skipDelimiter(input, '?')) {
if(!readIdentifier(input, buffer))
return false;
auto n = input.find("?>");
if(n == std::string_view::npos)
return false;
input.remove_prefix(n + 2);
continue;
}
if(skipDelimiter(input, '!')) {
if(skipString(input, "--")) {
auto n = input.find("-->");
if(n == std::string_view::npos)
return false;
handleText(input.substr(0, n), false);
input.remove_prefix(n + 3);
continue;
}
if(skipString(input, "[CDATA[")) {
auto n = input.find("]]>");
if(n == std::string_view::npos)
return false;
handleText(input.substr(0, n), true);
input.remove_prefix(n + 3);
continue;
}
if(skipString(input, "DOCTYPE")) {
while(!input.empty() && input.front() != '>') {
if(input.front() == '[') {
int depth = 1;
input.remove_prefix(1);
while(!input.empty() && depth > 0) {
if(input.front() == '[') ++depth;
else if(input.front() == ']') --depth;
input.remove_prefix(1);
}
} else {
input.remove_prefix(1);
}
}
if(!skipDelimiter(input, '>'))
return false;
continue;
}
return false;
}
if(skipDelimiter(input, '/')) {
if(currentElement == nullptr && ignoring == 0)
return false;
if(!readIdentifier(input, buffer))
return false;
if(ignoring == 0) {
auto id = elementid(buffer);
if(id != currentElement->id())
return false;
currentElement = currentElement->parentElement();
} else {
--ignoring;
}
skipOptionalSpaces(input);
if(!skipDelimiter(input, '>'))
return false;
continue;
}
if(!readIdentifier(input, buffer))
return false;
SVGElement* element = nullptr;
if(ignoring > 0) {
++ignoring;
} else {
auto id = elementid(buffer);
if(id == ElementID::Unknown) {
ignoring = 1;
} else {
if(m_rootElement && currentElement == nullptr)
return false;
if(m_rootElement == nullptr) {
if(id != ElementID::Svg)
return false;
m_rootElement = std::make_unique<SVGRootElement>(this);
element = m_rootElement.get();
} else {
auto child = SVGElement::create(this, id);
element = child.get();
currentElement->addChild(std::move(child));
}
}
}
skipOptionalSpaces(input);
while(readIdentifier(input, buffer)) {
skipOptionalSpaces(input);
if(!skipDelimiter(input, '='))
return false;
skipOptionalSpaces(input);
if(input.empty() || !(input.front() == '\"' || input.front() == '\''))
return false;
auto quote = input.front();
input.remove_prefix(1);
auto n = input.find(quote);
if(n == std::string_view::npos)
return false;
auto id = PropertyID::Unknown;
if(element != nullptr)
id = propertyid(buffer);
if(id != PropertyID::Unknown) {
decodeText(input.substr(0, n), buffer);
if(id == PropertyID::Style) {
removeStyleComments(buffer);
parseInlineStyle(buffer, element);
} else {
if(id == PropertyID::Id)
m_rootElement->addElementById(buffer, element);
element->setAttribute(0x1, id, buffer);
}
}
input.remove_prefix(n + 1);
skipOptionalSpaces(input);
}
if(skipDelimiter(input, '>')) {
if(element != nullptr)
currentElement = element;
continue;
}
if(skipDelimiter(input, '/')) {
if(!skipDelimiter(input, '>'))
return false;
if(ignoring > 0)
--ignoring;
continue;
}
return false;
}
if(m_rootElement == nullptr || ignoring > 0 || !input.empty())
return false;
applyStyleSheet(styleSheet);
m_rootElement->build();
return true;
}
void Document::applyStyleSheet(const std::string& content)
{
auto rules = parseStyleSheet(content);
if(!rules.empty()) {
std::sort(rules.begin(), rules.end());
m_rootElement->transverse([&rules](SVGElement* element) {
for(const auto& rule : rules) {
if(rule.match(element)) {
for(const auto& declaration : rule.declarations()) {
element->setAttribute(declaration.specificity, declaration.id, declaration.value);
}
}
}
});
}
}
ElementList Document::querySelectorAll(const std::string& content) const
{
auto selectors = parseQuerySelectors(content);
if(selectors.empty())
return ElementList();
ElementList elements;
m_rootElement->transverse([&](SVGElement* element) {
for(const auto& selector : selectors) {
if(matchSelector(selector, element)) {
elements.push_back(element);
break;
}
}
});
return elements;
}
} // namespace lunasvg
}
@@ -0,0 +1,212 @@
#ifndef LUNASVG_SVGPARSERUTILS_H
#define LUNASVG_SVGPARSERUTILS_H
#include <cmath>
#include <string_view>
#include <limits>
namespace {
namespace lunasvg {
constexpr bool IS_NUM(int cc) { return cc >= '0' && cc <= '9'; }
constexpr bool IS_ALPHA(int cc) { return (cc >= 'a' && cc <= 'z') || (cc >= 'A' && cc <= 'Z'); }
constexpr bool IS_WS(int cc) { return cc == ' ' || cc == '\t' || cc == '\n' || cc == '\r'; }
constexpr void stripLeadingSpaces(std::string_view& input)
{
while(!input.empty() && IS_WS(input.front())) {
input.remove_prefix(1);
}
}
constexpr void stripTrailingSpaces(std::string_view& input)
{
while(!input.empty() && IS_WS(input.back())) {
input.remove_suffix(1);
}
}
constexpr void stripLeadingAndTrailingSpaces(std::string_view& input)
{
stripLeadingSpaces(input);
stripTrailingSpaces(input);
}
constexpr bool skipOptionalSpaces(std::string_view& input)
{
while(!input.empty() && IS_WS(input.front()))
input.remove_prefix(1);
return !input.empty();
}
constexpr bool skipOptionalSpacesOrDelimiter(std::string_view& input, char delimiter)
{
if(!input.empty() && !IS_WS(input.front()) && delimiter != input.front())
return false;
if(skipOptionalSpaces(input)) {
if(delimiter == input.front()) {
input.remove_prefix(1);
skipOptionalSpaces(input);
}
}
return !input.empty();
}
constexpr bool skipOptionalSpacesOrComma(std::string_view& input)
{
return skipOptionalSpacesOrDelimiter(input, ',');
}
constexpr bool skipDelimiterAndOptionalSpaces(std::string_view& input, char delimiter)
{
if(!input.empty() && input.front() == delimiter) {
input.remove_prefix(1);
skipOptionalSpaces(input);
return true;
}
return false;
}
constexpr bool skipDelimiter(std::string_view& input, char delimiter)
{
if(!input.empty() && input.front() == delimiter) {
input.remove_prefix(1);
return true;
}
return false;
}
constexpr bool skipString(std::string_view& input, const std::string_view& value)
{
if(input.size() >= value.size() && value == input.substr(0, value.size())) {
input.remove_prefix(value.size());
return true;
}
return false;
}
constexpr bool isIntegralDigit(char ch, int base)
{
if(IS_NUM(ch))
return ch - '0' < base;
if(IS_ALPHA(ch))
return (ch >= 'a' && ch < 'a' + base - 10) || (ch >= 'A' && ch < 'A' + base - 10);
return false;
}
constexpr int toIntegralDigit(char ch)
{
if(IS_NUM(ch))
return ch - '0';
if(ch >= 'a')
return ch - 'a' + 10;
return ch - 'A' + 10;
}
template<typename T>
inline bool parseInteger(std::string_view& input, T& integer, int base = 10)
{
constexpr bool isSigned = std::numeric_limits<T>::is_signed;
constexpr T intMax = std::numeric_limits<T>::max();
const T maxMultiplier = intMax / static_cast<T>(base);
T value = 0;
bool isNegative = false;
if(!input.empty() && input.front() == '+') {
input.remove_prefix(1);
} else if(!input.empty() && isSigned && input.front() == '-') {
input.remove_prefix(1);
isNegative = true;
}
if(input.empty() || !isIntegralDigit(input.front(), base))
return false;
do {
const int digitValue = toIntegralDigit(input.front());
if(value > maxMultiplier || (value == maxMultiplier && static_cast<T>(digitValue) > (intMax % static_cast<T>(base)) + isNegative))
return false;
value = static_cast<T>(base) * value + static_cast<T>(digitValue);
input.remove_prefix(1);
} while(!input.empty() && isIntegralDigit(input.front(), base));
using SignedType = typename std::make_signed<T>::type;
if(isNegative)
integer = -static_cast<SignedType>(value);
else
integer = value;
return true;
}
template<typename T>
inline bool parseNumber(std::string_view& input, T& number)
{
constexpr T maxValue = std::numeric_limits<T>::max();
T integer = 0;
T fraction = 0;
int exponent = 0;
int sign = 1;
int expsign = 1;
if(!input.empty() && input.front() == '+') {
input.remove_prefix(1);
} else if(!input.empty() && input.front() == '-') {
input.remove_prefix(1);
sign = -1;
}
if(input.empty() || (!IS_NUM(input.front()) && input.front() != '.'))
return false;
if(IS_NUM(input.front())) {
do {
integer = static_cast<T>(10) * integer + (input.front() - '0');
input.remove_prefix(1);
} while(!input.empty() && IS_NUM(input.front()));
}
if(!input.empty() && input.front() == '.') {
input.remove_prefix(1);
if(input.empty() || !IS_NUM(input.front()))
return false;
T divisor = static_cast<T>(1);
do {
fraction = static_cast<T>(10) * fraction + (input.front() - '0');
divisor *= static_cast<T>(10);
input.remove_prefix(1);
} while(!input.empty() && IS_NUM(input.front()));
fraction /= divisor;
}
if(input.size() > 1 && (input[0] == 'e' || input[0] == 'E')
&& (input[1] != 'x' && input[1] != 'm'))
{
input.remove_prefix(1);
if(!input.empty() && input.front() == '+')
input.remove_prefix(1);
else if(!input.empty() && input.front() == '-') {
input.remove_prefix(1);
expsign = -1;
}
if(input.empty() || !IS_NUM(input.front()))
return false;
do {
exponent = 10 * exponent + (input.front() - '0');
input.remove_prefix(1);
} while(!input.empty() && IS_NUM(input.front()));
}
number = sign * (integer + fraction);
if(exponent)
number *= static_cast<T>(std::pow(10.0, expsign * exponent));
return number >= -maxValue && number <= maxValue;
}
} // namespace lunasvg
}
#endif // LUNASVG_SVGPARSERUTILS_H
@@ -0,0 +1,707 @@
#include "svgproperty.h"
#include "svgelement.h"
#include "svgparserutils.h"
#include <cassert>
namespace {
namespace lunasvg {
PropertyID propertyid(const std::string_view& name)
{
static const struct {
std::string_view name;
PropertyID value;
} table[] = {
{"class", PropertyID::Class},
{"clipPathUnits", PropertyID::ClipPathUnits},
{"cx", PropertyID::Cx},
{"cy", PropertyID::Cy},
{"d", PropertyID::D},
{"dx", PropertyID::Dx},
{"dy", PropertyID::Dy},
{"fx", PropertyID::Fx},
{"fy", PropertyID::Fy},
{"gradientTransform", PropertyID::GradientTransform},
{"gradientUnits", PropertyID::GradientUnits},
{"height", PropertyID::Height},
{"href", PropertyID::Href},
{"id", PropertyID::Id},
{"lengthAdjust", PropertyID::LengthAdjust},
{"markerHeight", PropertyID::MarkerHeight},
{"markerUnits", PropertyID::MarkerUnits},
{"markerWidth", PropertyID::MarkerWidth},
{"maskContentUnits", PropertyID::MaskContentUnits},
{"maskUnits", PropertyID::MaskUnits},
{"offset", PropertyID::Offset},
{"orient", PropertyID::Orient},
{"patternContentUnits", PropertyID::PatternContentUnits},
{"patternTransform", PropertyID::PatternTransform},
{"patternUnits", PropertyID::PatternUnits},
{"points", PropertyID::Points},
{"preserveAspectRatio", PropertyID::PreserveAspectRatio},
{"r", PropertyID::R},
{"refX", PropertyID::RefX},
{"refY", PropertyID::RefY},
{"rotate", PropertyID::Rotate},
{"rx", PropertyID::Rx},
{"ry", PropertyID::Ry},
{"spreadMethod", PropertyID::SpreadMethod},
{"style", PropertyID::Style},
{"textLength", PropertyID::TextLength},
{"transform", PropertyID::Transform},
{"viewBox", PropertyID::ViewBox},
{"width", PropertyID::Width},
{"x", PropertyID::X},
{"x1", PropertyID::X1},
{"x2", PropertyID::X2},
{"xlink:href", PropertyID::Href},
{"xml:space", PropertyID::White_Space},
{"y", PropertyID::Y},
{"y1", PropertyID::Y1},
{"y2", PropertyID::Y2}
};
auto it = std::lower_bound(table, std::end(table), name, [](const auto& item, const auto& name) { return item.name < name; });
if(it == std::end(table) || it->name != name)
return csspropertyid(name);
return it->value;
}
PropertyID csspropertyid(const std::string_view& name)
{
static const struct {
std::string_view name;
PropertyID value;
} table[] = {
{"alignment-baseline", PropertyID::Alignment_Baseline},
{"baseline-shift", PropertyID::Baseline_Shift},
{"clip-path", PropertyID::Clip_Path},
{"clip-rule", PropertyID::Clip_Rule},
{"color", PropertyID::Color},
{"direction", PropertyID::Direction},
{"display", PropertyID::Display},
{"dominant-baseline", PropertyID::Dominant_Baseline},
{"fill", PropertyID::Fill},
{"fill-opacity", PropertyID::Fill_Opacity},
{"fill-rule", PropertyID::Fill_Rule},
{"font-family", PropertyID::Font_Family},
{"font-size", PropertyID::Font_Size},
{"font-style", PropertyID::Font_Style},
{"font-weight", PropertyID::Font_Weight},
{"letter-spacing", PropertyID::Letter_Spacing},
{"marker-end", PropertyID::Marker_End},
{"marker-mid", PropertyID::Marker_Mid},
{"marker-start", PropertyID::Marker_Start},
{"mask", PropertyID::Mask},
{"mask-type", PropertyID::Mask_Type},
{"opacity", PropertyID::Opacity},
{"overflow", PropertyID::Overflow},
{"pointer-events", PropertyID::Pointer_Events},
{"stop-color", PropertyID::Stop_Color},
{"stop-opacity", PropertyID::Stop_Opacity},
{"stroke", PropertyID::Stroke},
{"stroke-dasharray", PropertyID::Stroke_Dasharray},
{"stroke-dashoffset", PropertyID::Stroke_Dashoffset},
{"stroke-linecap", PropertyID::Stroke_Linecap},
{"stroke-linejoin", PropertyID::Stroke_Linejoin},
{"stroke-miterlimit", PropertyID::Stroke_Miterlimit},
{"stroke-opacity", PropertyID::Stroke_Opacity},
{"stroke-width", PropertyID::Stroke_Width},
{"text-anchor", PropertyID::Text_Anchor},
{"text-orientation", PropertyID::Text_Orientation},
{"visibility", PropertyID::Visibility},
{"white-space", PropertyID::White_Space},
{"word-spacing", PropertyID::Word_Spacing},
{"writing-mode", PropertyID::Writing_Mode}
};
auto it = std::lower_bound(table, std::end(table), name, [](const auto& item, const auto& name) { return item.name < name; });
if(it == std::end(table) || it->name != name)
return PropertyID::Unknown;
return it->value;
}
SVGProperty::SVGProperty(PropertyID id)
: m_id(id)
{
}
bool SVGString::parse(std::string_view input)
{
stripLeadingAndTrailingSpaces(input);
m_value.assign(input);
return true;
}
template<>
bool SVGEnumeration<SpreadMethod>::parse(std::string_view input)
{
static const SVGEnumerationEntry<SpreadMethod> entries[] = {
{SpreadMethod::Pad, "pad"},
{SpreadMethod::Reflect, "reflect"},
{SpreadMethod::Repeat, "repeat"}
};
return parseEnum(input, entries);
}
template<>
bool SVGEnumeration<Units>::parse(std::string_view input)
{
static const SVGEnumerationEntry<Units> entries[] = {
{Units::UserSpaceOnUse, "userSpaceOnUse"},
{Units::ObjectBoundingBox, "objectBoundingBox"}
};
return parseEnum(input, entries);
}
template<>
bool SVGEnumeration<MarkerUnits>::parse(std::string_view input)
{
static const SVGEnumerationEntry<MarkerUnits> entries[] = {
{MarkerUnits::StrokeWidth, "strokeWidth"},
{MarkerUnits::UserSpaceOnUse, "userSpaceOnUse"}
};
return parseEnum(input, entries);
}
template<>
bool SVGEnumeration<LengthAdjust>::parse(std::string_view input)
{
static const SVGEnumerationEntry<LengthAdjust> entries[] = {
{LengthAdjust::Spacing, "spacing"},
{LengthAdjust::SpacingAndGlyphs, "spacingAndGlyphs"}
};
return parseEnum(input, entries);
}
template<typename Enum>
template<unsigned int N>
bool SVGEnumeration<Enum>::parseEnum(std::string_view input, const SVGEnumerationEntry<Enum>(&entries)[N])
{
stripLeadingAndTrailingSpaces(input);
for(const auto& entry : entries) {
if(input == entry.second) {
m_value = entry.first;
return true;
}
}
return false;
}
bool SVGAngle::parse(std::string_view input)
{
stripLeadingAndTrailingSpaces(input);
if(input == "auto") {
m_value = 0.f;
m_orientType = OrientType::Auto;
return true;
}
if(input == "auto-start-reverse") {
m_value = 0.f;
m_orientType = OrientType::AutoStartReverse;
return true;
}
float value = 0.f;
if(!parseNumber(input, value))
return false;
if(!input.empty()) {
if(input == "rad")
value *= 180.f / JUCE_PLUTOVG_PI;
else if(input == "grad")
value *= 360.f / 400.f;
else if(input == "turn")
value *= 360.f;
else if(input != "deg") {
return false;
}
}
m_value = value;
m_orientType = OrientType::Angle;
return true;
}
bool Length::parse(std::string_view input, LengthNegativeMode mode)
{
float value = 0.f;
stripLeadingAndTrailingSpaces(input);
if(!parseNumber(input, value))
return false;
if(value < 0.f && mode == LengthNegativeMode::Forbid)
return false;
if(input.empty()) {
m_value = value;
m_units = LengthUnits::None;
return true;
}
constexpr auto dpi = 96.f;
switch(input.front()) {
case '%':
m_value = value;
m_units = LengthUnits::Percent;
input.remove_prefix(1);
break;
case 'p':
input.remove_prefix(1);
if(input.empty())
return false;
else if(input.front() == 'x')
m_value = value;
else if(input.front() == 'c')
m_value = value * dpi / 6.f;
else if(input.front() == 't')
m_value = value * dpi / 72.f;
else
return false;
m_units = LengthUnits::Px;
input.remove_prefix(1);
break;
case 'i':
input.remove_prefix(1);
if(input.empty())
return false;
else if(input.front() == 'n')
m_value = value * dpi;
else
return false;
m_units = LengthUnits::Px;
input.remove_prefix(1);
break;
case 'c':
input.remove_prefix(1);
if(input.empty())
return false;
else if(input.front() == 'm')
m_value = value * dpi / 2.54f;
else
return false;
m_units = LengthUnits::Px;
input.remove_prefix(1);
break;
case 'm':
input.remove_prefix(1);
if(input.empty())
return false;
else if(input.front() == 'm')
m_value = value * dpi / 25.4f;
else
return false;
m_units = LengthUnits::Px;
input.remove_prefix(1);
break;
case 'e':
input.remove_prefix(1);
if(input.empty())
return false;
else if(input.front() == 'm')
m_units = LengthUnits::Em;
else if(input.front() == 'x')
m_units = LengthUnits::Ex;
else
return false;
m_value = value;
input.remove_prefix(1);
break;
default:
return false;
}
return input.empty();
}
float LengthContext::valueForLength(const Length& length, LengthDirection direction) const
{
if(length.units() == LengthUnits::Percent) {
if(m_units == Units::UserSpaceOnUse)
return length.value() * viewportDimension(direction) / 100.f;
return length.value() / 100.f;
}
if(length.units() == LengthUnits::Ex)
return length.value() * m_element->font_size() / 2.f;
if(length.units() == LengthUnits::Em)
return length.value() * m_element->font_size();
return length.value();
}
float LengthContext::viewportDimension(LengthDirection direction) const
{
auto viewportSize = m_element->currentViewportSize();
switch(direction) {
case LengthDirection::Horizontal:
return viewportSize.w;
case LengthDirection::Vertical:
return viewportSize.h;
default:
return std::sqrt(viewportSize.w * viewportSize.w + viewportSize.h * viewportSize.h) / JUCE_PLUTOVG_SQRT2;
}
}
bool SVGLength::parse(std::string_view input)
{
return m_value.parse(input, m_negativeMode);
}
bool SVGLengthList::parse(std::string_view input)
{
m_values.clear();
while(!input.empty()) {
size_t count = 0;
while(count < input.length() && input[count] != ',' && !IS_WS(input[count]))
++count;
if(count == 0)
break;
Length value(0, LengthUnits::None);
if(!value.parse(input.substr(0, count), m_negativeMode))
return false;
input.remove_prefix(count);
skipOptionalSpacesOrComma(input);
m_values.push_back(value);
}
return true;
}
bool SVGNumber::parse(std::string_view input)
{
float value = 0.f;
stripLeadingAndTrailingSpaces(input);
if(!parseNumber(input, value))
return false;
if(!input.empty())
return false;
m_value = value;
return true;
}
bool SVGNumberPercentage::parse(std::string_view input)
{
float value = 0.f;
stripLeadingAndTrailingSpaces(input);
if(!parseNumber(input, value))
return false;
if(!input.empty() && input.front() == '%') {
value /= 100.f;
input.remove_prefix(1);
}
if(!input.empty())
return false;
m_value = std::clamp(value, 0.f, 1.f);
return true;
}
bool SVGNumberList::parse(std::string_view input)
{
m_values.clear();
stripLeadingSpaces(input);
while(!input.empty()) {
float value = 0.f;
if(!parseNumber(input, value))
return false;
skipOptionalSpacesOrComma(input);
m_values.push_back(value);
}
return true;
}
bool SVGPath::parse(std::string_view input)
{
return m_value.parse(input.data(), input.length());
}
bool SVGPoint::parse(std::string_view input)
{
Point value;
stripLeadingAndTrailingSpaces(input);
if(!parseNumber(input, value.x)
|| !skipOptionalSpaces(input)
|| !parseNumber(input, value.y)
|| !input.empty()) {
return false;
}
m_value = value;
return true;
}
bool SVGPointList::parse(std::string_view input)
{
m_values.clear();
stripLeadingSpaces(input);
while(!input.empty()) {
Point value;
if(!parseNumber(input, value.x)
|| !skipOptionalSpacesOrComma(input)
|| !parseNumber(input, value.y)) {
return false;
}
m_values.push_back(value);
skipOptionalSpacesOrComma(input);
}
return true;
}
bool SVGRect::parse(std::string_view input)
{
Rect value;
stripLeadingAndTrailingSpaces(input);
if(!parseNumber(input, value.x)
|| !skipOptionalSpacesOrComma(input)
|| !parseNumber(input, value.y)
|| !skipOptionalSpacesOrComma(input)
|| !parseNumber(input, value.w)
|| !skipOptionalSpacesOrComma(input)
|| !parseNumber(input, value.h)
|| !input.empty()) {
return false;
}
if(value.w < 0.f || value.h < 0.f)
return false;
m_value = value;
return true;
}
bool SVGTransform::parse(std::string_view input)
{
return m_value.parse(input.data(), input.length());
}
bool SVGPreserveAspectRatio::parse(std::string_view input)
{
auto alignType = AlignType::xMidYMid;
stripLeadingSpaces(input);
if(skipString(input, "none"))
alignType = AlignType::None;
else if(skipString(input, "xMinYMin"))
alignType = AlignType::xMinYMin;
else if(skipString(input, "xMidYMin"))
alignType = AlignType::xMidYMin;
else if(skipString(input, "xMaxYMin"))
alignType = AlignType::xMaxYMin;
else if(skipString(input, "xMinYMid"))
alignType = AlignType::xMinYMid;
else if(skipString(input, "xMidYMid"))
alignType = AlignType::xMidYMid;
else if(skipString(input, "xMaxYMid"))
alignType = AlignType::xMaxYMid;
else if(skipString(input, "xMinYMax"))
alignType = AlignType::xMinYMax;
else if(skipString(input, "xMidYMax"))
alignType = AlignType::xMidYMax;
else if(skipString(input, "xMaxYMax"))
alignType = AlignType::xMaxYMax;
else {
return false;
}
auto meetOrSlice = MeetOrSlice::Meet;
skipOptionalSpaces(input);
if(skipString(input, "meet")) {
meetOrSlice = MeetOrSlice::Meet;
} else if(skipString(input, "slice")) {
meetOrSlice = MeetOrSlice::Slice;
}
if(alignType == AlignType::None)
meetOrSlice = MeetOrSlice::Meet;
skipOptionalSpaces(input);
if(!input.empty())
return false;
m_alignType = alignType;
m_meetOrSlice = meetOrSlice;
return true;
}
Rect SVGPreserveAspectRatio::getClipRect(const Rect& viewBoxRect, const Size& viewportSize) const
{
assert(!viewBoxRect.isEmpty() && !viewportSize.isEmpty());
auto xScale = viewportSize.w / viewBoxRect.w;
auto yScale = viewportSize.h / viewBoxRect.h;
if(m_alignType == AlignType::None) {
return Rect(viewBoxRect.x, viewBoxRect.y, viewportSize.w / xScale, viewportSize.h / yScale);
}
auto scale = (m_meetOrSlice == MeetOrSlice::Meet) ? std::min(xScale, yScale) : std::max(xScale, yScale);
auto xOffset = -viewBoxRect.x * scale;
auto yOffset = -viewBoxRect.y * scale;
auto viewWidth = viewBoxRect.w * scale;
auto viewHeight = viewBoxRect.h * scale;
switch(m_alignType) {
case AlignType::xMidYMin:
case AlignType::xMidYMid:
case AlignType::xMidYMax:
xOffset += (viewportSize.w - viewWidth) * 0.5f;
break;
case AlignType::xMaxYMin:
case AlignType::xMaxYMid:
case AlignType::xMaxYMax:
xOffset += (viewportSize.w - viewWidth);
break;
default:
break;
}
switch(m_alignType) {
case AlignType::xMinYMid:
case AlignType::xMidYMid:
case AlignType::xMaxYMid:
yOffset += (viewportSize.h - viewHeight) * 0.5f;
break;
case AlignType::xMinYMax:
case AlignType::xMidYMax:
case AlignType::xMaxYMax:
yOffset += (viewportSize.h - viewHeight);
break;
default:
break;
}
return Rect(-xOffset / scale, -yOffset / scale, viewportSize.w / scale, viewportSize.h / scale);
}
Transform SVGPreserveAspectRatio::getTransform(const Rect& viewBoxRect, const Size& viewportSize) const
{
assert(!viewBoxRect.isEmpty() && !viewportSize.isEmpty());
auto xScale = viewportSize.w / viewBoxRect.w;
auto yScale = viewportSize.h / viewBoxRect.h;
if(m_alignType == AlignType::None) {
return Transform(xScale, 0, 0, yScale, -viewBoxRect.x * xScale, -viewBoxRect.y * yScale);
}
auto scale = (m_meetOrSlice == MeetOrSlice::Meet) ? std::min(xScale, yScale) : std::max(xScale, yScale);
auto xOffset = -viewBoxRect.x * scale;
auto yOffset = -viewBoxRect.y * scale;
auto viewWidth = viewBoxRect.w * scale;
auto viewHeight = viewBoxRect.h * scale;
switch(m_alignType) {
case AlignType::xMidYMin:
case AlignType::xMidYMid:
case AlignType::xMidYMax:
xOffset += (viewportSize.w - viewWidth) * 0.5f;
break;
case AlignType::xMaxYMin:
case AlignType::xMaxYMid:
case AlignType::xMaxYMax:
xOffset += (viewportSize.w - viewWidth);
break;
default:
break;
}
switch(m_alignType) {
case AlignType::xMinYMid:
case AlignType::xMidYMid:
case AlignType::xMaxYMid:
yOffset += (viewportSize.h - viewHeight) * 0.5f;
break;
case AlignType::xMinYMax:
case AlignType::xMidYMax:
case AlignType::xMaxYMax:
yOffset += (viewportSize.h - viewHeight);
break;
default:
break;
}
return Transform(scale, 0, 0, scale, xOffset, yOffset);
}
void SVGPreserveAspectRatio::transformRect(Rect& dstRect, Rect& srcRect) const
{
if(m_alignType == AlignType::None)
return;
auto viewSize = dstRect.size();
auto imageSize = srcRect.size();
if(m_meetOrSlice == MeetOrSlice::Meet) {
auto scale = imageSize.h / imageSize.w;
if(viewSize.h > viewSize.w * scale) {
dstRect.h = viewSize.w * scale;
switch(m_alignType) {
case AlignType::xMinYMid:
case AlignType::xMidYMid:
case AlignType::xMaxYMid:
dstRect.y += (viewSize.h - dstRect.h) * 0.5f;
break;
case AlignType::xMinYMax:
case AlignType::xMidYMax:
case AlignType::xMaxYMax:
dstRect.y += viewSize.h - dstRect.h;
break;
default:
break;
}
}
if(viewSize.w > viewSize.h / scale) {
dstRect.w = viewSize.h / scale;
switch(m_alignType) {
case AlignType::xMidYMin:
case AlignType::xMidYMid:
case AlignType::xMidYMax:
dstRect.x += (viewSize.w - dstRect.w) * 0.5f;
break;
case AlignType::xMaxYMin:
case AlignType::xMaxYMid:
case AlignType::xMaxYMax:
dstRect.x += viewSize.w - dstRect.w;
break;
default:
break;
}
}
} else if(m_meetOrSlice == MeetOrSlice::Slice) {
auto scale = imageSize.h / imageSize.w;
if(viewSize.h < viewSize.w * scale) {
srcRect.h = viewSize.h * (imageSize.w / viewSize.w);
switch(m_alignType) {
case AlignType::xMinYMid:
case AlignType::xMidYMid:
case AlignType::xMaxYMid:
srcRect.y += (imageSize.h - srcRect.h) * 0.5f;
break;
case AlignType::xMinYMax:
case AlignType::xMidYMax:
case AlignType::xMaxYMax:
srcRect.y += imageSize.h - srcRect.h;
break;
default:
break;
}
}
if(viewSize.w < viewSize.h / scale) {
srcRect.w = viewSize.w * (imageSize.h / viewSize.h);
switch(m_alignType) {
case AlignType::xMidYMin:
case AlignType::xMidYMid:
case AlignType::xMidYMax:
srcRect.x += (imageSize.w - srcRect.w) * 0.5f;
break;
case AlignType::xMaxYMin:
case AlignType::xMaxYMid:
case AlignType::xMaxYMax:
srcRect.x += imageSize.w - srcRect.w;
break;
default:
break;
}
}
}
}
} // namespace lunasvg
}
@@ -0,0 +1,572 @@
#ifndef LUNASVG_SVGPROPERTY_H
#define LUNASVG_SVGPROPERTY_H
#include "graphics.h"
#include <string>
namespace {
namespace lunasvg {
enum class PropertyID : uint8_t {
Unknown = 0,
Alignment_Baseline,
Baseline_Shift,
Class,
Clip_Path,
Clip_Rule,
ClipPathUnits,
Color,
Cx,
Cy,
D,
Direction,
Display,
Dominant_Baseline,
Dx,
Dy,
Fill,
Fill_Opacity,
Fill_Rule,
Font_Family,
Font_Size,
Font_Style,
Font_Weight,
Fx,
Fy,
GradientTransform,
GradientUnits,
Height,
Href,
Id,
LengthAdjust,
Letter_Spacing,
Marker_End,
Marker_Mid,
Marker_Start,
MarkerHeight,
MarkerUnits,
MarkerWidth,
Mask,
Mask_Type,
MaskContentUnits,
MaskUnits,
Offset,
Opacity,
Orient,
Overflow,
PatternContentUnits,
PatternTransform,
PatternUnits,
Pointer_Events,
Points,
PreserveAspectRatio,
R,
RefX,
RefY,
Rotate,
Rx,
Ry,
SpreadMethod,
Stop_Color,
Stop_Opacity,
Stroke,
Stroke_Dasharray,
Stroke_Dashoffset,
Stroke_Linecap,
Stroke_Linejoin,
Stroke_Miterlimit,
Stroke_Opacity,
Stroke_Width,
Style,
Text_Anchor,
Text_Orientation,
TextLength,
Transform,
ViewBox,
Visibility,
White_Space,
Width,
Word_Spacing,
Writing_Mode,
X,
X1,
X2,
Y,
Y1,
Y2
};
PropertyID propertyid(const std::string_view& name);
PropertyID csspropertyid(const std::string_view& name);
class SVGElement;
class SVGProperty {
public:
SVGProperty(PropertyID id);
virtual ~SVGProperty() = default;
PropertyID id() const { return m_id; }
virtual bool parse(std::string_view input) = 0;
private:
SVGProperty(const SVGProperty&) = delete;
SVGProperty& operator=(const SVGProperty&) = delete;
PropertyID m_id;
};
class SVGString final : public SVGProperty {
public:
explicit SVGString(PropertyID id)
: SVGProperty(id)
{}
const std::string& value() const { return m_value; }
bool parse(std::string_view input) final;
private:
std::string m_value;
};
class Paint {
public:
Paint() = default;
explicit Paint(const Color& color) : m_color(color) {}
Paint(const std::string& id, const Color& color)
: m_id(id), m_color(color)
{}
const Color& color() const { return m_color; }
const std::string& id() const { return m_id; }
bool isNone() const { return m_id.empty() && !m_color.isVisible(); }
private:
std::string m_id;
Color m_color = Color::Transparent;
};
enum class Display : uint8_t {
Inline,
None
};
enum class Visibility : uint8_t {
Visible,
Hidden,
Collapse
};
enum class Overflow : uint8_t {
Visible,
Hidden
};
enum class PointerEvents : uint8_t {
None,
Auto,
Stroke,
Fill,
Painted,
Visible,
VisibleStroke,
VisibleFill,
VisiblePainted,
BoundingBox,
All
};
enum class FontStyle : uint8_t {
Normal,
Italic
};
enum class FontWeight : uint8_t {
Normal,
Bold
};
enum class AlignmentBaseline : uint8_t {
Auto,
Baseline,
BeforeEdge,
TextBeforeEdge,
Middle,
Central,
AfterEdge,
TextAfterEdge,
Ideographic,
Alphabetic,
Hanging,
Mathematical
};
enum class DominantBaseline : uint8_t {
Auto,
UseScript,
NoChange,
ResetSize,
Ideographic,
Alphabetic,
Hanging,
Mathematical,
Central,
Middle,
TextAfterEdge,
TextBeforeEdge
};
enum class TextAnchor : uint8_t {
Start,
Middle,
End
};
enum class WhiteSpace : uint8_t {
Default,
Preserve
};
enum class WritingMode : uint8_t {
Horizontal,
Vertical
};
enum class TextOrientation : uint8_t {
Mixed,
Upright
};
enum class Direction : uint8_t {
Ltr,
Rtl
};
enum class MaskType : uint8_t {
Luminance,
Alpha
};
enum class Units : uint8_t {
UserSpaceOnUse,
ObjectBoundingBox
};
enum class MarkerUnits : uint8_t {
StrokeWidth,
UserSpaceOnUse
};
enum class LengthAdjust : uint8_t {
Spacing,
SpacingAndGlyphs
};
template<typename Enum>
using SVGEnumerationEntry = std::pair<Enum, std::string_view>;
template<typename Enum>
class SVGEnumeration final : public SVGProperty {
public:
explicit SVGEnumeration(PropertyID id, Enum value)
: SVGProperty(id)
, m_value(value)
{}
Enum value() const { return m_value; }
bool parse(std::string_view input) final;
private:
template<unsigned int N>
bool parseEnum(std::string_view input, const SVGEnumerationEntry<Enum>(&entries)[N]);
Enum m_value;
};
class SVGAngle final : public SVGProperty {
public:
enum class OrientType {
Auto,
AutoStartReverse,
Angle
};
explicit SVGAngle(PropertyID id)
: SVGProperty(id)
{}
float value() const { return m_value; }
OrientType orientType() const { return m_orientType; }
bool parse(std::string_view input) final;
private:
float m_value = 0;
OrientType m_orientType = OrientType::Angle;
};
enum class LengthUnits : uint8_t {
None,
Percent,
Px,
Em,
Ex
};
enum class LengthDirection : uint8_t {
Horizontal,
Vertical,
Diagonal
};
enum class LengthNegativeMode : uint8_t {
Allow,
Forbid
};
class Length {
public:
Length() = default;
Length(float value, LengthUnits units)
: m_value(value), m_units(units)
{}
float value() const { return m_value; }
LengthUnits units() const { return m_units; }
bool parse(std::string_view input, LengthNegativeMode mode);
private:
float m_value = 0.f;
LengthUnits m_units = LengthUnits::None;
};
class SVGLength final : public SVGProperty {
public:
SVGLength(PropertyID id, LengthDirection direction, LengthNegativeMode negativeMode, float value = 0, LengthUnits units = LengthUnits::None)
: SVGProperty(id)
, m_direction(direction)
, m_negativeMode(negativeMode)
, m_value(value, units)
{}
bool isPercent() const { return m_value.units() == LengthUnits::Percent; }
LengthDirection direction() const { return m_direction; }
LengthNegativeMode negativeMode() const { return m_negativeMode; }
const Length& value() const { return m_value; }
bool parse(std::string_view input) final;
private:
const LengthDirection m_direction;
const LengthNegativeMode m_negativeMode;
Length m_value;
};
class LengthContext {
public:
LengthContext(const SVGElement* element, Units units = Units::UserSpaceOnUse)
: m_element(element), m_units(units)
{}
float valueForLength(const Length& length, LengthDirection direction) const;
float valueForLength(const SVGLength& length) const { return valueForLength(length.value(), length.direction()); }
private:
float viewportDimension(LengthDirection direction) const;
const SVGElement* m_element;
const Units m_units;
};
using LengthList = std::vector<Length>;
class SVGLengthList final : public SVGProperty {
public:
SVGLengthList(PropertyID id, LengthDirection direction, LengthNegativeMode negativeMode)
: SVGProperty(id)
, m_direction(direction)
, m_negativeMode(negativeMode)
{}
LengthDirection direction() const { return m_direction; }
LengthNegativeMode negativeMode() const { return m_negativeMode; }
const LengthList& values() const { return m_values; }
bool parse(std::string_view input) final;
private:
const LengthDirection m_direction;
const LengthNegativeMode m_negativeMode;
LengthList m_values;
};
class BaselineShift {
public:
enum class Type {
Baseline,
Sub,
Super,
Length
};
BaselineShift() = default;
BaselineShift(Type type) : m_type(type) {}
BaselineShift(const Length& length) : m_type(Type::Length), m_length(length) {}
Type type() const { return m_type; }
const Length& length() const { return m_length; }
private:
Type m_type{Type::Baseline};
Length m_length;
};
class SVGNumber : public SVGProperty {
public:
SVGNumber(PropertyID id, float value)
: SVGProperty(id)
, m_value(value)
{}
float value() const { return m_value; }
bool parse(std::string_view input) override;
private:
float m_value;
};
class SVGNumberPercentage final : public SVGProperty {
public:
SVGNumberPercentage(PropertyID id, float value)
: SVGProperty(id)
, m_value(value)
{}
float value() const { return m_value; }
bool parse(std::string_view input) final;
private:
float m_value;
};
using NumberList = std::vector<float>;
class SVGNumberList final : public SVGProperty {
public:
explicit SVGNumberList(PropertyID id)
: SVGProperty(id)
{}
const NumberList& values() const { return m_values; }
bool parse(std::string_view input) final;
private:
NumberList m_values;
};
class SVGPath final : public SVGProperty {
public:
explicit SVGPath(PropertyID id)
: SVGProperty(id)
{}
const Path& value() const { return m_value; }
bool parse(std::string_view input) final;
private:
Path m_value;
};
class SVGPoint final : public SVGProperty {
public:
explicit SVGPoint(PropertyID id)
: SVGProperty(id)
{}
const Point& value() const { return m_value; }
bool parse(std::string_view input) final;
private:
Point m_value;
};
using PointList = std::vector<Point>;
class SVGPointList final : public SVGProperty {
public:
explicit SVGPointList(PropertyID id)
: SVGProperty(id)
{}
const PointList& values() const { return m_values; }
bool parse(std::string_view input) final;
private:
PointList m_values;
};
class SVGRect final : public SVGProperty {
public:
explicit SVGRect(PropertyID id)
: SVGProperty(id)
, m_value(Rect::Invalid)
{}
const Rect& value() const { return m_value; }
bool parse(std::string_view input) final;
private:
Rect m_value;
};
class SVGTransform final : public SVGProperty {
public:
explicit SVGTransform(PropertyID id)
: SVGProperty(id)
{}
const Transform& value() const { return m_value; }
bool parse(std::string_view input) final;
private:
Transform m_value;
};
class SVGPreserveAspectRatio final : public SVGProperty {
public:
enum class AlignType {
None,
xMinYMin,
xMidYMin,
xMaxYMin,
xMinYMid,
xMidYMid,
xMaxYMid,
xMinYMax,
xMidYMax,
xMaxYMax
};
enum class MeetOrSlice {
Meet,
Slice
};
explicit SVGPreserveAspectRatio(PropertyID id)
: SVGProperty(id)
{}
AlignType alignType() const { return m_alignType; }
MeetOrSlice meetOrSlice() const { return m_meetOrSlice; }
bool parse(std::string_view input) final;
Rect getClipRect(const Rect& viewBoxRect, const Size& viewportSize) const;
Transform getTransform(const Rect& viewBoxRect, const Size& viewportSize) const;
void transformRect(Rect& dstRect, Rect& srcRect) const;
private:
AlignType m_alignType = AlignType::xMidYMid;
MeetOrSlice m_meetOrSlice = MeetOrSlice::Meet;
};
} // namespace lunasvg
}
#endif // LUNASVG_SVGPROPERTY_H
@@ -0,0 +1,63 @@
#include "svgrenderstate.h"
namespace {
namespace lunasvg {
SVGBlendInfo::SVGBlendInfo(const SVGElement* element)
: m_clipper(element->clipper())
, m_masker(element->masker())
, m_opacity(element->opacity())
{
}
bool SVGBlendInfo::requiresCompositing(SVGRenderMode mode) const
{
return (m_clipper && m_clipper->requiresMasking()) || (mode == SVGRenderMode::Painting && (m_masker || m_opacity < 1.f));
}
bool SVGRenderState::hasCycleReference(const SVGElement* element) const
{
auto current = this;
do {
if(element == current->element())
return true;
current = current->parent();
} while(current);
return false;
}
void SVGRenderState::beginGroup(const SVGBlendInfo& blendInfo)
{
auto requiresCompositing = blendInfo.requiresCompositing(m_mode);
if(requiresCompositing) {
auto boundingBox = m_currentTransform.mapRect(m_element->paintBoundingBox());
boundingBox.intersect(m_canvas->extents());
m_canvas = m_canvas->create(boundingBox);
} else {
m_canvas->save();
}
if(!requiresCompositing && blendInfo.clipper()) {
blendInfo.clipper()->applyClipPath(*this);
}
}
void SVGRenderState::endGroup(const SVGBlendInfo& blendInfo)
{
if(m_canvas == m_parent->canvas()) {
m_canvas->restore();
return;
}
auto opacity = m_mode == SVGRenderMode::Clipping ? 1.f : blendInfo.opacity();
if(blendInfo.clipper())
blendInfo.clipper()->applyClipMask(*this);
if(m_mode == SVGRenderMode::Painting && blendInfo.masker()) {
blendInfo.masker()->applyMask(*this);
}
m_parent->m_canvas->blendCanvas(*m_canvas, BlendMode::Src_Over, opacity);
}
} // namespace lunasvg
}
@@ -0,0 +1,71 @@
#ifndef LUNASVG_SVGRENDERSTATE_H
#define LUNASVG_SVGRENDERSTATE_H
#include "svgelement.h"
namespace {
namespace lunasvg {
enum class SVGRenderMode {
Painting,
Clipping
};
class SVGBlendInfo {
public:
explicit SVGBlendInfo(const SVGElement* element);
SVGBlendInfo(const SVGClipPathElement* clipper, const SVGMaskElement* masker, float opacity)
: m_clipper(clipper), m_masker(masker), m_opacity(opacity)
{}
bool requiresCompositing(SVGRenderMode mode) const;
const SVGClipPathElement* clipper() const { return m_clipper; }
const SVGMaskElement* masker() const { return m_masker; }
float opacity() const { return m_opacity; }
private:
const SVGClipPathElement* m_clipper;
const SVGMaskElement* m_masker;
const float m_opacity;
};
class SVGRenderState {
public:
SVGRenderState(const SVGElement* element, const SVGRenderState& parent, const Transform& localTransform)
: m_element(element), m_parent(&parent), m_currentTransform(parent.currentTransform() * localTransform)
, m_mode(parent.mode()), m_canvas(parent.canvas())
{}
SVGRenderState(const SVGElement* element, const SVGRenderState* parent, const Transform& currentTransform, SVGRenderMode mode, std::shared_ptr<Canvas> canvas)
: m_element(element), m_parent(parent), m_currentTransform(currentTransform), m_mode(mode), m_canvas(std::move(canvas))
{}
Canvas& operator*() const { return *m_canvas; }
Canvas* operator->() const { return &*m_canvas; }
const SVGElement* element() const { return m_element; }
const SVGRenderState* parent() const { return m_parent; }
const Transform& currentTransform() const { return m_currentTransform; }
const SVGRenderMode mode() const { return m_mode; }
const std::shared_ptr<Canvas>& canvas() const { return m_canvas; }
Rect fillBoundingBox() const { return m_element->fillBoundingBox(); }
Rect paintBoundingBox() const { return m_element->paintBoundingBox(); }
bool hasCycleReference(const SVGElement* element) const;
void beginGroup(const SVGBlendInfo& blendInfo);
void endGroup(const SVGBlendInfo& blendInfo);
private:
const SVGElement* m_element;
const SVGRenderState* m_parent;
const Transform m_currentTransform;
const SVGRenderMode m_mode;
std::shared_ptr<Canvas> m_canvas;
};
} // namespace lunasvg
}
#endif // LUNASVG_SVGRENDERSTATE_H
@@ -0,0 +1,581 @@
#include "svgtextelement.h"
#include "svglayoutstate.h"
#include "svgrenderstate.h"
#include <cassert>
namespace {
namespace lunasvg {
inline const SVGTextNode* toSVGTextNode(const SVGNode* node)
{
assert(node && node->isTextNode());
return static_cast<const SVGTextNode*>(node);
}
inline const SVGTextPositioningElement* toSVGTextPositioningElement(const SVGNode* node)
{
assert(node && node->isTextPositioningElement());
return static_cast<const SVGTextPositioningElement*>(node);
}
static AlignmentBaseline resolveDominantBaseline(const SVGTextPositioningElement* element)
{
switch(element->dominant_baseline()) {
case DominantBaseline::Auto:
if(element->isVerticalWritingMode())
return AlignmentBaseline::Central;
return AlignmentBaseline::Alphabetic;
case DominantBaseline::UseScript:
case DominantBaseline::NoChange:
case DominantBaseline::ResetSize:
return AlignmentBaseline::Auto;
case DominantBaseline::Ideographic:
return AlignmentBaseline::Ideographic;
case DominantBaseline::Alphabetic:
return AlignmentBaseline::Alphabetic;
case DominantBaseline::Hanging:
return AlignmentBaseline::Hanging;
case DominantBaseline::Mathematical:
return AlignmentBaseline::Mathematical;
case DominantBaseline::Central:
return AlignmentBaseline::Central;
case DominantBaseline::Middle:
return AlignmentBaseline::Middle;
case DominantBaseline::TextAfterEdge:
return AlignmentBaseline::TextAfterEdge;
case DominantBaseline::TextBeforeEdge:
return AlignmentBaseline::TextBeforeEdge;
default:
assert(false);
}
return AlignmentBaseline::Auto;
}
static float calculateBaselineOffset(const SVGTextPositioningElement* element)
{
auto offset = element->baseline_offset();
auto parent = element->parentElement();
while(parent->isTextPositioningElement()) {
offset += toSVGTextPositioningElement(parent)->baseline_offset();
parent = parent->parentElement();
}
auto baseline = element->alignment_baseline();
if(baseline == AlignmentBaseline::Auto || baseline == AlignmentBaseline::Baseline) {
baseline = resolveDominantBaseline(element);
}
const auto& font = element->font();
switch(baseline) {
case AlignmentBaseline::BeforeEdge:
case AlignmentBaseline::TextBeforeEdge:
offset -= font.ascent();
break;
case AlignmentBaseline::Middle:
offset -= font.xHeight() / 2.f;
break;
case AlignmentBaseline::Central:
offset -= (font.ascent() + font.descent()) / 2.f;
break;
case AlignmentBaseline::AfterEdge:
case AlignmentBaseline::TextAfterEdge:
case AlignmentBaseline::Ideographic:
offset -= font.descent();
break;
case AlignmentBaseline::Hanging:
offset -= font.ascent() * 8.f / 10.f;
break;
case AlignmentBaseline::Mathematical:
offset -= font.ascent() / 2.f;
break;
default:
break;
}
return offset;
}
static bool needsTextAnchorAdjustment(const SVGTextPositioningElement* element)
{
auto direction = element->direction();
switch(element->text_anchor()) {
case TextAnchor::Start:
return direction == Direction::Rtl;
case TextAnchor::Middle:
return true;
case TextAnchor::End:
return direction == Direction::Ltr;
default:
assert(false);
}
return false;
}
static float calculateTextAnchorOffset(const SVGTextPositioningElement* element, float width)
{
auto direction = element->direction();
switch(element->text_anchor()) {
case TextAnchor::Start:
if(direction == Direction::Ltr)
return 0.f;
return -width;
case TextAnchor::Middle:
return -width / 2.f;
case TextAnchor::End:
if(direction == Direction::Ltr)
return -width;
return 0.f;
default:
assert(false);
}
return 0.f;
}
using SVGTextFragmentIterator = SVGTextFragmentList::iterator;
static float calculateTextChunkLength(SVGTextFragmentIterator begin, SVGTextFragmentIterator end, bool isVerticalText)
{
float chunkLength = 0;
const SVGTextFragment* lastFragment = nullptr;
for(auto it = begin; it != end; ++it) {
const SVGTextFragment& fragment = *it;
chunkLength += isVerticalText ? fragment.height : fragment.width;
if(!lastFragment) {
lastFragment = &fragment;
continue;
}
if(isVerticalText) {
chunkLength += fragment.y - (lastFragment->y + lastFragment->height);
} else {
chunkLength += fragment.x - (lastFragment->x + lastFragment->width);
}
lastFragment = &fragment;
}
return chunkLength;
}
static void handleTextChunk(SVGTextFragmentIterator begin, SVGTextFragmentIterator end)
{
const SVGTextFragment& firstFragment = *begin;
const auto isVerticalText = firstFragment.element->isVerticalWritingMode();
if(firstFragment.element->hasAttribute(PropertyID::TextLength)) {
LengthContext lengthContext(firstFragment.element);
auto textLength = lengthContext.valueForLength(firstFragment.element->textLength());
auto chunkLength = calculateTextChunkLength(begin, end, isVerticalText);
if(textLength > 0.f && chunkLength > 0.f) {
size_t numCharacters = 0;
for(auto it = begin; it != end; ++it) {
const SVGTextFragment& fragment = *it;
numCharacters += fragment.length;
}
if(firstFragment.element->lengthAdjust() == LengthAdjust::SpacingAndGlyphs) {
auto textLengthScale = textLength / chunkLength;
auto lengthAdjustTransform = Transform::translated(firstFragment.x, firstFragment.y);
if(isVerticalText) {
lengthAdjustTransform.scale(1.f, textLengthScale);
} else {
lengthAdjustTransform.scale(textLengthScale, 1.f);
}
lengthAdjustTransform.translate(-firstFragment.x, -firstFragment.y);
for(auto it = begin; it != end; ++it) {
SVGTextFragment& fragment = *it;
fragment.lengthAdjustTransform = lengthAdjustTransform;
}
} else if(numCharacters > 1) {
assert(firstFragment.element->lengthAdjust() == LengthAdjust::Spacing);
size_t characterOffset = 0;
auto textLengthShift = (textLength - chunkLength) / (numCharacters - 1);
for(auto it = begin; it != end; ++it) {
SVGTextFragment& fragment = *it;
if(isVerticalText) {
fragment.y += textLengthShift * characterOffset;
} else {
fragment.x += textLengthShift * characterOffset;
}
characterOffset += fragment.length;
}
}
}
}
if(needsTextAnchorAdjustment(firstFragment.element)) {
auto chunkLength = calculateTextChunkLength(begin, end, isVerticalText);
auto chunkOffset = calculateTextAnchorOffset(firstFragment.element, chunkLength);
for(auto it = begin; it != end; ++it) {
SVGTextFragment& fragment = *it;
if(isVerticalText) {
fragment.y += chunkOffset;
} else {
fragment.x += chunkOffset;
}
}
}
}
SVGTextFragmentsBuilder::SVGTextFragmentsBuilder(std::u32string& text, SVGTextFragmentList& fragments)
: m_text(text), m_fragments(fragments)
{
m_text.clear();
m_fragments.clear();
}
void SVGTextFragmentsBuilder::build(const SVGTextElement* textElement)
{
handleElement(textElement);
for(const auto& position : m_textPositions) {
fillCharacterPositions(position);
}
std::u32string_view wholeText(m_text);
for(const auto& textPosition : m_textPositions) {
if(!textPosition.node->isTextNode())
continue;
auto element = toSVGTextPositioningElement(textPosition.node->parentElement());
const auto isVerticalText = element->isVerticalWritingMode();
const auto isUprightText = element->isUprightTextOrientation();
const auto& font = element->font();
SVGTextFragment fragment(element);
auto recordTextFragment = [&](auto startOffset, auto endOffset) {
auto text = wholeText.substr(startOffset, endOffset - startOffset);
fragment.offset = startOffset;
fragment.length = text.length();
fragment.width = font.measureText(text);
fragment.height = font.height() + font.lineGap();
if(isVerticalText) {
m_y += isUprightText ? fragment.height : fragment.width;
} else {
m_x += fragment.width;
}
m_fragments.push_back(fragment);
};
auto needsTextLengthSpacing = element->lengthAdjust() == LengthAdjust::Spacing && element->hasAttribute(PropertyID::TextLength);
auto baselineOffset = calculateBaselineOffset(element);
auto startOffset = textPosition.startOffset;
auto textOffset = textPosition.startOffset;
auto didStartTextFragment = false;
auto applySpacingToNextCharacter = false;
auto lastCharacter = 0u;
auto lastAngle = 0.f;
while(textOffset < textPosition.endOffset) {
SVGCharacterPosition characterPosition;
if(auto it = m_characterPositions.find(m_characterOffset); it != m_characterPositions.end()) {
characterPosition = it->second;
}
auto currentCharacter = wholeText.at(textOffset);
auto angle = characterPosition.rotate.value_or(0);
auto dx = characterPosition.dx.value_or(0);
auto dy = characterPosition.dy.value_or(0);
auto shouldStartNewFragment = needsTextLengthSpacing || isVerticalText || applySpacingToNextCharacter
|| characterPosition.x || characterPosition.y || dx || dy || angle || angle != lastAngle;
if(shouldStartNewFragment && didStartTextFragment) {
recordTextFragment(startOffset, textOffset);
applySpacingToNextCharacter = false;
startOffset = textOffset;
}
auto startsNewTextChunk = (characterPosition.x || characterPosition.y) && textOffset == textPosition.startOffset;
if(startsNewTextChunk || shouldStartNewFragment || !didStartTextFragment) {
m_x = dx + characterPosition.x.value_or(m_x);
m_y = dy + characterPosition.y.value_or(m_y);
fragment.x = isVerticalText ? m_x + baselineOffset : m_x;
fragment.y = isVerticalText ? m_y : m_y - baselineOffset;
fragment.angle = angle;
if(isVerticalText) {
if(isUprightText) {
fragment.y += font.height();
} else {
fragment.angle += 90.f;
}
}
fragment.startsNewTextChunk = startsNewTextChunk;
didStartTextFragment = true;
}
auto spacing = element->letter_spacing();
if(currentCharacter && lastCharacter && element->word_spacing()) {
if(currentCharacter == ' ' && lastCharacter != ' ') {
spacing += element->word_spacing();
}
}
if(spacing) {
applySpacingToNextCharacter = true;
if(isVerticalText) {
m_y += spacing;
} else {
m_x += spacing;
}
}
lastAngle = angle;
lastCharacter = currentCharacter;
++textOffset;
++m_characterOffset;
}
recordTextFragment(startOffset, textOffset);
}
if(m_fragments.empty())
return;
auto it = m_fragments.begin();
auto begin = m_fragments.begin();
auto end = m_fragments.end();
for(++it; it != end; ++it) {
const SVGTextFragment& fragment = *it;
if(!fragment.startsNewTextChunk)
continue;
handleTextChunk(begin, it);
begin = it;
}
handleTextChunk(begin, it);
}
void SVGTextFragmentsBuilder::handleText(const SVGTextNode* node)
{
const auto& text = node->data();
if(text.empty())
return;
auto element = toSVGTextPositioningElement(node->parentElement());
const auto startOffset = m_text.length();
uint32_t lastCharacter = ' ';
if(!m_text.empty()) {
lastCharacter = m_text.back();
}
juce_plutovg_text_iterator_t it;
juce_plutovg_text_iterator_init(&it, text.data(), text.length(), JUCE_PLUTOVG_TEXT_ENCODING_UTF8);
while(juce_plutovg_text_iterator_has_next(&it)) {
auto currentCharacter = juce_plutovg_text_iterator_next(&it);
if(currentCharacter == '\t' || currentCharacter == '\n' || currentCharacter == '\r')
currentCharacter = ' ';
if(currentCharacter == ' ' && lastCharacter == ' ' && element->white_space() == WhiteSpace::Default)
continue;
m_text.push_back(currentCharacter);
lastCharacter = currentCharacter;
}
if(startOffset < m_text.length()) {
m_textPositions.emplace_back(node, startOffset, m_text.length());
}
}
void SVGTextFragmentsBuilder::handleElement(const SVGTextPositioningElement* element)
{
if(element->isDisplayNone())
return;
const auto itemIndex = m_textPositions.size();
m_textPositions.emplace_back(element, m_text.length(), m_text.length());
for(const auto& child : element->children()) {
if(child->isTextNode()) {
handleText(toSVGTextNode(child.get()));
} else if(child->isTextPositioningElement()) {
handleElement(toSVGTextPositioningElement(child.get()));
}
}
auto& position = m_textPositions[itemIndex];
assert(position.node == element);
position.endOffset = m_text.length();
}
void SVGTextFragmentsBuilder::fillCharacterPositions(const SVGTextPosition& position)
{
if(!position.node->isTextPositioningElement())
return;
auto element = toSVGTextPositioningElement(position.node);
const auto& xList = element->x();
const auto& yList = element->y();
const auto& dxList = element->dx();
const auto& dyList = element->dy();
const auto& rotateList = element->rotate();
auto xListSize = xList.size();
auto yListSize = yList.size();
auto dxListSize = dxList.size();
auto dyListSize = dyList.size();
auto rotateListSize = rotateList.size();
if(!xListSize && !yListSize && !dxListSize && !dyListSize && !rotateListSize) {
return;
}
LengthContext lengthContext(element);
std::optional<float> lastRotation;
for(auto offset = position.startOffset; offset < position.endOffset; ++offset) {
auto index = offset - position.startOffset;
if(index >= xListSize && index >= yListSize && index >= dxListSize && index >= dyListSize && index >= rotateListSize)
break;
auto& characterPosition = m_characterPositions[offset];
if(index < xListSize)
characterPosition.x = lengthContext.valueForLength(xList[index], LengthDirection::Horizontal);
if(index < yListSize)
characterPosition.y = lengthContext.valueForLength(yList[index], LengthDirection::Vertical);
if(index < dxListSize)
characterPosition.dx = lengthContext.valueForLength(dxList[index], LengthDirection::Horizontal);
if(index < dyListSize)
characterPosition.dy = lengthContext.valueForLength(dyList[index], LengthDirection::Vertical);
if(index < rotateListSize) {
characterPosition.rotate = rotateList[index];
lastRotation = characterPosition.rotate;
}
}
if(lastRotation == std::nullopt)
return;
auto offset = position.startOffset + rotateList.size();
while(offset < position.endOffset) {
m_characterPositions[offset++].rotate = lastRotation;
}
}
SVGTextPositioningElement::SVGTextPositioningElement(Document* document, ElementID id)
: SVGGraphicsElement(document, id)
, m_x(PropertyID::X, LengthDirection::Horizontal, LengthNegativeMode::Allow)
, m_y(PropertyID::Y, LengthDirection::Vertical, LengthNegativeMode::Allow)
, m_dx(PropertyID::Dx, LengthDirection::Horizontal, LengthNegativeMode::Allow)
, m_dy(PropertyID::Dy, LengthDirection::Vertical, LengthNegativeMode::Allow)
, m_rotate(PropertyID::Rotate)
, m_textLength(PropertyID::TextLength, LengthDirection::Horizontal, LengthNegativeMode::Forbid)
, m_lengthAdjust(PropertyID::LengthAdjust, LengthAdjust::Spacing)
{
addProperty(m_x);
addProperty(m_y);
addProperty(m_dx);
addProperty(m_dy);
addProperty(m_rotate);
addProperty(m_textLength);
addProperty(m_lengthAdjust);
}
void SVGTextPositioningElement::layoutElement(const SVGLayoutState& state)
{
m_font = state.font();
m_fill = getPaintServer(state.fill(), state.fill_opacity());
m_stroke = getPaintServer(state.stroke(), state.stroke_opacity());
SVGGraphicsElement::layoutElement(state);
LengthContext lengthContext(this);
m_stroke_width = lengthContext.valueForLength(state.stroke_width(), LengthDirection::Diagonal);
m_letter_spacing = lengthContext.valueForLength(state.letter_spacing(), LengthDirection::Diagonal);
m_word_spacing = lengthContext.valueForLength(state.word_spacing(), LengthDirection::Diagonal);
m_baseline_offset = convertBaselineOffset(state.baseline_shit());
m_alignment_baseline = state.alignment_baseline();
m_dominant_baseline = state.dominant_baseline();
m_text_anchor = state.text_anchor();
m_white_space = state.white_space();
m_writing_mode = state.writing_mode();
m_text_orientation = state.text_orientation();
m_direction = state.direction();
}
float SVGTextPositioningElement::convertBaselineOffset(const BaselineShift& baselineShift) const
{
if(baselineShift.type() == BaselineShift::Type::Baseline)
return 0.f;
if(baselineShift.type() == BaselineShift::Type::Sub)
return -m_font.height() / 2.f;
if(baselineShift.type() == BaselineShift::Type::Super) {
return m_font.height() / 2.f;
}
const auto& length = baselineShift.length();
if(length.units() == LengthUnits::Percent)
return length.value() * m_font.size() / 100.f;
if(length.units() == LengthUnits::Ex)
return length.value() * m_font.size() / 2.f;
if(length.units() == LengthUnits::Em)
return length.value() * m_font.size();
return length.value();
}
SVGTSpanElement::SVGTSpanElement(Document* document)
: SVGTextPositioningElement(document, ElementID::Tspan)
{
}
SVGTextElement::SVGTextElement(Document* document)
: SVGTextPositioningElement(document, ElementID::Text)
{
}
void SVGTextElement::layout(SVGLayoutState& state)
{
SVGTextPositioningElement::layout(state);
SVGTextFragmentsBuilder(m_text, m_fragments).build(this);
}
void SVGTextElement::render(SVGRenderState& state) const
{
if(m_fragments.empty() || isVisibilityHidden() || isDisplayNone())
return;
SVGBlendInfo blendInfo(this);
SVGRenderState newState(this, state, localTransform());
newState.beginGroup(blendInfo);
if(newState.mode() == SVGRenderMode::Clipping) {
newState->setColor(Color::White);
}
std::u32string_view wholeText(m_text);
for(const auto& fragment : m_fragments) {
if(fragment.element->isVisibilityHidden())
continue;
auto transform = newState.currentTransform() * Transform::rotated(fragment.angle, fragment.x, fragment.y) * fragment.lengthAdjustTransform;
auto text = wholeText.substr(fragment.offset, fragment.length);
auto origin = Point(fragment.x, fragment.y);
const auto& font = fragment.element->font();
if(newState.mode() == SVGRenderMode::Clipping) {
newState->fillText(text, font, origin, transform);
} else {
const auto& fill = fragment.element->fill();
const auto& stroke = fragment.element->stroke();
auto stroke_width = fragment.element->stroke_width();
if(fill.applyPaint(newState))
newState->fillText(text, font, origin, transform);
if(stroke.applyPaint(newState)) {
newState->strokeText(text, stroke_width, font, origin, transform);
}
}
}
newState.endGroup(blendInfo);
}
Rect SVGTextElement::boundingBox(bool includeStroke) const
{
auto boundingBox = Rect::Invalid;
for(const auto& fragment : m_fragments) {
const auto& font = fragment.element->font();
const auto& stroke = fragment.element->stroke();
auto fragmentTranform = Transform::rotated(fragment.angle, fragment.x, fragment.y) * fragment.lengthAdjustTransform;
auto fragmentRect = Rect(fragment.x, fragment.y - font.ascent(), fragment.width, fragment.height);
if(includeStroke && stroke.isRenderable())
fragmentRect.inflate(fragment.element->stroke_width() / 2.f);
boundingBox.unite(fragmentTranform.mapRect(fragmentRect));
}
if(!boundingBox.isValid())
boundingBox = Rect::Empty;
return boundingBox;
}
} // namespace lunasvg
}
@@ -0,0 +1,157 @@
#ifndef LUNASVG_SVGTEXTELEMENT_H
#define LUNASVG_SVGTEXTELEMENT_H
#include "svgelement.h"
#include <optional>
namespace {
namespace lunasvg {
class SVGTextPositioningElement;
class SVGTextElement;
struct SVGCharacterPosition {
std::optional<float> x;
std::optional<float> y;
std::optional<float> dx;
std::optional<float> dy;
std::optional<float> rotate;
};
using SVGCharacterPositions = std::map<size_t, SVGCharacterPosition>;
struct SVGTextPosition {
SVGTextPosition(const SVGNode* node, size_t startOffset, size_t endOffset)
: node(node), startOffset(startOffset), endOffset(endOffset)
{}
const SVGNode* node;
size_t startOffset;
size_t endOffset;
};
using SVGTextPositionList = std::vector<SVGTextPosition>;
struct SVGTextFragment {
explicit SVGTextFragment(const SVGTextPositioningElement* element) : element(element) {}
const SVGTextPositioningElement* element;
Transform lengthAdjustTransform;
size_t offset = 0;
size_t length = 0;
bool startsNewTextChunk = false;
float x = 0;
float y = 0;
float width = 0;
float height = 0;
float angle = 0;
};
using SVGTextFragmentList = std::vector<SVGTextFragment>;
class SVGTextFragmentsBuilder {
public:
SVGTextFragmentsBuilder(std::u32string& text, SVGTextFragmentList& fragments);
void build(const SVGTextElement* textElement);
private:
void handleText(const SVGTextNode* node);
void handleElement(const SVGTextPositioningElement* element);
void fillCharacterPositions(const SVGTextPosition& position);
std::u32string& m_text;
SVGTextFragmentList& m_fragments;
SVGCharacterPositions m_characterPositions;
SVGTextPositionList m_textPositions;
size_t m_characterOffset = 0;
float m_x = 0;
float m_y = 0;
};
class SVGTextPositioningElement : public SVGGraphicsElement {
public:
SVGTextPositioningElement(Document* document, ElementID id);
bool isTextPositioningElement() const final { return true; }
const LengthList& x() const { return m_x.values(); }
const LengthList& y() const { return m_y.values(); }
const LengthList& dx() const { return m_dx.values(); }
const LengthList& dy() const { return m_dy.values(); }
const NumberList& rotate() const { return m_rotate.values(); }
const SVGLength& textLength() const { return m_textLength; }
LengthAdjust lengthAdjust() const { return m_lengthAdjust.value(); }
const Font& font() const { return m_font; }
const SVGPaintServer& fill() const { return m_fill; }
const SVGPaintServer& stroke() const { return m_stroke; }
bool isVerticalWritingMode() const { return m_writing_mode == WritingMode::Vertical; }
bool isUprightTextOrientation() const { return m_text_orientation == TextOrientation::Upright; }
float stroke_width() const { return m_stroke_width; }
float letter_spacing() const { return m_letter_spacing; }
float word_spacing() const { return m_word_spacing; }
float baseline_offset() const { return m_baseline_offset; }
AlignmentBaseline alignment_baseline() const { return m_alignment_baseline; }
DominantBaseline dominant_baseline() const { return m_dominant_baseline; }
TextAnchor text_anchor() const { return m_text_anchor; }
WhiteSpace white_space() const { return m_white_space; }
Direction direction() const { return m_direction; }
void layoutElement(const SVGLayoutState& state) override;
private:
float convertBaselineOffset(const BaselineShift& baselineShift) const;
SVGLengthList m_x;
SVGLengthList m_y;
SVGLengthList m_dx;
SVGLengthList m_dy;
SVGNumberList m_rotate;
SVGLength m_textLength;
SVGEnumeration<LengthAdjust> m_lengthAdjust;
Font m_font;
SVGPaintServer m_fill;
SVGPaintServer m_stroke;
float m_stroke_width = 1.f;
float m_letter_spacing = 0.f;
float m_word_spacing = 0.f;
float m_baseline_offset = 0.f;
AlignmentBaseline m_alignment_baseline = AlignmentBaseline::Auto;
DominantBaseline m_dominant_baseline = DominantBaseline::Auto;
TextAnchor m_text_anchor = TextAnchor::Start;
WhiteSpace m_white_space = WhiteSpace::Default;
WritingMode m_writing_mode = WritingMode::Horizontal;
TextOrientation m_text_orientation = TextOrientation::Mixed;
Direction m_direction = Direction::Ltr;
};
class SVGTSpanElement final : public SVGTextPositioningElement {
public:
SVGTSpanElement(Document* document);
};
class SVGTextElement final : public SVGTextPositioningElement {
public:
SVGTextElement(Document* document);
Rect fillBoundingBox() const final { return boundingBox(false); }
Rect strokeBoundingBox() const final { return boundingBox(true); }
void layout(SVGLayoutState& state) final;
void render(SVGRenderState& state) const final;
private:
Rect boundingBox(bool includeStroke) const;
SVGTextFragmentList m_fragments;
std::u32string m_text;
};
} // namespace lunasvg
}
#endif // LUNASVG_SVGTEXTELEMENT_H
@@ -0,0 +1,153 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
DropShadow::DropShadow (Colour shadowColour, const int r, Point<int> o) noexcept
: colour (shadowColour), radius (r), offset (o)
{
jassert (radius > 0);
}
void DropShadow::drawForImage (Graphics& g, const Image& srcImage) const
{
jassert (radius > 0);
if (! srcImage.isValid())
return;
auto blurred = srcImage.convertedToFormat (Image::SingleChannel);
blurred.setBackupEnabled (false);
blurred.getPixelData()->applySingleChannelBoxBlurEffect (radius);
g.setColour (colour);
g.drawImageAt (blurred, offset.x, offset.y, true);
}
void DropShadow::drawForPath (Graphics& g, const Path& path) const
{
jassert (radius > 0);
auto area = (path.getBounds().getSmallestIntegerContainer() + offset)
.expanded (radius + 1)
.getIntersection (g.getClipBounds().expanded (radius + 1));
if (area.getWidth() <= 2 || area.getHeight() <= 2)
return;
const auto tempImageType = g.getInternalContext().getPreferredImageTypeForTemporaryImages();
Image pathImage { Image::SingleChannel, area.getWidth(), area.getHeight(), true, *tempImageType };
pathImage.setBackupEnabled (false);
{
Graphics g2 (pathImage);
g2.setColour (Colours::white);
g2.fillPath (path, AffineTransform::translation ((float) (offset.x - area.getX()),
(float) (offset.y - area.getY())));
}
pathImage.getPixelData()->applySingleChannelBoxBlurEffect (radius);
g.setColour (colour);
g.drawImageAt (pathImage, area.getX(), area.getY(), true);
}
static void drawShadowSection (Graphics& g, ColourGradient& cg, Rectangle<float> area,
bool isCorner, float centreX, float centreY, float edgeX, float edgeY)
{
cg.point1 = area.getRelativePoint (centreX, centreY);
cg.point2 = area.getRelativePoint (edgeX, edgeY);
cg.isRadial = isCorner;
g.setGradientFill (cg);
g.fillRect (area);
}
void DropShadow::drawForRectangle (Graphics& g, const Rectangle<int>& targetArea) const
{
ColourGradient cg (colour, 0, 0, colour.withAlpha (0.0f), 0, 0, false);
for (float i = 0.05f; i < 1.0f; i += 0.1f)
cg.addColour (1.0 - i, colour.withMultipliedAlpha (i * i));
const float radiusInset = (float) radius / 2.0f;
const float expandedRadius = (float) radius + radiusInset;
auto area = targetArea.toFloat().reduced (radiusInset) + offset.toFloat();
auto r = area.expanded (expandedRadius);
auto top = r.removeFromTop (expandedRadius);
auto bottom = r.removeFromBottom (expandedRadius);
drawShadowSection (g, cg, top.removeFromLeft (expandedRadius), true, 1.0f, 1.0f, 0, 1.0f);
drawShadowSection (g, cg, top.removeFromRight (expandedRadius), true, 0, 1.0f, 1.0f, 1.0f);
drawShadowSection (g, cg, top, false, 0, 1.0f, 0, 0);
drawShadowSection (g, cg, bottom.removeFromLeft (expandedRadius), true, 1.0f, 0, 0, 0);
drawShadowSection (g, cg, bottom.removeFromRight (expandedRadius), true, 0, 0, 1.0f, 0);
drawShadowSection (g, cg, bottom, false, 0, 0, 0, 1.0f);
drawShadowSection (g, cg, r.removeFromLeft (expandedRadius), false, 1.0f, 0, 0, 0);
drawShadowSection (g, cg, r.removeFromRight (expandedRadius), false, 0, 0, 1.0f, 0);
g.setColour (colour);
g.fillRect (area);
}
//==============================================================================
DropShadowEffect::DropShadowEffect() = default;
DropShadowEffect::~DropShadowEffect() = default;
void DropShadowEffect::setShadowProperties (const DropShadow& newShadow)
{
shadow = newShadow;
}
void DropShadowEffect::applyEffect (Image& image, Graphics& g, float scaleFactor, float alpha)
{
DropShadow s (shadow);
s.radius = roundToInt ((float) s.radius * scaleFactor);
s.colour = s.colour.withMultipliedAlpha (alpha);
s.offset.x = roundToInt ((float) s.offset.x * scaleFactor);
s.offset.y = roundToInt ((float) s.offset.y * scaleFactor);
s.drawForImage (g, image);
g.setOpacity (alpha);
g.drawImageAt (image, 0, 0);
}
} // namespace juce
@@ -0,0 +1,122 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
Defines a drop-shadow effect.
@tags{Graphics}
*/
struct JUCE_API DropShadow
{
/** Creates a default drop-shadow effect. */
DropShadow() = default;
/** Creates a drop-shadow object with the given parameters. */
DropShadow (Colour shadowColour, int radius, Point<int> offset) noexcept;
/** Renders a drop-shadow based on the alpha-channel of the given image. */
void drawForImage (Graphics& g, const Image& srcImage) const;
/** Renders a drop-shadow based on the shape of a path. */
void drawForPath (Graphics& g, const Path& path) const;
/** Renders a drop-shadow for a rectangle.
Note that for speed, this approximates the shadow using gradients.
*/
void drawForRectangle (Graphics& g, const Rectangle<int>& area) const;
/** The colour with which to render the shadow.
In most cases you'll probably want to leave this as black with an alpha
value of around 0.5
*/
Colour colour { 0x90000000 };
/** The approximate spread of the shadow. */
int radius { 4 };
/** The offset of the shadow. */
Point<int> offset;
};
//==============================================================================
/**
An effect filter that adds a drop-shadow behind the image's content.
(This will only work on images/components that aren't opaque, of course).
When added to a component, this effect will draw a soft-edged
shadow based on what gets drawn inside it. The shadow will also
be applied to the component's children.
For speed, this doesn't use a proper gaussian blur, but cheats by
using a simple bilinear filter. If you need a really high-quality
shadow, check out ImageConvolutionKernel::createGaussianBlur()
@see Component::setComponentEffect
@tags{Graphics}
*/
class JUCE_API DropShadowEffect : public ImageEffectFilter
{
public:
//==============================================================================
/** Creates a default drop-shadow effect.
To customise the shadow's appearance, use the setShadowProperties() method.
*/
DropShadowEffect();
/** Destructor. */
~DropShadowEffect() override;
//==============================================================================
/** Sets up parameters affecting the shadow's appearance. */
void setShadowProperties (const DropShadow& newShadow);
//==============================================================================
/** @internal */
void applyEffect (Image& sourceImage, Graphics& destContext, float scaleFactor, float alpha) override;
private:
//==============================================================================
DropShadow shadow;
JUCE_LEAK_DETECTOR (DropShadowEffect)
};
} // namespace juce
@@ -0,0 +1,63 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
GlowEffect::GlowEffect() = default;
GlowEffect::~GlowEffect() = default;
void GlowEffect::setGlowProperties (float newRadius, Colour newColour, Point<int> pos)
{
radius = newRadius;
colour = newColour;
offset = pos;
}
void GlowEffect::applyEffect (Image& image, Graphics& g, float scaleFactor, float alpha)
{
auto blurred = image.createCopy();
blurred.setBackupEnabled (false);
if (auto ptr = blurred.getPixelData())
ptr->applyGaussianBlurEffect (radius * scaleFactor);
g.setColour (colour.withMultipliedAlpha (alpha));
g.drawImageAt (blurred, offset.x, offset.y, true);
g.setOpacity (alpha);
g.drawImageAt (image, offset.x, offset.y, false);
}
} // namespace juce
@@ -0,0 +1,85 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
A component effect that adds a coloured blur around the component's contents.
(This will only work on non-opaque components).
@see Component::setComponentEffect, DropShadowEffect
@tags{Graphics}
*/
class JUCE_API GlowEffect : public ImageEffectFilter
{
public:
//==============================================================================
/** Creates a default 'glow' effect.
To customise its appearance, use the setGlowProperties() method.
*/
GlowEffect();
/** Destructor. */
~GlowEffect() override;
//==============================================================================
/** Sets the glow's radius and colour.
The radius is how large the blur should be, and the colour is
used to render it (for a less intense glow, lower the colour's
opacity).
*/
void setGlowProperties (float newRadius,
Colour newColour,
Point<int> offset = {});
//==============================================================================
/** @internal */
void applyEffect (Image&, Graphics&, float scaleFactor, float alpha) override;
private:
//==============================================================================
float radius = 2.0f;
Colour colour { Colours::white };
Point<int> offset;
JUCE_LEAK_DETECTOR (GlowEffect)
};
} // namespace juce
@@ -0,0 +1,80 @@
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
/**
A graphical effect filter that can be applied to components.
An ImageEffectFilter can be applied to the image that a component
paints before it hits the screen.
This is used for adding effects like shadows, blurs, etc.
@see Component::setComponentEffect
@tags{Graphics}
*/
class JUCE_API ImageEffectFilter
{
public:
//==============================================================================
/** Overridden to render the effect.
The implementation of this method must use the image that is passed in
as its source, and should render its output to the graphics context passed in.
@param sourceImage the image that the source component has just rendered with
its paint() method. The image may or may not have an alpha
channel, depending on whether the component is opaque.
@param destContext the graphics context to use to draw the resultant image.
@param scaleFactor a scale factor that has been applied to the image - e.g. if
this is 2, then the image is actually scaled-up to twice the
original resolution
@param alpha the alpha with which to draw the resultant image to the
target context
*/
virtual void applyEffect (Image& sourceImage,
Graphics& destContext,
float scaleFactor,
float alpha) = 0;
/** Destructor. */
virtual ~ImageEffectFilter() = default;
};
} // namespace juce
@@ -0,0 +1,42 @@
HarfBuzz is licensed under the so-called "Old MIT" license. Details follow.
For parts of HarfBuzz that are licensed under different licenses see individual
files names COPYING in subdirectories where applicable.
Copyright © 2010-2022 Google, Inc.
Copyright © 2015-2020 Ebrahim Byagowi
Copyright © 2019,2020 Facebook, Inc.
Copyright © 2012,2015 Mozilla Foundation
Copyright © 2011 Codethink Limited
Copyright © 2008,2010 Nokia Corporation and/or its subsidiary(-ies)
Copyright © 2009 Keith Stribley
Copyright © 2011 Martin Hosken and SIL International
Copyright © 2007 Chris Wilson
Copyright © 2005,2006,2020,2021,2022,2023 Behdad Esfahbod
Copyright © 2004,2007,2008,2009,2010,2013,2021,2022,2023 Red Hat, Inc.
Copyright © 1998-2005 David Turner and Werner Lemberg
Copyright © 2016 Igalia S.L.
Copyright © 2022 Matthias Clasen
Copyright © 2018,2021 Khaled Hosny
Copyright © 2018,2019,2020 Adobe, Inc
Copyright © 2013-2015 Alexei Podtelezhnikov
For full copyright notices consult the individual files in the package.
Permission is hereby granted, without written agreement and without
license or royalty fees, to use, copy, modify, and distribute this
software and its documentation for any purpose, provided that the
above copyright notice and the following two paragraphs appear in
all copies of this software.
IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Loaded 100 of 10387 files, more files were not shown because too many files have changed in this diff. Show more