The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2779 lines
104KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. #if JUCE_MSVC
  22. #pragma warning (push)
  23. #pragma warning (disable: 4127) // "expression is constant" warning
  24. #endif
  25. namespace RenderingHelpers
  26. {
  27. //==============================================================================
  28. /** Holds either a simple integer translation, or an affine transform.
  29. @tags{Graphics}
  30. */
  31. class TranslationOrTransform
  32. {
  33. public:
  34. TranslationOrTransform() noexcept {}
  35. TranslationOrTransform (Point<int> origin) noexcept : offset (origin) {}
  36. TranslationOrTransform (const TranslationOrTransform& other) noexcept
  37. : complexTransform (other.complexTransform), offset (other.offset),
  38. isOnlyTranslated (other.isOnlyTranslated), isRotated (other.isRotated)
  39. {
  40. }
  41. AffineTransform getTransform() const noexcept
  42. {
  43. return isOnlyTranslated ? AffineTransform::translation (offset)
  44. : complexTransform;
  45. }
  46. AffineTransform getTransformWith (const AffineTransform& userTransform) const noexcept
  47. {
  48. return isOnlyTranslated ? userTransform.translated (offset)
  49. : userTransform.followedBy (complexTransform);
  50. }
  51. bool isIdentity() const noexcept
  52. {
  53. return isOnlyTranslated && offset.isOrigin();
  54. }
  55. void setOrigin (Point<int> delta) noexcept
  56. {
  57. if (isOnlyTranslated)
  58. offset += delta;
  59. else
  60. complexTransform = AffineTransform::translation (delta)
  61. .followedBy (complexTransform);
  62. }
  63. void addTransform (const AffineTransform& t) noexcept
  64. {
  65. if (isOnlyTranslated && t.isOnlyTranslation())
  66. {
  67. auto tx = (int) (t.getTranslationX() * 256.0f);
  68. auto ty = (int) (t.getTranslationY() * 256.0f);
  69. if (((tx | ty) & 0xf8) == 0)
  70. {
  71. offset += Point<int> (tx >> 8, ty >> 8);
  72. return;
  73. }
  74. }
  75. complexTransform = getTransformWith (t);
  76. isOnlyTranslated = false;
  77. isRotated = (complexTransform.mat01 != 0.0f || complexTransform.mat10 != 0.0f
  78. || complexTransform.mat00 < 0 || complexTransform.mat11 < 0);
  79. }
  80. float getPhysicalPixelScaleFactor() const noexcept
  81. {
  82. return isOnlyTranslated ? 1.0f : std::abs (complexTransform.getScaleFactor());
  83. }
  84. void moveOriginInDeviceSpace (Point<int> delta) noexcept
  85. {
  86. if (isOnlyTranslated)
  87. offset += delta;
  88. else
  89. complexTransform = complexTransform.translated (delta);
  90. }
  91. Rectangle<int> translated (Rectangle<int> r) const noexcept
  92. {
  93. jassert (isOnlyTranslated);
  94. return r + offset;
  95. }
  96. Rectangle<float> translated (Rectangle<float> r) const noexcept
  97. {
  98. jassert (isOnlyTranslated);
  99. return r + offset.toFloat();
  100. }
  101. template <typename RectangleOrPoint>
  102. RectangleOrPoint transformed (RectangleOrPoint r) const noexcept
  103. {
  104. jassert (! isOnlyTranslated);
  105. return r.transformedBy (complexTransform);
  106. }
  107. template <typename Type>
  108. Rectangle<Type> deviceSpaceToUserSpace (Rectangle<Type> r) const noexcept
  109. {
  110. return isOnlyTranslated ? r - offset
  111. : r.transformedBy (complexTransform.inverted());
  112. }
  113. AffineTransform complexTransform;
  114. Point<int> offset;
  115. bool isOnlyTranslated = true, isRotated = false;
  116. };
  117. //==============================================================================
  118. /** Holds a cache of recently-used glyph objects of some type.
  119. @tags{Graphics}
  120. */
  121. template <class CachedGlyphType, class RenderTargetType>
  122. class GlyphCache : private DeletedAtShutdown
  123. {
  124. public:
  125. GlyphCache()
  126. {
  127. reset();
  128. }
  129. ~GlyphCache()
  130. {
  131. getSingletonPointer() = nullptr;
  132. }
  133. static GlyphCache& getInstance()
  134. {
  135. auto& g = getSingletonPointer();
  136. if (g == nullptr)
  137. g = new GlyphCache();
  138. return *g;
  139. }
  140. //==============================================================================
  141. void reset()
  142. {
  143. const ScopedLock sl (lock);
  144. glyphs.clear();
  145. addNewGlyphSlots (120);
  146. hits = 0;
  147. misses = 0;
  148. }
  149. void drawGlyph (RenderTargetType& target, const Font& font, const int glyphNumber, Point<float> pos)
  150. {
  151. if (auto glyph = findOrCreateGlyph (font, glyphNumber))
  152. {
  153. glyph->lastAccessCount = ++accessCounter;
  154. glyph->draw (target, pos);
  155. }
  156. }
  157. ReferenceCountedObjectPtr<CachedGlyphType> findOrCreateGlyph (const Font& font, int glyphNumber)
  158. {
  159. const ScopedLock sl (lock);
  160. if (auto g = findExistingGlyph (font, glyphNumber))
  161. {
  162. ++hits;
  163. return g;
  164. }
  165. ++misses;
  166. auto g = getGlyphForReuse();
  167. jassert (g != nullptr);
  168. g->generate (font, glyphNumber);
  169. return g;
  170. }
  171. private:
  172. ReferenceCountedArray<CachedGlyphType> glyphs;
  173. Atomic<int> accessCounter, hits, misses;
  174. CriticalSection lock;
  175. ReferenceCountedObjectPtr<CachedGlyphType> findExistingGlyph (const Font& font, int glyphNumber) const noexcept
  176. {
  177. for (auto g : glyphs)
  178. if (g->glyph == glyphNumber && g->font == font)
  179. return *g;
  180. return {};
  181. }
  182. ReferenceCountedObjectPtr<CachedGlyphType> getGlyphForReuse()
  183. {
  184. if (hits.get() + misses.get() > glyphs.size() * 16)
  185. {
  186. if (misses.get() * 2 > hits.get())
  187. addNewGlyphSlots (32);
  188. hits = 0;
  189. misses = 0;
  190. }
  191. if (auto g = findLeastRecentlyUsedGlyph())
  192. return *g;
  193. addNewGlyphSlots (32);
  194. return glyphs.getLast();
  195. }
  196. void addNewGlyphSlots (int num)
  197. {
  198. glyphs.ensureStorageAllocated (glyphs.size() + num);
  199. while (--num >= 0)
  200. glyphs.add (new CachedGlyphType());
  201. }
  202. CachedGlyphType* findLeastRecentlyUsedGlyph() const noexcept
  203. {
  204. CachedGlyphType* oldest = nullptr;
  205. auto oldestCounter = std::numeric_limits<int>::max();
  206. for (auto* g : glyphs)
  207. {
  208. if (g->lastAccessCount <= oldestCounter
  209. && g->getReferenceCount() == 1)
  210. {
  211. oldestCounter = g->lastAccessCount;
  212. oldest = g;
  213. }
  214. }
  215. return oldest;
  216. }
  217. static GlyphCache*& getSingletonPointer() noexcept
  218. {
  219. static GlyphCache* g = nullptr;
  220. return g;
  221. }
  222. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphCache)
  223. };
  224. //==============================================================================
  225. /** Caches a glyph as an edge-table.
  226. @tags{Graphics}
  227. */
  228. template <class RendererType>
  229. class CachedGlyphEdgeTable : public ReferenceCountedObject
  230. {
  231. public:
  232. CachedGlyphEdgeTable() {}
  233. void draw (RendererType& state, Point<float> pos) const
  234. {
  235. if (snapToIntegerCoordinate)
  236. pos.x = std::floor (pos.x + 0.5f);
  237. if (edgeTable != nullptr)
  238. state.fillEdgeTable (*edgeTable, pos.x, roundToInt (pos.y));
  239. }
  240. void generate (const Font& newFont, int glyphNumber)
  241. {
  242. font = newFont;
  243. auto* typeface = newFont.getTypeface();
  244. snapToIntegerCoordinate = typeface->isHinted();
  245. glyph = glyphNumber;
  246. auto fontHeight = font.getHeight();
  247. edgeTable.reset (typeface->getEdgeTableForGlyph (glyphNumber,
  248. AffineTransform::scale (fontHeight * font.getHorizontalScale(),
  249. fontHeight), fontHeight));
  250. }
  251. Font font;
  252. std::unique_ptr<EdgeTable> edgeTable;
  253. int glyph = 0, lastAccessCount = 0;
  254. bool snapToIntegerCoordinate = false;
  255. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedGlyphEdgeTable)
  256. };
  257. //==============================================================================
  258. /** Calculates the alpha values and positions for rendering the edges of a
  259. non-pixel-aligned rectangle.
  260. @tags{Graphics}
  261. */
  262. struct FloatRectangleRasterisingInfo
  263. {
  264. FloatRectangleRasterisingInfo (Rectangle<float> area)
  265. : left (roundToInt (256.0f * area.getX())),
  266. top (roundToInt (256.0f * area.getY())),
  267. right (roundToInt (256.0f * area.getRight())),
  268. bottom (roundToInt (256.0f * area.getBottom()))
  269. {
  270. if ((top >> 8) == (bottom >> 8))
  271. {
  272. topAlpha = bottom - top;
  273. bottomAlpha = 0;
  274. totalTop = top >> 8;
  275. totalBottom = bottom = top = totalTop + 1;
  276. }
  277. else
  278. {
  279. if ((top & 255) == 0)
  280. {
  281. topAlpha = 0;
  282. top = totalTop = (top >> 8);
  283. }
  284. else
  285. {
  286. topAlpha = 255 - (top & 255);
  287. totalTop = (top >> 8);
  288. top = totalTop + 1;
  289. }
  290. bottomAlpha = bottom & 255;
  291. bottom >>= 8;
  292. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  293. }
  294. if ((left >> 8) == (right >> 8))
  295. {
  296. leftAlpha = right - left;
  297. rightAlpha = 0;
  298. totalLeft = (left >> 8);
  299. totalRight = right = left = totalLeft + 1;
  300. }
  301. else
  302. {
  303. if ((left & 255) == 0)
  304. {
  305. leftAlpha = 0;
  306. left = totalLeft = (left >> 8);
  307. }
  308. else
  309. {
  310. leftAlpha = 255 - (left & 255);
  311. totalLeft = (left >> 8);
  312. left = totalLeft + 1;
  313. }
  314. rightAlpha = right & 255;
  315. right >>= 8;
  316. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  317. }
  318. }
  319. template <class Callback>
  320. void iterate (Callback& callback) const
  321. {
  322. if (topAlpha != 0) callback (totalLeft, totalTop, totalRight - totalLeft, 1, topAlpha);
  323. if (bottomAlpha != 0) callback (totalLeft, bottom, totalRight - totalLeft, 1, bottomAlpha);
  324. if (leftAlpha != 0) callback (totalLeft, totalTop, 1, totalBottom - totalTop, leftAlpha);
  325. if (rightAlpha != 0) callback (right, totalTop, 1, totalBottom - totalTop, rightAlpha);
  326. callback (left, top, right - left, bottom - top, 255);
  327. }
  328. inline bool isOnePixelWide() const noexcept { return right - left == 1 && leftAlpha + rightAlpha == 0; }
  329. inline int getTopLeftCornerAlpha() const noexcept { return (topAlpha * leftAlpha) >> 8; }
  330. inline int getTopRightCornerAlpha() const noexcept { return (topAlpha * rightAlpha) >> 8; }
  331. inline int getBottomLeftCornerAlpha() const noexcept { return (bottomAlpha * leftAlpha) >> 8; }
  332. inline int getBottomRightCornerAlpha() const noexcept { return (bottomAlpha * rightAlpha) >> 8; }
  333. //==============================================================================
  334. int left, top, right, bottom; // bounds of the solid central area, excluding anti-aliased edges
  335. int totalTop, totalLeft, totalBottom, totalRight; // bounds of the total area, including edges
  336. int topAlpha, leftAlpha, bottomAlpha, rightAlpha; // alpha of each anti-aliased edge
  337. };
  338. //==============================================================================
  339. /** Contains classes for calculating the colour of pixels within various types of gradient. */
  340. namespace GradientPixelIterators
  341. {
  342. /** Iterates the colour of pixels in a linear gradient */
  343. struct Linear
  344. {
  345. Linear (const ColourGradient& gradient, const AffineTransform& transform,
  346. const PixelARGB* colours, int numColours)
  347. : lookupTable (colours),
  348. numEntries (numColours)
  349. {
  350. jassert (numColours >= 0);
  351. auto p1 = gradient.point1;
  352. auto p2 = gradient.point2;
  353. if (! transform.isIdentity())
  354. {
  355. auto p3 = Line<float> (p2, p1).getPointAlongLine (0.0f, 100.0f);
  356. p1.applyTransform (transform);
  357. p2.applyTransform (transform);
  358. p3.applyTransform (transform);
  359. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  360. }
  361. vertical = std::abs (p1.x - p2.x) < 0.001f;
  362. horizontal = std::abs (p1.y - p2.y) < 0.001f;
  363. if (vertical)
  364. {
  365. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.y - p1.y));
  366. start = roundToInt (p1.y * (float) scale);
  367. }
  368. else if (horizontal)
  369. {
  370. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.x - p1.x));
  371. start = roundToInt (p1.x * (float) scale);
  372. }
  373. else
  374. {
  375. grad = (p2.getY() - p1.y) / (double) (p1.x - p2.x);
  376. yTerm = p1.getY() - p1.x / grad;
  377. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.y * grad - p2.x)));
  378. grad *= scale;
  379. }
  380. }
  381. forcedinline void setY (int y) noexcept
  382. {
  383. if (vertical)
  384. linePix = lookupTable[jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  385. else if (! horizontal)
  386. start = roundToInt ((y - yTerm) * grad);
  387. }
  388. inline PixelARGB getPixel (int x) const noexcept
  389. {
  390. return vertical ? linePix
  391. : lookupTable[jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  392. }
  393. const PixelARGB* const lookupTable;
  394. const int numEntries;
  395. PixelARGB linePix;
  396. int start, scale;
  397. double grad, yTerm;
  398. bool vertical, horizontal;
  399. enum { numScaleBits = 12 };
  400. JUCE_DECLARE_NON_COPYABLE (Linear)
  401. };
  402. //==============================================================================
  403. /** Iterates the colour of pixels in a circular radial gradient */
  404. struct Radial
  405. {
  406. Radial (const ColourGradient& gradient, const AffineTransform&,
  407. const PixelARGB* colours, int numColours)
  408. : lookupTable (colours),
  409. numEntries (numColours),
  410. gx1 (gradient.point1.x),
  411. gy1 (gradient.point1.y)
  412. {
  413. jassert (numColours >= 0);
  414. auto diff = gradient.point1 - gradient.point2;
  415. maxDist = diff.x * diff.x + diff.y * diff.y;
  416. invScale = numEntries / std::sqrt (maxDist);
  417. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  418. }
  419. forcedinline void setY (int y) noexcept
  420. {
  421. dy = y - gy1;
  422. dy *= dy;
  423. }
  424. inline PixelARGB getPixel (int px) const noexcept
  425. {
  426. auto x = px - gx1;
  427. x *= x;
  428. x += dy;
  429. return lookupTable[x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  430. }
  431. const PixelARGB* const lookupTable;
  432. const int numEntries;
  433. const double gx1, gy1;
  434. double maxDist, invScale, dy;
  435. JUCE_DECLARE_NON_COPYABLE (Radial)
  436. };
  437. //==============================================================================
  438. /** Iterates the colour of pixels in a skewed radial gradient */
  439. struct TransformedRadial : public Radial
  440. {
  441. TransformedRadial (const ColourGradient& gradient, const AffineTransform& transform,
  442. const PixelARGB* colours, int numColours)
  443. : Radial (gradient, transform, colours, numColours),
  444. inverseTransform (transform.inverted())
  445. {
  446. tM10 = inverseTransform.mat10;
  447. tM00 = inverseTransform.mat00;
  448. }
  449. forcedinline void setY (int y) noexcept
  450. {
  451. auto floatY = (float) y;
  452. lineYM01 = inverseTransform.mat01 * floatY + inverseTransform.mat02 - gx1;
  453. lineYM11 = inverseTransform.mat11 * floatY + inverseTransform.mat12 - gy1;
  454. }
  455. inline PixelARGB getPixel (int px) const noexcept
  456. {
  457. double x = px;
  458. auto y = tM10 * x + lineYM11;
  459. x = tM00 * x + lineYM01;
  460. x *= x;
  461. x += y * y;
  462. if (x >= maxDist)
  463. return lookupTable[numEntries];
  464. return lookupTable[jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  465. }
  466. private:
  467. double tM10, tM00, lineYM01, lineYM11;
  468. const AffineTransform inverseTransform;
  469. JUCE_DECLARE_NON_COPYABLE (TransformedRadial)
  470. };
  471. }
  472. #define JUCE_PERFORM_PIXEL_OP_LOOP(op) \
  473. { \
  474. const int destStride = destData.pixelStride; \
  475. do { dest->op; dest = addBytesToPointer (dest, destStride); } while (--width > 0); \
  476. }
  477. //==============================================================================
  478. /** Contains classes for filling edge tables with various fill types. */
  479. namespace EdgeTableFillers
  480. {
  481. /** Fills an edge-table with a solid colour. */
  482. template <class PixelType, bool replaceExisting = false>
  483. struct SolidColour
  484. {
  485. SolidColour (const Image::BitmapData& image, PixelARGB colour)
  486. : destData (image), sourceColour (colour)
  487. {
  488. if (sizeof (PixelType) == 3 && (size_t) destData.pixelStride == sizeof (PixelType))
  489. {
  490. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  491. && sourceColour.getGreen() == sourceColour.getBlue();
  492. filler[0].set (sourceColour);
  493. filler[1].set (sourceColour);
  494. filler[2].set (sourceColour);
  495. filler[3].set (sourceColour);
  496. }
  497. else
  498. {
  499. areRGBComponentsEqual = false;
  500. }
  501. }
  502. forcedinline void setEdgeTableYPos (int y) noexcept
  503. {
  504. linePixels = (PixelType*) destData.getLinePointer (y);
  505. }
  506. forcedinline void handleEdgeTablePixel (int x, int alphaLevel) const noexcept
  507. {
  508. if (replaceExisting)
  509. getPixel (x)->set (sourceColour);
  510. else
  511. getPixel (x)->blend (sourceColour, (uint32) alphaLevel);
  512. }
  513. forcedinline void handleEdgeTablePixelFull (int x) const noexcept
  514. {
  515. if (replaceExisting)
  516. getPixel (x)->set (sourceColour);
  517. else
  518. getPixel (x)->blend (sourceColour);
  519. }
  520. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const noexcept
  521. {
  522. auto p = sourceColour;
  523. p.multiplyAlpha (alphaLevel);
  524. auto* dest = getPixel (x);
  525. if (replaceExisting || p.getAlpha() >= 0xff)
  526. replaceLine (dest, p, width);
  527. else
  528. blendLine (dest, p, width);
  529. }
  530. forcedinline void handleEdgeTableLineFull (int x, int width) const noexcept
  531. {
  532. auto* dest = getPixel (x);
  533. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  534. replaceLine (dest, sourceColour, width);
  535. else
  536. blendLine (dest, sourceColour, width);
  537. }
  538. void handleEdgeTableRectangle (int x, int y, int width, int height, int alphaLevel) noexcept
  539. {
  540. auto p = sourceColour;
  541. p.multiplyAlpha (alphaLevel);
  542. setEdgeTableYPos (y);
  543. auto* dest = getPixel (x);
  544. if (replaceExisting || p.getAlpha() >= 0xff)
  545. {
  546. while (--height >= 0)
  547. {
  548. replaceLine (dest, p, width);
  549. dest = addBytesToPointer (dest, destData.lineStride);
  550. }
  551. }
  552. else
  553. {
  554. while (--height >= 0)
  555. {
  556. blendLine (dest, p, width);
  557. dest = addBytesToPointer (dest, destData.lineStride);
  558. }
  559. }
  560. }
  561. void handleEdgeTableRectangleFull (int x, int y, int width, int height) noexcept
  562. {
  563. handleEdgeTableRectangle (x, y, width, height, 255);
  564. }
  565. private:
  566. const Image::BitmapData& destData;
  567. PixelType* linePixels;
  568. PixelARGB sourceColour;
  569. PixelRGB filler[4];
  570. bool areRGBComponentsEqual;
  571. forcedinline PixelType* getPixel (int x) const noexcept
  572. {
  573. return addBytesToPointer (linePixels, x * destData.pixelStride);
  574. }
  575. inline void blendLine (PixelType* dest, PixelARGB colour, int width) const noexcept
  576. {
  577. JUCE_PERFORM_PIXEL_OP_LOOP (blend (colour))
  578. }
  579. forcedinline void replaceLine (PixelRGB* dest, PixelARGB colour, int width) const noexcept
  580. {
  581. if ((size_t) destData.pixelStride == sizeof (*dest))
  582. {
  583. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  584. {
  585. memset (dest, colour.getRed(), (size_t) width * 3);
  586. }
  587. else
  588. {
  589. if (width >> 5)
  590. {
  591. auto intFiller = reinterpret_cast<const int*> (filler);
  592. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  593. {
  594. dest->set (colour);
  595. ++dest;
  596. --width;
  597. }
  598. while (width > 4)
  599. {
  600. auto d = reinterpret_cast<int*> (dest);
  601. *d++ = intFiller[0];
  602. *d++ = intFiller[1];
  603. *d++ = intFiller[2];
  604. dest = reinterpret_cast<PixelRGB*> (d);
  605. width -= 4;
  606. }
  607. }
  608. while (--width >= 0)
  609. {
  610. dest->set (colour);
  611. ++dest;
  612. }
  613. }
  614. }
  615. else
  616. {
  617. JUCE_PERFORM_PIXEL_OP_LOOP (set (colour))
  618. }
  619. }
  620. forcedinline void replaceLine (PixelAlpha* dest, const PixelARGB colour, int width) const noexcept
  621. {
  622. if ((size_t) destData.pixelStride == sizeof (*dest))
  623. memset (dest, colour.getAlpha(), (size_t) width);
  624. else
  625. JUCE_PERFORM_PIXEL_OP_LOOP (setAlpha (colour.getAlpha()))
  626. }
  627. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB colour, int width) const noexcept
  628. {
  629. JUCE_PERFORM_PIXEL_OP_LOOP (set (colour))
  630. }
  631. JUCE_DECLARE_NON_COPYABLE (SolidColour)
  632. };
  633. //==============================================================================
  634. /** Fills an edge-table with a gradient. */
  635. template <class PixelType, class GradientType>
  636. struct Gradient : public GradientType
  637. {
  638. Gradient (const Image::BitmapData& dest, const ColourGradient& gradient, const AffineTransform& transform,
  639. const PixelARGB* colours, int numColours)
  640. : GradientType (gradient, transform, colours, numColours - 1),
  641. destData (dest)
  642. {
  643. }
  644. forcedinline void setEdgeTableYPos (int y) noexcept
  645. {
  646. linePixels = (PixelType*) destData.getLinePointer (y);
  647. GradientType::setY (y);
  648. }
  649. forcedinline void handleEdgeTablePixel (int x, int alphaLevel) const noexcept
  650. {
  651. getPixel (x)->blend (GradientType::getPixel (x), (uint32) alphaLevel);
  652. }
  653. forcedinline void handleEdgeTablePixelFull (int x) const noexcept
  654. {
  655. getPixel (x)->blend (GradientType::getPixel (x));
  656. }
  657. void handleEdgeTableLine (int x, int width, int alphaLevel) const noexcept
  658. {
  659. auto* dest = getPixel (x);
  660. if (alphaLevel < 0xff)
  661. JUCE_PERFORM_PIXEL_OP_LOOP (blend (GradientType::getPixel (x++), (uint32) alphaLevel))
  662. else
  663. JUCE_PERFORM_PIXEL_OP_LOOP (blend (GradientType::getPixel (x++)))
  664. }
  665. void handleEdgeTableLineFull (int x, int width) const noexcept
  666. {
  667. auto* dest = getPixel (x);
  668. JUCE_PERFORM_PIXEL_OP_LOOP (blend (GradientType::getPixel (x++)))
  669. }
  670. void handleEdgeTableRectangle (int x, int y, int width, int height, int alphaLevel) noexcept
  671. {
  672. while (--height >= 0)
  673. {
  674. setEdgeTableYPos (y++);
  675. handleEdgeTableLine (x, width, alphaLevel);
  676. }
  677. }
  678. void handleEdgeTableRectangleFull (int x, int y, int width, int height) noexcept
  679. {
  680. while (--height >= 0)
  681. {
  682. setEdgeTableYPos (y++);
  683. handleEdgeTableLineFull (x, width);
  684. }
  685. }
  686. private:
  687. const Image::BitmapData& destData;
  688. PixelType* linePixels;
  689. forcedinline PixelType* getPixel (int x) const noexcept
  690. {
  691. return addBytesToPointer (linePixels, x * destData.pixelStride);
  692. }
  693. JUCE_DECLARE_NON_COPYABLE (Gradient)
  694. };
  695. //==============================================================================
  696. /** Fills an edge-table with a non-transformed image. */
  697. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  698. struct ImageFill
  699. {
  700. ImageFill (const Image::BitmapData& dest, const Image::BitmapData& src, int alpha, int x, int y)
  701. : destData (dest),
  702. srcData (src),
  703. extraAlpha (alpha + 1),
  704. xOffset (repeatPattern ? negativeAwareModulo (x, src.width) - src.width : x),
  705. yOffset (repeatPattern ? negativeAwareModulo (y, src.height) - src.height : y)
  706. {
  707. }
  708. forcedinline void setEdgeTableYPos (int y) noexcept
  709. {
  710. linePixels = (DestPixelType*) destData.getLinePointer (y);
  711. y -= yOffset;
  712. if (repeatPattern)
  713. {
  714. jassert (y >= 0);
  715. y %= srcData.height;
  716. }
  717. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  718. }
  719. forcedinline void handleEdgeTablePixel (int x, int alphaLevel) const noexcept
  720. {
  721. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  722. getDestPixel (x)->blend (*getSrcPixel (repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)), (uint32) alphaLevel);
  723. }
  724. forcedinline void handleEdgeTablePixelFull (int x) const noexcept
  725. {
  726. getDestPixel (x)->blend (*getSrcPixel (repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)), (uint32) extraAlpha);
  727. }
  728. void handleEdgeTableLine (int x, int width, int alphaLevel) const noexcept
  729. {
  730. auto* dest = getDestPixel (x);
  731. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  732. x -= xOffset;
  733. if (repeatPattern)
  734. {
  735. if (alphaLevel < 0xfe)
  736. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*getSrcPixel (x++ % srcData.width), (uint32) alphaLevel))
  737. else
  738. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*getSrcPixel (x++ % srcData.width)))
  739. }
  740. else
  741. {
  742. jassert (x >= 0 && x + width <= srcData.width);
  743. if (alphaLevel < 0xfe)
  744. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*getSrcPixel (x++), (uint32) alphaLevel))
  745. else
  746. copyRow (dest, getSrcPixel (x), width);
  747. }
  748. }
  749. void handleEdgeTableLineFull (int x, int width) const noexcept
  750. {
  751. auto* dest = getDestPixel (x);
  752. x -= xOffset;
  753. if (repeatPattern)
  754. {
  755. if (extraAlpha < 0xfe)
  756. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*getSrcPixel (x++ % srcData.width), (uint32) extraAlpha))
  757. else
  758. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*getSrcPixel (x++ % srcData.width)))
  759. }
  760. else
  761. {
  762. jassert (x >= 0 && x + width <= srcData.width);
  763. if (extraAlpha < 0xfe)
  764. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*getSrcPixel (x++), (uint32) extraAlpha))
  765. else
  766. copyRow (dest, getSrcPixel (x), width);
  767. }
  768. }
  769. void handleEdgeTableRectangle (int x, int y, int width, int height, int alphaLevel) noexcept
  770. {
  771. while (--height >= 0)
  772. {
  773. setEdgeTableYPos (y++);
  774. handleEdgeTableLine (x, width, alphaLevel);
  775. }
  776. }
  777. void handleEdgeTableRectangleFull (int x, int y, int width, int height) noexcept
  778. {
  779. while (--height >= 0)
  780. {
  781. setEdgeTableYPos (y++);
  782. handleEdgeTableLineFull (x, width);
  783. }
  784. }
  785. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  786. {
  787. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  788. auto* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  789. auto* mask = (uint8*) (s + x - xOffset);
  790. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  791. mask += PixelARGB::indexA;
  792. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  793. }
  794. private:
  795. const Image::BitmapData& destData;
  796. const Image::BitmapData& srcData;
  797. const int extraAlpha, xOffset, yOffset;
  798. DestPixelType* linePixels;
  799. SrcPixelType* sourceLineStart;
  800. forcedinline DestPixelType* getDestPixel (int x) const noexcept
  801. {
  802. return addBytesToPointer (linePixels, x * destData.pixelStride);
  803. }
  804. forcedinline SrcPixelType const* getSrcPixel (int x) const noexcept
  805. {
  806. return addBytesToPointer (sourceLineStart, x * srcData.pixelStride);
  807. }
  808. forcedinline void copyRow (DestPixelType* dest, SrcPixelType const* src, int width) const noexcept
  809. {
  810. auto destStride = destData.pixelStride;
  811. auto srcStride = srcData.pixelStride;
  812. if (destStride == srcStride
  813. && srcData.pixelFormat == Image::RGB
  814. && destData.pixelFormat == Image::RGB)
  815. {
  816. memcpy (dest, src, (size_t) (width * srcStride));
  817. }
  818. else
  819. {
  820. do
  821. {
  822. dest->blend (*src);
  823. dest = addBytesToPointer (dest, destStride);
  824. src = addBytesToPointer (src, srcStride);
  825. } while (--width > 0);
  826. }
  827. }
  828. JUCE_DECLARE_NON_COPYABLE (ImageFill)
  829. };
  830. //==============================================================================
  831. /** Fills an edge-table with a transformed image. */
  832. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  833. struct TransformedImageFill
  834. {
  835. TransformedImageFill (const Image::BitmapData& dest, const Image::BitmapData& src,
  836. const AffineTransform& transform, int alpha, Graphics::ResamplingQuality q)
  837. : interpolator (transform,
  838. q != Graphics::lowResamplingQuality ? 0.5f : 0.0f,
  839. q != Graphics::lowResamplingQuality ? -128 : 0),
  840. destData (dest),
  841. srcData (src),
  842. extraAlpha (alpha + 1),
  843. quality (q),
  844. maxX (src.width - 1),
  845. maxY (src.height - 1)
  846. {
  847. scratchBuffer.malloc (scratchSize);
  848. }
  849. forcedinline void setEdgeTableYPos (int newY) noexcept
  850. {
  851. currentY = newY;
  852. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  853. }
  854. forcedinline void handleEdgeTablePixel (int x, int alphaLevel) noexcept
  855. {
  856. SrcPixelType p;
  857. generate (&p, x, 1);
  858. getDestPixel (x)->blend (p, (uint32) (alphaLevel * extraAlpha) >> 8);
  859. }
  860. forcedinline void handleEdgeTablePixelFull (int x) noexcept
  861. {
  862. SrcPixelType p;
  863. generate (&p, x, 1);
  864. getDestPixel (x)->blend (p, (uint32) extraAlpha);
  865. }
  866. void handleEdgeTableLine (int x, int width, int alphaLevel) noexcept
  867. {
  868. if (width > (int) scratchSize)
  869. {
  870. scratchSize = (size_t) width;
  871. scratchBuffer.malloc (scratchSize);
  872. }
  873. SrcPixelType* span = scratchBuffer;
  874. generate (span, x, width);
  875. auto* dest = getDestPixel (x);
  876. alphaLevel *= extraAlpha;
  877. alphaLevel >>= 8;
  878. if (alphaLevel < 0xfe)
  879. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*span++, (uint32) alphaLevel))
  880. else
  881. JUCE_PERFORM_PIXEL_OP_LOOP (blend (*span++))
  882. }
  883. forcedinline void handleEdgeTableLineFull (int x, int width) noexcept
  884. {
  885. handleEdgeTableLine (x, width, 255);
  886. }
  887. void handleEdgeTableRectangle (int x, int y, int width, int height, int alphaLevel) noexcept
  888. {
  889. while (--height >= 0)
  890. {
  891. setEdgeTableYPos (y++);
  892. handleEdgeTableLine (x, width, alphaLevel);
  893. }
  894. }
  895. void handleEdgeTableRectangleFull (int x, int y, int width, int height) noexcept
  896. {
  897. while (--height >= 0)
  898. {
  899. setEdgeTableYPos (y++);
  900. handleEdgeTableLineFull (x, width);
  901. }
  902. }
  903. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  904. {
  905. if (width > (int) scratchSize)
  906. {
  907. scratchSize = (size_t) width;
  908. scratchBuffer.malloc (scratchSize);
  909. }
  910. currentY = y;
  911. generate (scratchBuffer.get(), x, width);
  912. et.clipLineToMask (x, y,
  913. reinterpret_cast<uint8*> (scratchBuffer.get()) + SrcPixelType::indexA,
  914. sizeof (SrcPixelType), width);
  915. }
  916. private:
  917. forcedinline DestPixelType* getDestPixel (int x) const noexcept
  918. {
  919. return addBytesToPointer (linePixels, x * destData.pixelStride);
  920. }
  921. //==============================================================================
  922. template <class PixelType>
  923. void generate (PixelType* dest, int x, int numPixels) noexcept
  924. {
  925. this->interpolator.setStartOfLine ((float) x, (float) currentY, numPixels);
  926. do
  927. {
  928. int hiResX, hiResY;
  929. this->interpolator.next (hiResX, hiResY);
  930. int loResX = hiResX >> 8;
  931. int loResY = hiResY >> 8;
  932. if (repeatPattern)
  933. {
  934. loResX = negativeAwareModulo (loResX, srcData.width);
  935. loResY = negativeAwareModulo (loResY, srcData.height);
  936. }
  937. if (quality != Graphics::lowResamplingQuality)
  938. {
  939. if (isPositiveAndBelow (loResX, maxX))
  940. {
  941. if (isPositiveAndBelow (loResY, maxY))
  942. {
  943. // In the centre of the image..
  944. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  945. hiResX & 255, hiResY & 255);
  946. ++dest;
  947. continue;
  948. }
  949. if (! repeatPattern)
  950. {
  951. // At a top or bottom edge..
  952. if (loResY < 0)
  953. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255);
  954. else
  955. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255);
  956. ++dest;
  957. continue;
  958. }
  959. }
  960. else
  961. {
  962. if (isPositiveAndBelow (loResY, maxY) && ! repeatPattern)
  963. {
  964. // At a left or right hand edge..
  965. if (loResX < 0)
  966. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255);
  967. else
  968. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255);
  969. ++dest;
  970. continue;
  971. }
  972. }
  973. }
  974. if (! repeatPattern)
  975. {
  976. if (loResX < 0) loResX = 0;
  977. if (loResY < 0) loResY = 0;
  978. if (loResX > maxX) loResX = maxX;
  979. if (loResY > maxY) loResY = maxY;
  980. }
  981. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  982. ++dest;
  983. } while (--numPixels > 0);
  984. }
  985. //==============================================================================
  986. void render4PixelAverage (PixelARGB* dest, const uint8* src, int subPixelX, int subPixelY) noexcept
  987. {
  988. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  989. auto weight = (uint32) ((256 - subPixelX) * (256 - subPixelY));
  990. c[0] += weight * src[0];
  991. c[1] += weight * src[1];
  992. c[2] += weight * src[2];
  993. c[3] += weight * src[3];
  994. src += this->srcData.pixelStride;
  995. weight = (uint32) (subPixelX * (256 - subPixelY));
  996. c[0] += weight * src[0];
  997. c[1] += weight * src[1];
  998. c[2] += weight * src[2];
  999. c[3] += weight * src[3];
  1000. src += this->srcData.lineStride;
  1001. weight = (uint32) (subPixelX * subPixelY);
  1002. c[0] += weight * src[0];
  1003. c[1] += weight * src[1];
  1004. c[2] += weight * src[2];
  1005. c[3] += weight * src[3];
  1006. src -= this->srcData.pixelStride;
  1007. weight = (uint32) ((256 - subPixelX) * subPixelY);
  1008. c[0] += weight * src[0];
  1009. c[1] += weight * src[1];
  1010. c[2] += weight * src[2];
  1011. c[3] += weight * src[3];
  1012. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  1013. (uint8) (c[PixelARGB::indexR] >> 16),
  1014. (uint8) (c[PixelARGB::indexG] >> 16),
  1015. (uint8) (c[PixelARGB::indexB] >> 16));
  1016. }
  1017. void render2PixelAverageX (PixelARGB* dest, const uint8* src, uint32 subPixelX) noexcept
  1018. {
  1019. uint32 c[4] = { 128, 128, 128, 128 };
  1020. uint32 weight = 256 - subPixelX;
  1021. c[0] += weight * src[0];
  1022. c[1] += weight * src[1];
  1023. c[2] += weight * src[2];
  1024. c[3] += weight * src[3];
  1025. src += this->srcData.pixelStride;
  1026. weight = subPixelX;
  1027. c[0] += weight * src[0];
  1028. c[1] += weight * src[1];
  1029. c[2] += weight * src[2];
  1030. c[3] += weight * src[3];
  1031. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 8),
  1032. (uint8) (c[PixelARGB::indexR] >> 8),
  1033. (uint8) (c[PixelARGB::indexG] >> 8),
  1034. (uint8) (c[PixelARGB::indexB] >> 8));
  1035. }
  1036. void render2PixelAverageY (PixelARGB* dest, const uint8* src, uint32 subPixelY) noexcept
  1037. {
  1038. uint32 c[4] = { 128, 128, 128, 128 };
  1039. uint32 weight = 256 - subPixelY;
  1040. c[0] += weight * src[0];
  1041. c[1] += weight * src[1];
  1042. c[2] += weight * src[2];
  1043. c[3] += weight * src[3];
  1044. src += this->srcData.lineStride;
  1045. weight = subPixelY;
  1046. c[0] += weight * src[0];
  1047. c[1] += weight * src[1];
  1048. c[2] += weight * src[2];
  1049. c[3] += weight * src[3];
  1050. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 8),
  1051. (uint8) (c[PixelARGB::indexR] >> 8),
  1052. (uint8) (c[PixelARGB::indexG] >> 8),
  1053. (uint8) (c[PixelARGB::indexB] >> 8));
  1054. }
  1055. //==============================================================================
  1056. void render4PixelAverage (PixelRGB* dest, const uint8* src, uint32 subPixelX, uint32 subPixelY) noexcept
  1057. {
  1058. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  1059. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  1060. c[0] += weight * src[0];
  1061. c[1] += weight * src[1];
  1062. c[2] += weight * src[2];
  1063. src += this->srcData.pixelStride;
  1064. weight = subPixelX * (256 - subPixelY);
  1065. c[0] += weight * src[0];
  1066. c[1] += weight * src[1];
  1067. c[2] += weight * src[2];
  1068. src += this->srcData.lineStride;
  1069. weight = subPixelX * subPixelY;
  1070. c[0] += weight * src[0];
  1071. c[1] += weight * src[1];
  1072. c[2] += weight * src[2];
  1073. src -= this->srcData.pixelStride;
  1074. weight = (256 - subPixelX) * subPixelY;
  1075. c[0] += weight * src[0];
  1076. c[1] += weight * src[1];
  1077. c[2] += weight * src[2];
  1078. dest->setARGB ((uint8) 255,
  1079. (uint8) (c[PixelRGB::indexR] >> 16),
  1080. (uint8) (c[PixelRGB::indexG] >> 16),
  1081. (uint8) (c[PixelRGB::indexB] >> 16));
  1082. }
  1083. void render2PixelAverageX (PixelRGB* dest, const uint8* src, uint32 subPixelX) noexcept
  1084. {
  1085. uint32 c[3] = { 128, 128, 128 };
  1086. const uint32 weight = 256 - subPixelX;
  1087. c[0] += weight * src[0];
  1088. c[1] += weight * src[1];
  1089. c[2] += weight * src[2];
  1090. src += this->srcData.pixelStride;
  1091. c[0] += subPixelX * src[0];
  1092. c[1] += subPixelX * src[1];
  1093. c[2] += subPixelX * src[2];
  1094. dest->setARGB ((uint8) 255,
  1095. (uint8) (c[PixelRGB::indexR] >> 8),
  1096. (uint8) (c[PixelRGB::indexG] >> 8),
  1097. (uint8) (c[PixelRGB::indexB] >> 8));
  1098. }
  1099. void render2PixelAverageY (PixelRGB* dest, const uint8* src, uint32 subPixelY) noexcept
  1100. {
  1101. uint32 c[3] = { 128, 128, 128 };
  1102. const uint32 weight = 256 - subPixelY;
  1103. c[0] += weight * src[0];
  1104. c[1] += weight * src[1];
  1105. c[2] += weight * src[2];
  1106. src += this->srcData.lineStride;
  1107. c[0] += subPixelY * src[0];
  1108. c[1] += subPixelY * src[1];
  1109. c[2] += subPixelY * src[2];
  1110. dest->setARGB ((uint8) 255,
  1111. (uint8) (c[PixelRGB::indexR] >> 8),
  1112. (uint8) (c[PixelRGB::indexG] >> 8),
  1113. (uint8) (c[PixelRGB::indexB] >> 8));
  1114. }
  1115. //==============================================================================
  1116. void render4PixelAverage (PixelAlpha* dest, const uint8* src, uint32 subPixelX, uint32 subPixelY) noexcept
  1117. {
  1118. uint32 c = 256 * 128;
  1119. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  1120. src += this->srcData.pixelStride;
  1121. c += src[0] * (subPixelX * (256 - subPixelY));
  1122. src += this->srcData.lineStride;
  1123. c += src[0] * (subPixelX * subPixelY);
  1124. src -= this->srcData.pixelStride;
  1125. c += src[0] * ((256 - subPixelX) * subPixelY);
  1126. *((uint8*) dest) = (uint8) (c >> 16);
  1127. }
  1128. void render2PixelAverageX (PixelAlpha* dest, const uint8* src, uint32 subPixelX) noexcept
  1129. {
  1130. uint32 c = 128;
  1131. c += src[0] * (256 - subPixelX);
  1132. src += this->srcData.pixelStride;
  1133. c += src[0] * subPixelX;
  1134. *((uint8*) dest) = (uint8) (c >> 8);
  1135. }
  1136. void render2PixelAverageY (PixelAlpha* dest, const uint8* src, uint32 subPixelY) noexcept
  1137. {
  1138. uint32 c = 128;
  1139. c += src[0] * (256 - subPixelY);
  1140. src += this->srcData.lineStride;
  1141. c += src[0] * subPixelY;
  1142. *((uint8*) dest) = (uint8) (c >> 8);
  1143. }
  1144. //==============================================================================
  1145. struct TransformedImageSpanInterpolator
  1146. {
  1147. TransformedImageSpanInterpolator (const AffineTransform& transform, float offsetFloat, int offsetInt) noexcept
  1148. : inverseTransform (transform.inverted()),
  1149. pixelOffset (offsetFloat), pixelOffsetInt (offsetInt)
  1150. {}
  1151. void setStartOfLine (float sx, float sy, int numPixels) noexcept
  1152. {
  1153. jassert (numPixels > 0);
  1154. sx += pixelOffset;
  1155. sy += pixelOffset;
  1156. auto x1 = sx, y1 = sy;
  1157. sx += (float) numPixels;
  1158. inverseTransform.transformPoints (x1, y1, sx, sy);
  1159. xBresenham.set ((int) (x1 * 256.0f), (int) (sx * 256.0f), numPixels, pixelOffsetInt);
  1160. yBresenham.set ((int) (y1 * 256.0f), (int) (sy * 256.0f), numPixels, pixelOffsetInt);
  1161. }
  1162. void next (int& px, int& py) noexcept
  1163. {
  1164. px = xBresenham.n; xBresenham.stepToNext();
  1165. py = yBresenham.n; yBresenham.stepToNext();
  1166. }
  1167. private:
  1168. struct BresenhamInterpolator
  1169. {
  1170. BresenhamInterpolator() noexcept {}
  1171. void set (int n1, int n2, int steps, int offsetInt) noexcept
  1172. {
  1173. numSteps = steps;
  1174. step = (n2 - n1) / numSteps;
  1175. remainder = modulo = (n2 - n1) % numSteps;
  1176. n = n1 + offsetInt;
  1177. if (modulo <= 0)
  1178. {
  1179. modulo += numSteps;
  1180. remainder += numSteps;
  1181. --step;
  1182. }
  1183. modulo -= numSteps;
  1184. }
  1185. forcedinline void stepToNext() noexcept
  1186. {
  1187. modulo += remainder;
  1188. n += step;
  1189. if (modulo > 0)
  1190. {
  1191. modulo -= numSteps;
  1192. ++n;
  1193. }
  1194. }
  1195. int n;
  1196. private:
  1197. int numSteps, step, modulo, remainder;
  1198. };
  1199. const AffineTransform inverseTransform;
  1200. BresenhamInterpolator xBresenham, yBresenham;
  1201. const float pixelOffset;
  1202. const int pixelOffsetInt;
  1203. JUCE_DECLARE_NON_COPYABLE (TransformedImageSpanInterpolator)
  1204. };
  1205. //==============================================================================
  1206. TransformedImageSpanInterpolator interpolator;
  1207. const Image::BitmapData& destData;
  1208. const Image::BitmapData& srcData;
  1209. const int extraAlpha;
  1210. const Graphics::ResamplingQuality quality;
  1211. const int maxX, maxY;
  1212. int currentY;
  1213. DestPixelType* linePixels;
  1214. HeapBlock<SrcPixelType> scratchBuffer;
  1215. size_t scratchSize = 2048;
  1216. JUCE_DECLARE_NON_COPYABLE (TransformedImageFill)
  1217. };
  1218. //==============================================================================
  1219. template <class Iterator>
  1220. void renderImageTransformed (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  1221. int alpha, const AffineTransform& transform, Graphics::ResamplingQuality quality, bool tiledFill)
  1222. {
  1223. switch (destData.pixelFormat)
  1224. {
  1225. case Image::ARGB:
  1226. switch (srcData.pixelFormat)
  1227. {
  1228. case Image::ARGB:
  1229. if (tiledFill) { TransformedImageFill<PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1230. else { TransformedImageFill<PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1231. break;
  1232. case Image::RGB:
  1233. if (tiledFill) { TransformedImageFill<PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1234. else { TransformedImageFill<PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1235. break;
  1236. default:
  1237. if (tiledFill) { TransformedImageFill<PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1238. else { TransformedImageFill<PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1239. break;
  1240. }
  1241. break;
  1242. case Image::RGB:
  1243. switch (srcData.pixelFormat)
  1244. {
  1245. case Image::ARGB:
  1246. if (tiledFill) { TransformedImageFill<PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1247. else { TransformedImageFill<PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1248. break;
  1249. case Image::RGB:
  1250. if (tiledFill) { TransformedImageFill<PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1251. else { TransformedImageFill<PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1252. break;
  1253. default:
  1254. if (tiledFill) { TransformedImageFill<PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1255. else { TransformedImageFill<PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1256. break;
  1257. }
  1258. break;
  1259. default:
  1260. switch (srcData.pixelFormat)
  1261. {
  1262. case Image::ARGB:
  1263. if (tiledFill) { TransformedImageFill<PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1264. else { TransformedImageFill<PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1265. break;
  1266. case Image::RGB:
  1267. if (tiledFill) { TransformedImageFill<PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1268. else { TransformedImageFill<PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1269. break;
  1270. default:
  1271. if (tiledFill) { TransformedImageFill<PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1272. else { TransformedImageFill<PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, quality); iter.iterate (r); }
  1273. break;
  1274. }
  1275. break;
  1276. }
  1277. }
  1278. template <class Iterator>
  1279. void renderImageUntransformed (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, int alpha, int x, int y, bool tiledFill)
  1280. {
  1281. switch (destData.pixelFormat)
  1282. {
  1283. case Image::ARGB:
  1284. switch (srcData.pixelFormat)
  1285. {
  1286. case Image::ARGB:
  1287. if (tiledFill) { ImageFill<PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1288. else { ImageFill<PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1289. break;
  1290. case Image::RGB:
  1291. if (tiledFill) { ImageFill<PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1292. else { ImageFill<PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1293. break;
  1294. default:
  1295. if (tiledFill) { ImageFill<PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1296. else { ImageFill<PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1297. break;
  1298. }
  1299. break;
  1300. case Image::RGB:
  1301. switch (srcData.pixelFormat)
  1302. {
  1303. case Image::ARGB:
  1304. if (tiledFill) { ImageFill<PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1305. else { ImageFill<PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1306. break;
  1307. case Image::RGB:
  1308. if (tiledFill) { ImageFill<PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1309. else { ImageFill<PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1310. break;
  1311. default:
  1312. if (tiledFill) { ImageFill<PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1313. else { ImageFill<PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1314. break;
  1315. }
  1316. break;
  1317. default:
  1318. switch (srcData.pixelFormat)
  1319. {
  1320. case Image::ARGB:
  1321. if (tiledFill) { ImageFill<PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1322. else { ImageFill<PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1323. break;
  1324. case Image::RGB:
  1325. if (tiledFill) { ImageFill<PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1326. else { ImageFill<PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1327. break;
  1328. default:
  1329. if (tiledFill) { ImageFill<PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1330. else { ImageFill<PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  1331. break;
  1332. }
  1333. break;
  1334. }
  1335. }
  1336. template <class Iterator, class DestPixelType>
  1337. void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, PixelARGB fillColour, bool replaceContents, DestPixelType*)
  1338. {
  1339. if (replaceContents)
  1340. {
  1341. EdgeTableFillers::SolidColour<DestPixelType, true> r (destData, fillColour);
  1342. iter.iterate (r);
  1343. }
  1344. else
  1345. {
  1346. EdgeTableFillers::SolidColour<DestPixelType, false> r (destData, fillColour);
  1347. iter.iterate (r);
  1348. }
  1349. }
  1350. template <class Iterator, class DestPixelType>
  1351. void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  1352. const PixelARGB* lookupTable, int numLookupEntries, bool isIdentity, DestPixelType*)
  1353. {
  1354. if (g.isRadial)
  1355. {
  1356. if (isIdentity)
  1357. {
  1358. EdgeTableFillers::Gradient<DestPixelType, GradientPixelIterators::Radial> renderer (destData, g, transform, lookupTable, numLookupEntries);
  1359. iter.iterate (renderer);
  1360. }
  1361. else
  1362. {
  1363. EdgeTableFillers::Gradient<DestPixelType, GradientPixelIterators::TransformedRadial> renderer (destData, g, transform, lookupTable, numLookupEntries);
  1364. iter.iterate (renderer);
  1365. }
  1366. }
  1367. else
  1368. {
  1369. EdgeTableFillers::Gradient<DestPixelType, GradientPixelIterators::Linear> renderer (destData, g, transform, lookupTable, numLookupEntries);
  1370. iter.iterate (renderer);
  1371. }
  1372. }
  1373. }
  1374. //==============================================================================
  1375. template <class SavedStateType>
  1376. struct ClipRegions
  1377. {
  1378. struct Base : public SingleThreadedReferenceCountedObject
  1379. {
  1380. Base() {}
  1381. virtual ~Base() {}
  1382. using Ptr = ReferenceCountedObjectPtr<Base>;
  1383. virtual Ptr clone() const = 0;
  1384. virtual Ptr applyClipTo (const Ptr& target) const = 0;
  1385. virtual Ptr clipToRectangle (Rectangle<int>) = 0;
  1386. virtual Ptr clipToRectangleList (const RectangleList<int>&) = 0;
  1387. virtual Ptr excludeClipRectangle (Rectangle<int>) = 0;
  1388. virtual Ptr clipToPath (const Path&, const AffineTransform&) = 0;
  1389. virtual Ptr clipToEdgeTable (const EdgeTable&) = 0;
  1390. virtual Ptr clipToImageAlpha (const Image&, const AffineTransform&, Graphics::ResamplingQuality) = 0;
  1391. virtual void translate (Point<int> delta) = 0;
  1392. virtual bool clipRegionIntersects (Rectangle<int>) const = 0;
  1393. virtual Rectangle<int> getClipBounds() const = 0;
  1394. virtual void fillRectWithColour (SavedStateType&, Rectangle<int>, PixelARGB colour, bool replaceContents) const = 0;
  1395. virtual void fillRectWithColour (SavedStateType&, Rectangle<float>, PixelARGB colour) const = 0;
  1396. virtual void fillAllWithColour (SavedStateType&, PixelARGB colour, bool replaceContents) const = 0;
  1397. virtual void fillAllWithGradient (SavedStateType&, ColourGradient&, const AffineTransform&, bool isIdentity) const = 0;
  1398. virtual void renderImageTransformed (SavedStateType&, const Image&, int alpha, const AffineTransform&, Graphics::ResamplingQuality, bool tiledFill) const = 0;
  1399. virtual void renderImageUntransformed (SavedStateType&, const Image&, int alpha, int x, int y, bool tiledFill) const = 0;
  1400. };
  1401. //==============================================================================
  1402. struct EdgeTableRegion : public Base
  1403. {
  1404. EdgeTableRegion (const EdgeTable& e) : edgeTable (e) {}
  1405. EdgeTableRegion (Rectangle<int> r) : edgeTable (r) {}
  1406. EdgeTableRegion (Rectangle<float> r) : edgeTable (r) {}
  1407. EdgeTableRegion (const RectangleList<int>& r) : edgeTable (r) {}
  1408. EdgeTableRegion (const RectangleList<float>& r) : edgeTable (r) {}
  1409. EdgeTableRegion (Rectangle<int> bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  1410. EdgeTableRegion (const EdgeTableRegion& other) : Base(), edgeTable (other.edgeTable) {}
  1411. EdgeTableRegion& operator= (const EdgeTableRegion&) = delete;
  1412. using Ptr = typename Base::Ptr;
  1413. Ptr clone() const override { return *new EdgeTableRegion (*this); }
  1414. Ptr applyClipTo (const Ptr& target) const override { return target->clipToEdgeTable (edgeTable); }
  1415. Ptr clipToRectangle (Rectangle<int> r) override
  1416. {
  1417. edgeTable.clipToRectangle (r);
  1418. return edgeTable.isEmpty() ? Ptr() : Ptr (*this);
  1419. }
  1420. Ptr clipToRectangleList (const RectangleList<int>& r) override
  1421. {
  1422. RectangleList<int> inverse (edgeTable.getMaximumBounds());
  1423. if (inverse.subtract (r))
  1424. for (auto& i : inverse)
  1425. edgeTable.excludeRectangle (i);
  1426. return edgeTable.isEmpty() ? Ptr() : Ptr (*this);
  1427. }
  1428. Ptr excludeClipRectangle (Rectangle<int> r) override
  1429. {
  1430. edgeTable.excludeRectangle (r);
  1431. return edgeTable.isEmpty() ? Ptr() : Ptr (*this);
  1432. }
  1433. Ptr clipToPath (const Path& p, const AffineTransform& transform) override
  1434. {
  1435. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  1436. edgeTable.clipToEdgeTable (et);
  1437. return edgeTable.isEmpty() ? Ptr() : Ptr (*this);
  1438. }
  1439. Ptr clipToEdgeTable (const EdgeTable& et) override
  1440. {
  1441. edgeTable.clipToEdgeTable (et);
  1442. return edgeTable.isEmpty() ? Ptr() : Ptr (*this);
  1443. }
  1444. Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, Graphics::ResamplingQuality quality) override
  1445. {
  1446. const Image::BitmapData srcData (image, Image::BitmapData::readOnly);
  1447. if (transform.isOnlyTranslation())
  1448. {
  1449. // If our translation doesn't involve any distortion, just use a simple blit..
  1450. auto tx = (int) (transform.getTranslationX() * 256.0f);
  1451. auto ty = (int) (transform.getTranslationY() * 256.0f);
  1452. if (quality == Graphics::lowResamplingQuality || ((tx | ty) & 224) == 0)
  1453. {
  1454. auto imageX = ((tx + 128) >> 8);
  1455. auto imageY = ((ty + 128) >> 8);
  1456. if (image.getFormat() == Image::ARGB)
  1457. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  1458. else
  1459. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  1460. return edgeTable.isEmpty() ? Ptr() : Ptr (*this);
  1461. }
  1462. }
  1463. if (transform.isSingularity())
  1464. return Ptr();
  1465. {
  1466. Path p;
  1467. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  1468. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  1469. edgeTable.clipToEdgeTable (et2);
  1470. }
  1471. if (! edgeTable.isEmpty())
  1472. {
  1473. if (image.getFormat() == Image::ARGB)
  1474. transformedClipImage (srcData, transform, quality, (PixelARGB*) 0);
  1475. else
  1476. transformedClipImage (srcData, transform, quality, (PixelAlpha*) 0);
  1477. }
  1478. return edgeTable.isEmpty() ? Ptr() : Ptr (*this);
  1479. }
  1480. void translate (Point<int> delta) override
  1481. {
  1482. edgeTable.translate ((float) delta.x, delta.y);
  1483. }
  1484. bool clipRegionIntersects (Rectangle<int> r) const override
  1485. {
  1486. return edgeTable.getMaximumBounds().intersects (r);
  1487. }
  1488. Rectangle<int> getClipBounds() const override
  1489. {
  1490. return edgeTable.getMaximumBounds();
  1491. }
  1492. void fillRectWithColour (SavedStateType& state, Rectangle<int> area, PixelARGB colour, bool replaceContents) const override
  1493. {
  1494. auto totalClip = edgeTable.getMaximumBounds();
  1495. auto clipped = totalClip.getIntersection (area);
  1496. if (! clipped.isEmpty())
  1497. {
  1498. EdgeTableRegion et (clipped);
  1499. et.edgeTable.clipToEdgeTable (edgeTable);
  1500. state.fillWithSolidColour (et.edgeTable, colour, replaceContents);
  1501. }
  1502. }
  1503. void fillRectWithColour (SavedStateType& state, Rectangle<float> area, PixelARGB colour) const override
  1504. {
  1505. auto totalClip = edgeTable.getMaximumBounds().toFloat();
  1506. auto clipped = totalClip.getIntersection (area);
  1507. if (! clipped.isEmpty())
  1508. {
  1509. EdgeTableRegion et (clipped);
  1510. et.edgeTable.clipToEdgeTable (edgeTable);
  1511. state.fillWithSolidColour (et.edgeTable, colour, false);
  1512. }
  1513. }
  1514. void fillAllWithColour (SavedStateType& state, PixelARGB colour, bool replaceContents) const override
  1515. {
  1516. state.fillWithSolidColour (edgeTable, colour, replaceContents);
  1517. }
  1518. void fillAllWithGradient (SavedStateType& state, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const override
  1519. {
  1520. state.fillWithGradient (edgeTable, gradient, transform, isIdentity);
  1521. }
  1522. void renderImageTransformed (SavedStateType& state, const Image& src, int alpha, const AffineTransform& transform, Graphics::ResamplingQuality quality, bool tiledFill) const override
  1523. {
  1524. state.renderImageTransformed (edgeTable, src, alpha, transform, quality, tiledFill);
  1525. }
  1526. void renderImageUntransformed (SavedStateType& state, const Image& src, int alpha, int x, int y, bool tiledFill) const override
  1527. {
  1528. state.renderImageUntransformed (edgeTable, src, alpha, x, y, tiledFill);
  1529. }
  1530. EdgeTable edgeTable;
  1531. private:
  1532. template <class SrcPixelType>
  1533. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, Graphics::ResamplingQuality quality, const SrcPixelType*)
  1534. {
  1535. EdgeTableFillers::TransformedImageFill<SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, quality);
  1536. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  1537. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  1538. edgeTable.getMaximumBounds().getWidth());
  1539. }
  1540. template <class SrcPixelType>
  1541. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  1542. {
  1543. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  1544. edgeTable.clipToRectangle (r);
  1545. EdgeTableFillers::ImageFill<SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  1546. for (int y = 0; y < r.getHeight(); ++y)
  1547. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  1548. }
  1549. };
  1550. //==============================================================================
  1551. class RectangleListRegion : public Base
  1552. {
  1553. public:
  1554. RectangleListRegion (Rectangle<int> r) : clip (r) {}
  1555. RectangleListRegion (const RectangleList<int>& r) : clip (r) {}
  1556. RectangleListRegion (const RectangleListRegion& other) : Base(), clip (other.clip) {}
  1557. using Ptr = typename Base::Ptr;
  1558. Ptr clone() const override { return *new RectangleListRegion (*this); }
  1559. Ptr applyClipTo (const Ptr& target) const override { return target->clipToRectangleList (clip); }
  1560. Ptr clipToRectangle (Rectangle<int> r) override
  1561. {
  1562. clip.clipTo (r);
  1563. return clip.isEmpty() ? Ptr() : Ptr (*this);
  1564. }
  1565. Ptr clipToRectangleList (const RectangleList<int>& r) override
  1566. {
  1567. clip.clipTo (r);
  1568. return clip.isEmpty() ? Ptr() : Ptr (*this);
  1569. }
  1570. Ptr excludeClipRectangle (Rectangle<int> r) override
  1571. {
  1572. clip.subtract (r);
  1573. return clip.isEmpty() ? Ptr() : Ptr (*this);
  1574. }
  1575. Ptr clipToPath (const Path& p, const AffineTransform& transform) override { return toEdgeTable()->clipToPath (p, transform); }
  1576. Ptr clipToEdgeTable (const EdgeTable& et) override { return toEdgeTable()->clipToEdgeTable (et); }
  1577. Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, Graphics::ResamplingQuality quality) override
  1578. {
  1579. return toEdgeTable()->clipToImageAlpha (image, transform, quality);
  1580. }
  1581. void translate (Point<int> delta) override { clip.offsetAll (delta); }
  1582. bool clipRegionIntersects (Rectangle<int> r) const override { return clip.intersects (r); }
  1583. Rectangle<int> getClipBounds() const override { return clip.getBounds(); }
  1584. void fillRectWithColour (SavedStateType& state, Rectangle<int> area, PixelARGB colour, bool replaceContents) const override
  1585. {
  1586. SubRectangleIterator iter (clip, area);
  1587. state.fillWithSolidColour (iter, colour, replaceContents);
  1588. }
  1589. void fillRectWithColour (SavedStateType& state, Rectangle<float> area, PixelARGB colour) const override
  1590. {
  1591. SubRectangleIteratorFloat iter (clip, area);
  1592. state.fillWithSolidColour (iter, colour, false);
  1593. }
  1594. void fillAllWithColour (SavedStateType& state, PixelARGB colour, bool replaceContents) const override
  1595. {
  1596. state.fillWithSolidColour (*this, colour, replaceContents);
  1597. }
  1598. void fillAllWithGradient (SavedStateType& state, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const override
  1599. {
  1600. state.fillWithGradient (*this, gradient, transform, isIdentity);
  1601. }
  1602. void renderImageTransformed (SavedStateType& state, const Image& src, int alpha, const AffineTransform& transform, Graphics::ResamplingQuality quality, bool tiledFill) const override
  1603. {
  1604. state.renderImageTransformed (*this, src, alpha, transform, quality, tiledFill);
  1605. }
  1606. void renderImageUntransformed (SavedStateType& state, const Image& src, int alpha, int x, int y, bool tiledFill) const override
  1607. {
  1608. state.renderImageUntransformed (*this, src, alpha, x, y, tiledFill);
  1609. }
  1610. RectangleList<int> clip;
  1611. //==============================================================================
  1612. template <class Renderer>
  1613. void iterate (Renderer& r) const noexcept
  1614. {
  1615. for (auto& i : clip)
  1616. {
  1617. auto x = i.getX();
  1618. auto w = i.getWidth();
  1619. jassert (w > 0);
  1620. auto bottom = i.getBottom();
  1621. for (int y = i.getY(); y < bottom; ++y)
  1622. {
  1623. r.setEdgeTableYPos (y);
  1624. r.handleEdgeTableLineFull (x, w);
  1625. }
  1626. }
  1627. }
  1628. private:
  1629. //==============================================================================
  1630. class SubRectangleIterator
  1631. {
  1632. public:
  1633. SubRectangleIterator (const RectangleList<int>& clipList, Rectangle<int> clipBounds)
  1634. : clip (clipList), area (clipBounds)
  1635. {}
  1636. template <class Renderer>
  1637. void iterate (Renderer& r) const noexcept
  1638. {
  1639. for (auto& i : clip)
  1640. {
  1641. auto rect = i.getIntersection (area);
  1642. if (! rect.isEmpty())
  1643. r.handleEdgeTableRectangleFull (rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
  1644. }
  1645. }
  1646. private:
  1647. const RectangleList<int>& clip;
  1648. const Rectangle<int> area;
  1649. JUCE_DECLARE_NON_COPYABLE (SubRectangleIterator)
  1650. };
  1651. //==============================================================================
  1652. class SubRectangleIteratorFloat
  1653. {
  1654. public:
  1655. SubRectangleIteratorFloat (const RectangleList<int>& clipList, Rectangle<float> clipBounds) noexcept
  1656. : clip (clipList), area (clipBounds)
  1657. {
  1658. }
  1659. template <class Renderer>
  1660. void iterate (Renderer& r) const noexcept
  1661. {
  1662. const RenderingHelpers::FloatRectangleRasterisingInfo f (area);
  1663. for (auto& i : clip)
  1664. {
  1665. auto clipLeft = i.getX();
  1666. auto clipRight = i.getRight();
  1667. auto clipTop = i.getY();
  1668. auto clipBottom = i.getBottom();
  1669. if (f.totalBottom > clipTop && f.totalTop < clipBottom
  1670. && f.totalRight > clipLeft && f.totalLeft < clipRight)
  1671. {
  1672. if (f.isOnePixelWide())
  1673. {
  1674. if (f.topAlpha != 0 && f.totalTop >= clipTop)
  1675. {
  1676. r.setEdgeTableYPos (f.totalTop);
  1677. r.handleEdgeTablePixel (f.left, f.topAlpha);
  1678. }
  1679. auto y1 = jmax (clipTop, f.top);
  1680. auto y2 = jmin (f.bottom, clipBottom);
  1681. auto h = y2 - y1;
  1682. if (h > 0)
  1683. r.handleEdgeTableRectangleFull (f.left, y1, 1, h);
  1684. if (f.bottomAlpha != 0 && f.bottom < clipBottom)
  1685. {
  1686. r.setEdgeTableYPos (f.bottom);
  1687. r.handleEdgeTablePixel (f.left, f.bottomAlpha);
  1688. }
  1689. }
  1690. else
  1691. {
  1692. auto clippedLeft = jmax (f.left, clipLeft);
  1693. auto clippedWidth = jmin (f.right, clipRight) - clippedLeft;
  1694. bool doLeftAlpha = f.leftAlpha != 0 && f.totalLeft >= clipLeft;
  1695. bool doRightAlpha = f.rightAlpha != 0 && f.right < clipRight;
  1696. if (f.topAlpha != 0 && f.totalTop >= clipTop)
  1697. {
  1698. r.setEdgeTableYPos (f.totalTop);
  1699. if (doLeftAlpha) r.handleEdgeTablePixel (f.totalLeft, f.getTopLeftCornerAlpha());
  1700. if (clippedWidth > 0) r.handleEdgeTableLine (clippedLeft, clippedWidth, f.topAlpha);
  1701. if (doRightAlpha) r.handleEdgeTablePixel (f.right, f.getTopRightCornerAlpha());
  1702. }
  1703. auto y1 = jmax (clipTop, f.top);
  1704. auto y2 = jmin (f.bottom, clipBottom);
  1705. auto h = y2 - y1;
  1706. if (h > 0)
  1707. {
  1708. if (h == 1)
  1709. {
  1710. r.setEdgeTableYPos (y1);
  1711. if (doLeftAlpha) r.handleEdgeTablePixel (f.totalLeft, f.leftAlpha);
  1712. if (clippedWidth > 0) r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  1713. if (doRightAlpha) r.handleEdgeTablePixel (f.right, f.rightAlpha);
  1714. }
  1715. else
  1716. {
  1717. if (doLeftAlpha) r.handleEdgeTableRectangle (f.totalLeft, y1, 1, h, f.leftAlpha);
  1718. if (clippedWidth > 0) r.handleEdgeTableRectangleFull (clippedLeft, y1, clippedWidth, h);
  1719. if (doRightAlpha) r.handleEdgeTableRectangle (f.right, y1, 1, h, f.rightAlpha);
  1720. }
  1721. }
  1722. if (f.bottomAlpha != 0 && f.bottom < clipBottom)
  1723. {
  1724. r.setEdgeTableYPos (f.bottom);
  1725. if (doLeftAlpha) r.handleEdgeTablePixel (f.totalLeft, f.getBottomLeftCornerAlpha());
  1726. if (clippedWidth > 0) r.handleEdgeTableLine (clippedLeft, clippedWidth, f.bottomAlpha);
  1727. if (doRightAlpha) r.handleEdgeTablePixel (f.right, f.getBottomRightCornerAlpha());
  1728. }
  1729. }
  1730. }
  1731. }
  1732. }
  1733. private:
  1734. const RectangleList<int>& clip;
  1735. Rectangle<float> area;
  1736. JUCE_DECLARE_NON_COPYABLE (SubRectangleIteratorFloat)
  1737. };
  1738. Ptr toEdgeTable() const { return *new EdgeTableRegion (clip); }
  1739. RectangleListRegion& operator= (const RectangleListRegion&);
  1740. };
  1741. };
  1742. //==============================================================================
  1743. template <class SavedStateType>
  1744. class SavedStateBase
  1745. {
  1746. public:
  1747. using BaseRegionType = typename ClipRegions<SavedStateType>::Base;
  1748. using EdgeTableRegionType = typename ClipRegions<SavedStateType>::EdgeTableRegion;
  1749. using RectangleListRegionType = typename ClipRegions<SavedStateType>::RectangleListRegion;
  1750. SavedStateBase (Rectangle<int> initialClip)
  1751. : clip (new RectangleListRegionType (initialClip)),
  1752. interpolationQuality (Graphics::mediumResamplingQuality), transparencyLayerAlpha (1.0f)
  1753. {
  1754. }
  1755. SavedStateBase (const RectangleList<int>& clipList, Point<int> origin)
  1756. : clip (new RectangleListRegionType (clipList)), transform (origin),
  1757. interpolationQuality (Graphics::mediumResamplingQuality), transparencyLayerAlpha (1.0f)
  1758. {
  1759. }
  1760. SavedStateBase (const SavedStateBase& other)
  1761. : clip (other.clip), transform (other.transform), fillType (other.fillType),
  1762. interpolationQuality (other.interpolationQuality),
  1763. transparencyLayerAlpha (other.transparencyLayerAlpha)
  1764. {
  1765. }
  1766. SavedStateType& getThis() noexcept { return *static_cast<SavedStateType*> (this); }
  1767. bool clipToRectangle (Rectangle<int> r)
  1768. {
  1769. if (clip != nullptr)
  1770. {
  1771. if (transform.isOnlyTranslated)
  1772. {
  1773. cloneClipIfMultiplyReferenced();
  1774. clip = clip->clipToRectangle (transform.translated (r));
  1775. }
  1776. else if (! transform.isRotated)
  1777. {
  1778. cloneClipIfMultiplyReferenced();
  1779. clip = clip->clipToRectangle (transform.transformed (r));
  1780. }
  1781. else
  1782. {
  1783. Path p;
  1784. p.addRectangle (r);
  1785. clipToPath (p, {});
  1786. }
  1787. }
  1788. return clip != nullptr;
  1789. }
  1790. bool clipToRectangleList (const RectangleList<int>& r)
  1791. {
  1792. if (clip != nullptr)
  1793. {
  1794. if (transform.isOnlyTranslated)
  1795. {
  1796. cloneClipIfMultiplyReferenced();
  1797. if (transform.isIdentity())
  1798. {
  1799. clip = clip->clipToRectangleList (r);
  1800. }
  1801. else
  1802. {
  1803. RectangleList<int> offsetList (r);
  1804. offsetList.offsetAll (transform.offset);
  1805. clip = clip->clipToRectangleList (offsetList);
  1806. }
  1807. }
  1808. else if (! transform.isRotated)
  1809. {
  1810. cloneClipIfMultiplyReferenced();
  1811. RectangleList<int> scaledList;
  1812. for (auto& i : r)
  1813. scaledList.add (transform.transformed (i));
  1814. clip = clip->clipToRectangleList (scaledList);
  1815. }
  1816. else
  1817. {
  1818. clipToPath (r.toPath(), {});
  1819. }
  1820. }
  1821. return clip != nullptr;
  1822. }
  1823. static Rectangle<int> getLargestIntegerWithin (Rectangle<float> r)
  1824. {
  1825. auto x1 = (int) std::ceil (r.getX());
  1826. auto y1 = (int) std::ceil (r.getY());
  1827. auto x2 = (int) std::floor (r.getRight());
  1828. auto y2 = (int) std::floor (r.getBottom());
  1829. return { x1, y1, x2 - x1, y2 - y1 };
  1830. }
  1831. bool excludeClipRectangle (Rectangle<int> r)
  1832. {
  1833. if (clip != nullptr)
  1834. {
  1835. cloneClipIfMultiplyReferenced();
  1836. if (transform.isOnlyTranslated)
  1837. {
  1838. clip = clip->excludeClipRectangle (getLargestIntegerWithin (transform.translated (r.toFloat())));
  1839. }
  1840. else if (! transform.isRotated)
  1841. {
  1842. clip = clip->excludeClipRectangle (getLargestIntegerWithin (transform.transformed (r.toFloat())));
  1843. }
  1844. else
  1845. {
  1846. Path p;
  1847. p.addRectangle (r.toFloat());
  1848. p.applyTransform (transform.complexTransform);
  1849. p.addRectangle (clip->getClipBounds().toFloat());
  1850. p.setUsingNonZeroWinding (false);
  1851. clip = clip->clipToPath (p, {});
  1852. }
  1853. }
  1854. return clip != nullptr;
  1855. }
  1856. void clipToPath (const Path& p, const AffineTransform& t)
  1857. {
  1858. if (clip != nullptr)
  1859. {
  1860. cloneClipIfMultiplyReferenced();
  1861. clip = clip->clipToPath (p, transform.getTransformWith (t));
  1862. }
  1863. }
  1864. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& t)
  1865. {
  1866. if (clip != nullptr)
  1867. {
  1868. if (sourceImage.hasAlphaChannel())
  1869. {
  1870. cloneClipIfMultiplyReferenced();
  1871. clip = clip->clipToImageAlpha (sourceImage, transform.getTransformWith (t), interpolationQuality);
  1872. }
  1873. else
  1874. {
  1875. Path p;
  1876. p.addRectangle (sourceImage.getBounds());
  1877. clipToPath (p, t);
  1878. }
  1879. }
  1880. }
  1881. bool clipRegionIntersects (Rectangle<int> r) const
  1882. {
  1883. if (clip != nullptr)
  1884. {
  1885. if (transform.isOnlyTranslated)
  1886. return clip->clipRegionIntersects (transform.translated (r));
  1887. return getClipBounds().intersects (r);
  1888. }
  1889. return false;
  1890. }
  1891. Rectangle<int> getClipBounds() const
  1892. {
  1893. return clip != nullptr ? transform.deviceSpaceToUserSpace (clip->getClipBounds())
  1894. : Rectangle<int>();
  1895. }
  1896. void setFillType (const FillType& newFill)
  1897. {
  1898. fillType = newFill;
  1899. }
  1900. void fillTargetRect (Rectangle<int> r, bool replaceContents)
  1901. {
  1902. if (fillType.isColour())
  1903. {
  1904. clip->fillRectWithColour (getThis(), r, fillType.colour.getPixelARGB(), replaceContents);
  1905. }
  1906. else
  1907. {
  1908. auto clipped = clip->getClipBounds().getIntersection (r);
  1909. if (! clipped.isEmpty())
  1910. fillShape (*new RectangleListRegionType (clipped), false);
  1911. }
  1912. }
  1913. void fillTargetRect (Rectangle<float> r)
  1914. {
  1915. if (fillType.isColour())
  1916. {
  1917. clip->fillRectWithColour (getThis(), r, fillType.colour.getPixelARGB());
  1918. }
  1919. else
  1920. {
  1921. auto clipped = clip->getClipBounds().toFloat().getIntersection (r);
  1922. if (! clipped.isEmpty())
  1923. fillShape (*new EdgeTableRegionType (clipped), false);
  1924. }
  1925. }
  1926. template <typename CoordType>
  1927. void fillRectAsPath (Rectangle<CoordType> r)
  1928. {
  1929. Path p;
  1930. p.addRectangle (r);
  1931. fillPath (p, {});
  1932. }
  1933. void fillRect (Rectangle<int> r, bool replaceContents)
  1934. {
  1935. if (clip != nullptr)
  1936. {
  1937. if (transform.isOnlyTranslated)
  1938. {
  1939. fillTargetRect (transform.translated (r), replaceContents);
  1940. }
  1941. else if (! transform.isRotated)
  1942. {
  1943. fillTargetRect (transform.transformed (r), replaceContents);
  1944. }
  1945. else
  1946. {
  1947. jassert (! replaceContents); // not implemented..
  1948. fillRectAsPath (r);
  1949. }
  1950. }
  1951. }
  1952. void fillRect (Rectangle<float> r)
  1953. {
  1954. if (clip != nullptr)
  1955. {
  1956. if (transform.isOnlyTranslated)
  1957. fillTargetRect (transform.translated (r));
  1958. else if (! transform.isRotated)
  1959. fillTargetRect (transform.transformed (r));
  1960. else
  1961. fillRectAsPath (r);
  1962. }
  1963. }
  1964. void fillRectList (const RectangleList<float>& list)
  1965. {
  1966. if (clip != nullptr)
  1967. {
  1968. if (list.getNumRectangles() == 1)
  1969. return fillRect (*list.begin());
  1970. if (transform.isIdentity())
  1971. {
  1972. fillShape (*new EdgeTableRegionType (list), false);
  1973. }
  1974. else if (! transform.isRotated)
  1975. {
  1976. RectangleList<float> transformed (list);
  1977. if (transform.isOnlyTranslated)
  1978. transformed.offsetAll (transform.offset.toFloat());
  1979. else
  1980. transformed.transformAll (transform.getTransform());
  1981. fillShape (*new EdgeTableRegionType (transformed), false);
  1982. }
  1983. else
  1984. {
  1985. fillPath (list.toPath(), {});
  1986. }
  1987. }
  1988. }
  1989. void fillPath (const Path& path, const AffineTransform& t)
  1990. {
  1991. if (clip != nullptr)
  1992. {
  1993. auto trans = transform.getTransformWith (t);
  1994. auto clipRect = clip->getClipBounds();
  1995. if (path.getBoundsTransformed (trans).getSmallestIntegerContainer().intersects (clipRect))
  1996. fillShape (*new EdgeTableRegionType (clipRect, path, trans), false);
  1997. }
  1998. }
  1999. void fillEdgeTable (const EdgeTable& edgeTable, float x, int y)
  2000. {
  2001. if (clip != nullptr)
  2002. {
  2003. auto* edgeTableClip = new EdgeTableRegionType (edgeTable);
  2004. edgeTableClip->edgeTable.translate (x, y);
  2005. if (fillType.isColour())
  2006. {
  2007. auto brightness = fillType.colour.getBrightness() - 0.5f;
  2008. if (brightness > 0.0f)
  2009. edgeTableClip->edgeTable.multiplyLevels (1.0f + 1.6f * brightness);
  2010. }
  2011. fillShape (*edgeTableClip, false);
  2012. }
  2013. }
  2014. void drawLine (Line<float> line)
  2015. {
  2016. Path p;
  2017. p.addLineSegment (line, 1.0f);
  2018. fillPath (p, {});
  2019. }
  2020. void drawImage (const Image& sourceImage, const AffineTransform& trans)
  2021. {
  2022. if (clip != nullptr && ! fillType.colour.isTransparent())
  2023. renderImage (sourceImage, trans, {});
  2024. }
  2025. static bool isOnlyTranslationAllowingError (const AffineTransform& t, float tolerence) noexcept
  2026. {
  2027. return std::abs (t.mat01) < tolerence
  2028. && std::abs (t.mat10) < tolerence
  2029. && std::abs (t.mat00 - 1.0f) < tolerence
  2030. && std::abs (t.mat11 - 1.0f) < tolerence;
  2031. }
  2032. void renderImage (const Image& sourceImage, const AffineTransform& trans, const BaseRegionType* tiledFillClipRegion)
  2033. {
  2034. auto t = transform.getTransformWith (trans);
  2035. auto alpha = fillType.colour.getAlpha();
  2036. if (isOnlyTranslationAllowingError (t, 0.002f))
  2037. {
  2038. // If our translation doesn't involve any distortion, just use a simple blit..
  2039. auto tx = (int) (t.getTranslationX() * 256.0f);
  2040. auto ty = (int) (t.getTranslationY() * 256.0f);
  2041. if (interpolationQuality == Graphics::lowResamplingQuality || ((tx | ty) & 224) == 0)
  2042. {
  2043. tx = ((tx + 128) >> 8);
  2044. ty = ((ty + 128) >> 8);
  2045. if (tiledFillClipRegion != nullptr)
  2046. {
  2047. tiledFillClipRegion->renderImageUntransformed (getThis(), sourceImage, alpha, tx, ty, true);
  2048. }
  2049. else
  2050. {
  2051. Rectangle<int> area (tx, ty, sourceImage.getWidth(), sourceImage.getHeight());
  2052. area = area.getIntersection (getThis().getMaximumBounds());
  2053. if (! area.isEmpty())
  2054. if (auto c = clip->applyClipTo (*new EdgeTableRegionType (area)))
  2055. c->renderImageUntransformed (getThis(), sourceImage, alpha, tx, ty, false);
  2056. }
  2057. return;
  2058. }
  2059. }
  2060. if (! t.isSingularity())
  2061. {
  2062. if (tiledFillClipRegion != nullptr)
  2063. {
  2064. tiledFillClipRegion->renderImageTransformed (getThis(), sourceImage, alpha,
  2065. t, interpolationQuality, true);
  2066. }
  2067. else
  2068. {
  2069. Path p;
  2070. p.addRectangle (sourceImage.getBounds());
  2071. if (auto c = clip->clone()->clipToPath (p, t))
  2072. c->renderImageTransformed (getThis(), sourceImage, alpha,
  2073. t, interpolationQuality, false);
  2074. }
  2075. }
  2076. }
  2077. void fillShape (typename BaseRegionType::Ptr shapeToFill, bool replaceContents)
  2078. {
  2079. jassert (clip != nullptr);
  2080. shapeToFill = clip->applyClipTo (shapeToFill);
  2081. if (shapeToFill != nullptr)
  2082. {
  2083. if (fillType.isGradient())
  2084. {
  2085. jassert (! replaceContents); // that option is just for solid colours
  2086. auto g2 = *(fillType.gradient);
  2087. g2.multiplyOpacity (fillType.getOpacity());
  2088. auto t = transform.getTransformWith (fillType.transform).translated (-0.5f, -0.5f);
  2089. bool isIdentity = t.isOnlyTranslation();
  2090. if (isIdentity)
  2091. {
  2092. // If our translation doesn't involve any distortion, we can speed it up..
  2093. g2.point1.applyTransform (t);
  2094. g2.point2.applyTransform (t);
  2095. t = {};
  2096. }
  2097. shapeToFill->fillAllWithGradient (getThis(), g2, t, isIdentity);
  2098. }
  2099. else if (fillType.isTiledImage())
  2100. {
  2101. renderImage (fillType.image, fillType.transform, shapeToFill.get());
  2102. }
  2103. else
  2104. {
  2105. shapeToFill->fillAllWithColour (getThis(), fillType.colour.getPixelARGB(), replaceContents);
  2106. }
  2107. }
  2108. }
  2109. void cloneClipIfMultiplyReferenced()
  2110. {
  2111. if (clip->getReferenceCount() > 1)
  2112. clip = clip->clone();
  2113. }
  2114. typename BaseRegionType::Ptr clip;
  2115. RenderingHelpers::TranslationOrTransform transform;
  2116. FillType fillType;
  2117. Graphics::ResamplingQuality interpolationQuality;
  2118. float transparencyLayerAlpha;
  2119. };
  2120. //==============================================================================
  2121. class SoftwareRendererSavedState : public SavedStateBase<SoftwareRendererSavedState>
  2122. {
  2123. using BaseClass = SavedStateBase<SoftwareRendererSavedState>;
  2124. public:
  2125. SoftwareRendererSavedState (const Image& im, Rectangle<int> clipBounds)
  2126. : BaseClass (clipBounds), image (im)
  2127. {
  2128. }
  2129. SoftwareRendererSavedState (const Image& im, const RectangleList<int>& clipList, Point<int> origin)
  2130. : BaseClass (clipList, origin), image (im)
  2131. {
  2132. }
  2133. SoftwareRendererSavedState (const SoftwareRendererSavedState& other)
  2134. : BaseClass (other), image (other.image), font (other.font)
  2135. {
  2136. }
  2137. SoftwareRendererSavedState* beginTransparencyLayer (float opacity)
  2138. {
  2139. auto* s = new SoftwareRendererSavedState (*this);
  2140. if (clip != nullptr)
  2141. {
  2142. auto layerBounds = clip->getClipBounds();
  2143. s->image = Image (Image::ARGB, layerBounds.getWidth(), layerBounds.getHeight(), true);
  2144. s->transparencyLayerAlpha = opacity;
  2145. s->transform.moveOriginInDeviceSpace (-layerBounds.getPosition());
  2146. s->cloneClipIfMultiplyReferenced();
  2147. s->clip->translate (-layerBounds.getPosition());
  2148. }
  2149. return s;
  2150. }
  2151. void endTransparencyLayer (SoftwareRendererSavedState& finishedLayerState)
  2152. {
  2153. if (clip != nullptr)
  2154. {
  2155. auto layerBounds = clip->getClipBounds();
  2156. const std::unique_ptr<LowLevelGraphicsContext> g (image.createLowLevelContext());
  2157. g->setOpacity (finishedLayerState.transparencyLayerAlpha);
  2158. g->drawImage (finishedLayerState.image, AffineTransform::translation (layerBounds.getPosition()));
  2159. }
  2160. }
  2161. using GlyphCacheType = GlyphCache<CachedGlyphEdgeTable<SoftwareRendererSavedState>, SoftwareRendererSavedState>;
  2162. static void clearGlyphCache()
  2163. {
  2164. GlyphCacheType::getInstance().reset();
  2165. }
  2166. //==============================================================================
  2167. void drawGlyph (int glyphNumber, const AffineTransform& trans)
  2168. {
  2169. if (clip != nullptr)
  2170. {
  2171. if (trans.isOnlyTranslation() && ! transform.isRotated)
  2172. {
  2173. auto& cache = GlyphCacheType::getInstance();
  2174. Point<float> pos (trans.getTranslationX(), trans.getTranslationY());
  2175. if (transform.isOnlyTranslated)
  2176. {
  2177. cache.drawGlyph (*this, font, glyphNumber, pos + transform.offset.toFloat());
  2178. }
  2179. else
  2180. {
  2181. pos = transform.transformed (pos);
  2182. Font f (font);
  2183. f.setHeight (font.getHeight() * transform.complexTransform.mat11);
  2184. auto xScale = transform.complexTransform.mat00 / transform.complexTransform.mat11;
  2185. if (std::abs (xScale - 1.0f) > 0.01f)
  2186. f.setHorizontalScale (xScale);
  2187. cache.drawGlyph (*this, f, glyphNumber, pos);
  2188. }
  2189. }
  2190. else
  2191. {
  2192. auto fontHeight = font.getHeight();
  2193. auto t = transform.getTransformWith (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  2194. .followedBy (trans));
  2195. std::unique_ptr<EdgeTable> et (font.getTypeface()->getEdgeTableForGlyph (glyphNumber, t, fontHeight));
  2196. if (et != nullptr)
  2197. fillShape (*new EdgeTableRegionType (*et), false);
  2198. }
  2199. }
  2200. }
  2201. Rectangle<int> getMaximumBounds() const { return image.getBounds(); }
  2202. //==============================================================================
  2203. template <typename IteratorType>
  2204. void renderImageTransformed (IteratorType& iter, const Image& src, int alpha, const AffineTransform& trans, Graphics::ResamplingQuality quality, bool tiledFill) const
  2205. {
  2206. Image::BitmapData destData (image, Image::BitmapData::readWrite);
  2207. const Image::BitmapData srcData (src, Image::BitmapData::readOnly);
  2208. EdgeTableFillers::renderImageTransformed (iter, destData, srcData, alpha, trans, quality, tiledFill);
  2209. }
  2210. template <typename IteratorType>
  2211. void renderImageUntransformed (IteratorType& iter, const Image& src, int alpha, int x, int y, bool tiledFill) const
  2212. {
  2213. Image::BitmapData destData (image, Image::BitmapData::readWrite);
  2214. const Image::BitmapData srcData (src, Image::BitmapData::readOnly);
  2215. EdgeTableFillers::renderImageUntransformed (iter, destData, srcData, alpha, x, y, tiledFill);
  2216. }
  2217. template <typename IteratorType>
  2218. void fillWithSolidColour (IteratorType& iter, PixelARGB colour, bool replaceContents) const
  2219. {
  2220. Image::BitmapData destData (image, Image::BitmapData::readWrite);
  2221. switch (destData.pixelFormat)
  2222. {
  2223. case Image::ARGB: EdgeTableFillers::renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  2224. case Image::RGB: EdgeTableFillers::renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  2225. default: EdgeTableFillers::renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  2226. }
  2227. }
  2228. template <typename IteratorType>
  2229. void fillWithGradient (IteratorType& iter, ColourGradient& gradient, const AffineTransform& trans, bool isIdentity) const
  2230. {
  2231. HeapBlock<PixelARGB> lookupTable;
  2232. auto numLookupEntries = gradient.createLookupTable (trans, lookupTable);
  2233. jassert (numLookupEntries > 0);
  2234. Image::BitmapData destData (image, Image::BitmapData::readWrite);
  2235. switch (destData.pixelFormat)
  2236. {
  2237. case Image::ARGB: EdgeTableFillers::renderGradient (iter, destData, gradient, trans, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  2238. case Image::RGB: EdgeTableFillers::renderGradient (iter, destData, gradient, trans, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  2239. default: EdgeTableFillers::renderGradient (iter, destData, gradient, trans, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  2240. }
  2241. }
  2242. //==============================================================================
  2243. Image image;
  2244. Font font;
  2245. private:
  2246. SoftwareRendererSavedState& operator= (const SoftwareRendererSavedState&);
  2247. };
  2248. //==============================================================================
  2249. template <class StateObjectType>
  2250. class SavedStateStack
  2251. {
  2252. public:
  2253. SavedStateStack (StateObjectType* initialState) noexcept
  2254. : currentState (initialState)
  2255. {}
  2256. SavedStateStack() noexcept {}
  2257. void initialise (StateObjectType* state)
  2258. {
  2259. currentState.reset (state);
  2260. }
  2261. inline StateObjectType* operator->() const noexcept { return currentState.get(); }
  2262. inline StateObjectType& operator*() const noexcept { return *currentState; }
  2263. void save()
  2264. {
  2265. stack.add (new StateObjectType (*currentState));
  2266. }
  2267. void restore()
  2268. {
  2269. if (auto* top = stack.getLast())
  2270. {
  2271. currentState.reset (top);
  2272. stack.removeLast (1, false);
  2273. }
  2274. else
  2275. {
  2276. jassertfalse; // trying to pop with an empty stack!
  2277. }
  2278. }
  2279. void beginTransparencyLayer (float opacity)
  2280. {
  2281. save();
  2282. currentState.reset (currentState->beginTransparencyLayer (opacity));
  2283. }
  2284. void endTransparencyLayer()
  2285. {
  2286. std::unique_ptr<StateObjectType> finishedTransparencyLayer (currentState.release());
  2287. restore();
  2288. currentState->endTransparencyLayer (*finishedTransparencyLayer);
  2289. }
  2290. private:
  2291. std::unique_ptr<StateObjectType> currentState;
  2292. OwnedArray<StateObjectType> stack;
  2293. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedStateStack)
  2294. };
  2295. //==============================================================================
  2296. template <class SavedStateType>
  2297. class StackBasedLowLevelGraphicsContext : public LowLevelGraphicsContext
  2298. {
  2299. public:
  2300. bool isVectorDevice() const override { return false; }
  2301. void setOrigin (Point<int> o) override { stack->transform.setOrigin (o); }
  2302. void addTransform (const AffineTransform& t) override { stack->transform.addTransform (t); }
  2303. float getPhysicalPixelScaleFactor() override { return stack->transform.getPhysicalPixelScaleFactor(); }
  2304. Rectangle<int> getClipBounds() const override { return stack->getClipBounds(); }
  2305. bool isClipEmpty() const override { return stack->clip == nullptr; }
  2306. bool clipRegionIntersects (const Rectangle<int>& r) override { return stack->clipRegionIntersects (r); }
  2307. bool clipToRectangle (const Rectangle<int>& r) override { return stack->clipToRectangle (r); }
  2308. bool clipToRectangleList (const RectangleList<int>& r) override { return stack->clipToRectangleList (r); }
  2309. void excludeClipRectangle (const Rectangle<int>& r) override { stack->excludeClipRectangle (r); }
  2310. void clipToPath (const Path& path, const AffineTransform& t) override { stack->clipToPath (path, t); }
  2311. void clipToImageAlpha (const Image& im, const AffineTransform& t) override { stack->clipToImageAlpha (im, t); }
  2312. void saveState() override { stack.save(); }
  2313. void restoreState() override { stack.restore(); }
  2314. void beginTransparencyLayer (float opacity) override { stack.beginTransparencyLayer (opacity); }
  2315. void endTransparencyLayer() override { stack.endTransparencyLayer(); }
  2316. void setFill (const FillType& fillType) override { stack->setFillType (fillType); }
  2317. void setOpacity (float newOpacity) override { stack->fillType.setOpacity (newOpacity); }
  2318. void setInterpolationQuality (Graphics::ResamplingQuality quality) override { stack->interpolationQuality = quality; }
  2319. void fillRect (const Rectangle<int>& r, bool replace) override { stack->fillRect (r, replace); }
  2320. void fillRect (const Rectangle<float>& r) override { stack->fillRect (r); }
  2321. void fillRectList (const RectangleList<float>& list) override { stack->fillRectList (list); }
  2322. void fillPath (const Path& path, const AffineTransform& t) override { stack->fillPath (path, t); }
  2323. void drawImage (const Image& im, const AffineTransform& t) override { stack->drawImage (im, t); }
  2324. void drawGlyph (int glyphNumber, const AffineTransform& t) override { stack->drawGlyph (glyphNumber, t); }
  2325. void drawLine (const Line<float>& line) override { stack->drawLine (line); }
  2326. void setFont (const Font& newFont) override { stack->font = newFont; }
  2327. const Font& getFont() override { return stack->font; }
  2328. protected:
  2329. StackBasedLowLevelGraphicsContext (SavedStateType* initialState) : stack (initialState) {}
  2330. StackBasedLowLevelGraphicsContext() {}
  2331. RenderingHelpers::SavedStateStack<SavedStateType> stack;
  2332. };
  2333. }
  2334. #if JUCE_MSVC
  2335. #pragma warning (pop)
  2336. #endif
  2337. } // namespace juce