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.

527 lines
16KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. /**
  18. This scene description is broadcast to all the clients, and contains a list of all
  19. the clients involved, as well as the set of shapes to be drawn.
  20. Each client will draw the part of the path that lies within its own area. It can
  21. find its area by looking at the list of clients contained in this structure.
  22. All the path coordinates are roughly in units of inches, and devices will convert
  23. this to pixels based on their screen size and DPI
  24. */
  25. struct SharedCanvasDescription
  26. {
  27. SharedCanvasDescription() {}
  28. Colour backgroundColour = Colours::black;
  29. struct ColouredPath
  30. {
  31. Path path;
  32. FillType fill;
  33. };
  34. Array<ColouredPath> paths;
  35. struct ClientArea
  36. {
  37. String name;
  38. Point<float> centre; // in inches
  39. float scaleFactor; // extra scaling
  40. };
  41. Array<ClientArea> clients;
  42. //==============================================================================
  43. void reset()
  44. {
  45. paths.clearQuick();
  46. clients.clearQuick();
  47. }
  48. void swapWith (SharedCanvasDescription& other)
  49. {
  50. std::swap (backgroundColour, other.backgroundColour);
  51. paths.swapWith (other.paths);
  52. clients.swapWith (other.clients);
  53. }
  54. // This is a fixed size that represents the overall canvas limits that
  55. // content should lie within
  56. Rectangle<float> getLimits() const
  57. {
  58. float inchesX = 60.0f;
  59. float inchesY = 30.0f;
  60. return { inchesX * -0.5f, inchesY * -0.5f, inchesX, inchesY };
  61. }
  62. //==============================================================================
  63. void draw (Graphics& g, Rectangle<float> targetArea, Rectangle<float> clientArea) const
  64. {
  65. draw (g, clientArea,
  66. AffineTransform::fromTargetPoints (clientArea.getX(), clientArea.getY(),
  67. targetArea.getX(), targetArea.getY(),
  68. clientArea.getRight(), clientArea.getY(),
  69. targetArea.getRight(), targetArea.getY(),
  70. clientArea.getRight(), clientArea.getBottom(),
  71. targetArea.getRight(), targetArea.getBottom()));
  72. }
  73. void draw (Graphics& g, Rectangle<float> clientArea, AffineTransform t) const
  74. {
  75. g.saveState();
  76. g.addTransform (t);
  77. for (const auto& p : paths)
  78. {
  79. if (p.path.getBounds().intersects (clientArea))
  80. {
  81. g.setFillType (p.fill);
  82. g.fillPath (p.path);
  83. }
  84. }
  85. g.restoreState();
  86. }
  87. const ClientArea* findClient (const String& clientName) const
  88. {
  89. for (const auto& c : clients)
  90. if (c.name == clientName)
  91. return &c;
  92. return nullptr;
  93. }
  94. //==============================================================================
  95. // Serialisation...
  96. void save (OutputStream& out) const
  97. {
  98. out.writeInt (magic);
  99. out.writeInt ((int) backgroundColour.getARGB());
  100. out.writeInt (clients.size());
  101. for (const auto& c : clients)
  102. {
  103. out.writeString (c.name);
  104. writePoint (out, c.centre);
  105. out.writeFloat (c.scaleFactor);
  106. }
  107. out.writeInt (paths.size());
  108. for (const auto& p : paths)
  109. {
  110. writeFill (out, p.fill);
  111. p.path.writePathToStream (out);
  112. }
  113. }
  114. void load (InputStream& in)
  115. {
  116. if (in.readInt() != magic)
  117. return;
  118. backgroundColour = Colour ((uint32) in.readInt());
  119. {
  120. const int numClients = in.readInt();
  121. clients.clearQuick();
  122. for (int i = 0; i < numClients; ++i)
  123. {
  124. ClientArea c;
  125. c.name = in.readString();
  126. c.centre = readPoint (in);
  127. c.scaleFactor = in.readFloat();
  128. clients.add (c);
  129. }
  130. }
  131. {
  132. const int numPaths = in.readInt();
  133. paths.clearQuick();
  134. for (int i = 0; i < numPaths; ++i)
  135. {
  136. ColouredPath p;
  137. p.fill = readFill (in);
  138. p.path.loadPathFromStream (in);
  139. paths.add (std::move (p));
  140. }
  141. }
  142. }
  143. MemoryBlock toMemoryBlock() const
  144. {
  145. MemoryOutputStream o;
  146. save (o);
  147. return o.getMemoryBlock();
  148. }
  149. private:
  150. //==============================================================================
  151. static void writePoint (OutputStream& out, Point<float> p)
  152. {
  153. out.writeFloat (p.x);
  154. out.writeFloat (p.y);
  155. }
  156. static void writeRect (OutputStream& out, Rectangle<float> r)
  157. {
  158. writePoint (out, r.getPosition());
  159. out.writeFloat (r.getWidth());
  160. out.writeFloat (r.getHeight());
  161. }
  162. static Point<float> readPoint (InputStream& in)
  163. {
  164. Point<float> p;
  165. p.x = in.readFloat();
  166. p.y = in.readFloat();
  167. return p;
  168. }
  169. static Rectangle<float> readRect (InputStream& in)
  170. {
  171. Rectangle<float> r;
  172. r.setPosition (readPoint (in));
  173. r.setWidth (in.readFloat());
  174. r.setHeight (in.readFloat());
  175. return r;
  176. }
  177. static void writeFill (OutputStream& out, const FillType& f)
  178. {
  179. if (f.isColour())
  180. {
  181. out.writeByte (0);
  182. out.writeInt ((int) f.colour.getARGB());
  183. }
  184. else if (f.isGradient())
  185. {
  186. const ColourGradient& cg = *f.gradient;
  187. jassert (cg.getNumColours() >= 2);
  188. out.writeByte (cg.isRadial ? 2 : 1);
  189. writePoint (out, cg.point1);
  190. writePoint (out, cg.point2);
  191. out.writeCompressedInt (cg.getNumColours());
  192. for (int i = 0; i < cg.getNumColours(); ++i)
  193. {
  194. out.writeDouble (cg.getColourPosition (i));
  195. out.writeInt ((int) cg.getColour(i).getARGB());
  196. }
  197. }
  198. else
  199. {
  200. jassertfalse;
  201. }
  202. }
  203. static FillType readFill (InputStream& in)
  204. {
  205. int type = in.readByte();
  206. if (type == 0)
  207. return FillType (Colour ((uint32) in.readInt()));
  208. if (type > 2)
  209. {
  210. jassertfalse;
  211. return FillType();
  212. }
  213. ColourGradient cg;
  214. cg.point1 = readPoint (in);
  215. cg.point2 = readPoint (in);
  216. cg.clearColours();
  217. int numColours = in.readCompressedInt();
  218. for (int i = 0; i < numColours; ++i)
  219. {
  220. const double pos = in.readDouble();
  221. cg.addColour (pos, Colour ((uint32) in.readInt()));
  222. }
  223. jassert (cg.getNumColours() >= 2);
  224. return FillType (cg);
  225. }
  226. const int magic = 0x2381239a;
  227. JUCE_DECLARE_NON_COPYABLE (SharedCanvasDescription)
  228. };
  229. //==============================================================================
  230. class CanvasGeneratingContext : public LowLevelGraphicsContext
  231. {
  232. public:
  233. CanvasGeneratingContext (SharedCanvasDescription& c) : canvas (c)
  234. {
  235. stateStack.add (new SavedState());
  236. }
  237. //==============================================================================
  238. bool isVectorDevice() const override { return true; }
  239. float getPhysicalPixelScaleFactor() override { return 1.0f; }
  240. void setOrigin (Point<int> o) override { addTransform (AffineTransform::translation ((float) o.x, (float) o.y)); }
  241. void addTransform (const AffineTransform& t) override
  242. {
  243. getState().transform = t.followedBy (getState().transform);
  244. }
  245. bool clipToRectangle (const Rectangle<int>&) override { return true; }
  246. bool clipToRectangleList (const RectangleList<int>&) override { return true; }
  247. void excludeClipRectangle (const Rectangle<int>&) override {}
  248. void clipToPath (const Path&, const AffineTransform&) override {}
  249. void clipToImageAlpha (const Image&, const AffineTransform&) override {}
  250. void saveState() override
  251. {
  252. stateStack.add (new SavedState (getState()));
  253. }
  254. void restoreState() override
  255. {
  256. jassert (stateStack.size() > 0);
  257. if (stateStack.size() > 0)
  258. stateStack.removeLast();
  259. }
  260. void beginTransparencyLayer (float alpha) override
  261. {
  262. saveState();
  263. getState().transparencyLayer = new SharedCanvasHolder();
  264. getState().transparencyOpacity = alpha;
  265. }
  266. void endTransparencyLayer() override
  267. {
  268. const ReferenceCountedObjectPtr<SharedCanvasHolder> finishedTransparencyLayer (getState().transparencyLayer);
  269. float alpha = getState().transparencyOpacity;
  270. restoreState();
  271. if (SharedCanvasHolder* c = finishedTransparencyLayer)
  272. {
  273. for (auto& path : c->canvas.paths)
  274. {
  275. path.fill.setOpacity (path.fill.getOpacity() * alpha);
  276. getTargetCanvas().paths.add (path);
  277. }
  278. }
  279. }
  280. Rectangle<int> getClipBounds() const override
  281. {
  282. return canvas.getLimits().getSmallestIntegerContainer()
  283. .transformedBy (getState().transform.inverted());
  284. }
  285. bool clipRegionIntersects (const Rectangle<int>&) override { return true; }
  286. bool isClipEmpty() const override { return false; }
  287. //==============================================================================
  288. void setFill (const FillType& fillType) override { getState().fillType = fillType; }
  289. void setOpacity (float op) override { getState().fillType.setOpacity (op); }
  290. void setInterpolationQuality (Graphics::ResamplingQuality) override {}
  291. //==============================================================================
  292. void fillRect (const Rectangle<int>& r, bool) override { fillRect (r.toFloat()); }
  293. void fillRectList (const RectangleList<float>& list) override { fillPath (list.toPath(), AffineTransform()); }
  294. void fillRect (const Rectangle<float>& r) override
  295. {
  296. Path p;
  297. p.addRectangle (r.toFloat());
  298. fillPath (p, AffineTransform());
  299. }
  300. void fillPath (const Path& p, const AffineTransform& t) override
  301. {
  302. Path p2 (p);
  303. p2.applyTransform (t.followedBy (getState().transform));
  304. getTargetCanvas().paths.add ({ std::move (p2), getState().fillType });
  305. }
  306. void drawImage (const Image&, const AffineTransform&) override {}
  307. void drawLine (const Line<float>& line) override
  308. {
  309. Path p;
  310. p.addLineSegment (line, 1.0f);
  311. fillPath (p, AffineTransform());
  312. }
  313. //==============================================================================
  314. const Font& getFont() override { return getState().font; }
  315. void setFont (const Font& newFont) override { getState().font = newFont; }
  316. void drawGlyph (int glyphNumber, const AffineTransform& transform) override
  317. {
  318. Path p;
  319. Font& font = getState().font;
  320. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  321. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  322. }
  323. private:
  324. //==============================================================================
  325. struct SharedCanvasHolder : public ReferenceCountedObject
  326. {
  327. SharedCanvasDescription canvas;
  328. };
  329. struct SavedState
  330. {
  331. FillType fillType;
  332. AffineTransform transform;
  333. Font font;
  334. ReferenceCountedObjectPtr<SharedCanvasHolder> transparencyLayer;
  335. float transparencyOpacity = 1.0f;
  336. };
  337. SharedCanvasDescription& getTargetCanvas() const
  338. {
  339. if (SharedCanvasHolder* c = getState().transparencyLayer)
  340. return c->canvas;
  341. return canvas;
  342. }
  343. SavedState& getState() const noexcept
  344. {
  345. jassert (stateStack.size() > 0);
  346. return *stateStack.getLast();
  347. }
  348. SharedCanvasDescription& canvas;
  349. OwnedArray<SavedState> stateStack;
  350. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CanvasGeneratingContext)
  351. };
  352. //==============================================================================
  353. /** Helper for breaking and reassembling a memory block into smaller checksummed
  354. blocks that will fit inside UDP packets
  355. */
  356. struct BlockPacketiser
  357. {
  358. void createBlocksFromData (const MemoryBlock& data, size_t maxBlockSize)
  359. {
  360. jassert (blocks.size() == 0);
  361. int offset = 0;
  362. size_t remaining = data.getSize();
  363. while (remaining > 0)
  364. {
  365. const int num = jmin (maxBlockSize, remaining);
  366. blocks.add (MemoryBlock (addBytesToPointer (data.getData(), offset), (size_t) num));
  367. offset += num;
  368. remaining -= num;
  369. }
  370. MemoryOutputStream checksumBlock;
  371. checksumBlock << getLastPacketPrefix() << MD5 (data).toHexString() << (char) 0 << (char) 0;
  372. blocks.add (checksumBlock.getMemoryBlock());
  373. for (int i = 0; i < blocks.size(); ++i)
  374. {
  375. uint32 index = ByteOrder::swapIfBigEndian (i);
  376. blocks.getReference(i).append (&index, sizeof (index));
  377. }
  378. }
  379. // returns true if this is an end-of-sequence block
  380. bool appendIncomingBlock (MemoryBlock data)
  381. {
  382. if (data.getSize() > 4)
  383. blocks.addSorted (*this, data);
  384. return String (CharPointer_ASCII ((const char*) data.getData())).startsWith (getLastPacketPrefix());
  385. }
  386. bool reassemble (MemoryBlock& result)
  387. {
  388. result.reset();
  389. if (blocks.size() > 1)
  390. {
  391. for (int i = 0; i < blocks.size() - 1; ++i)
  392. result.append (blocks.getReference(i).getData(), blocks.getReference(i).getSize() - 4);
  393. String storedMD5 (String (CharPointer_ASCII ((const char*) blocks.getLast().getData()))
  394. .fromFirstOccurrenceOf (getLastPacketPrefix(), false, false));
  395. blocks.clearQuick();
  396. if (MD5 (result).toHexString().trim().equalsIgnoreCase (storedMD5.trim()))
  397. return true;
  398. }
  399. result.reset();
  400. return false;
  401. }
  402. static int compareElements (const MemoryBlock& b1, const MemoryBlock& b2)
  403. {
  404. int i1 = ByteOrder::littleEndianInt (addBytesToPointer (b1.getData(), b1.getSize() - 4));
  405. int i2 = ByteOrder::littleEndianInt (addBytesToPointer (b2.getData(), b2.getSize() - 4));
  406. return i1 - i2;
  407. }
  408. static const char* getLastPacketPrefix() { return "**END_OF_PACKET_LIST** "; }
  409. Array<MemoryBlock> blocks;
  410. };
  411. //==============================================================================
  412. struct AnimatedContent
  413. {
  414. virtual ~AnimatedContent() {}
  415. virtual String getName() const = 0;
  416. virtual void reset() = 0;
  417. virtual void generateCanvas (Graphics&, SharedCanvasDescription& canvas, Rectangle<float> activeArea) = 0;
  418. virtual void handleTouch (Point<float> position) = 0;
  419. };