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.

521 lines
16KB

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