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.

695 lines
24KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. The code included in this file is provided under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  7. To use, copy, modify, and/or distribute this software for any purpose with or
  8. without fee is hereby granted provided that the above copyright notice and
  9. this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
  11. WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
  12. PURPOSE, ARE DISCLAIMED.
  13. ==============================================================================
  14. */
  15. /*******************************************************************************
  16. The block below describes the properties of this PIP. A PIP is a short snippet
  17. of code that can be read by the Projucer and used to generate a JUCE project.
  18. BEGIN_JUCE_PIP_METADATA
  19. name: BlocksDrawingDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Blocks application to draw shapes.
  24. dependencies: juce_audio_basics, juce_audio_devices, juce_audio_formats,
  25. juce_audio_processors, juce_audio_utils, juce_blocks_basics,
  26. juce_core, juce_data_structures, juce_events, juce_graphics,
  27. juce_gui_basics, juce_gui_extra
  28. exporters: xcode_mac, vs2017, linux_make, xcode_iphone
  29. type: Component
  30. mainClass: BlocksDrawingDemo
  31. useLocalCopy: 1
  32. END_JUCE_PIP_METADATA
  33. *******************************************************************************/
  34. #pragma once
  35. //==============================================================================
  36. /**
  37. Represents a single LED on a Lightpad
  38. */
  39. struct LEDComponent : public Component
  40. {
  41. LEDComponent() : ledColour (Colours::black) { setInterceptsMouseClicks (false, false); }
  42. void setColour (Colour newColour)
  43. {
  44. ledColour = newColour;
  45. repaint();
  46. }
  47. void paint (Graphics& g) override
  48. {
  49. g.setColour (ledColour);
  50. g.fillEllipse (getLocalBounds().toFloat());
  51. }
  52. Colour ledColour;
  53. };
  54. //==============================================================================
  55. /**
  56. A component that is used to represent a Lightpad on-screen
  57. */
  58. class DrawableLightpadComponent : public Component
  59. {
  60. public:
  61. DrawableLightpadComponent ()
  62. {
  63. for (auto x = 0; x < 15; ++x)
  64. for (auto y = 0; y < 15; ++y)
  65. addAndMakeVisible (leds.add (new LEDComponent()));
  66. }
  67. void paint (Graphics& g) override
  68. {
  69. auto r = getLocalBounds().toFloat();
  70. // Clip the drawing area to only draw in the block area
  71. {
  72. Path clipArea;
  73. clipArea.addRoundedRectangle (r, r.getWidth() / 20.0f);
  74. g.reduceClipRegion (clipArea);
  75. }
  76. // Fill a black square for the Lightpad
  77. g.fillAll (Colours::black);
  78. }
  79. void resized() override
  80. {
  81. auto r = getLocalBounds().reduced (10);
  82. auto circleWidth = r.getWidth() / 15;
  83. auto circleHeight = r.getHeight() / 15;
  84. for (auto x = 0; x < 15; ++x)
  85. for (auto y = 0; y < 15; ++y)
  86. leds.getUnchecked ((x * 15) + y)->setBounds (r.getX() + (x * circleWidth),
  87. r.getY() + (y * circleHeight),
  88. circleWidth, circleHeight);
  89. }
  90. void mouseDown (const MouseEvent& e) override
  91. {
  92. for (auto x = 0; x < 15; ++x)
  93. for (auto y = 0; y < 15; ++y)
  94. if (leds.getUnchecked ((x * 15) + y)->getBounds().contains (e.position.toInt()))
  95. listeners.call ([&] (Listener& l) { l.ledClicked (x, y, e.pressure); });
  96. }
  97. void mouseDrag (const MouseEvent& e) override
  98. {
  99. for (auto x = 0; x < 15; ++x)
  100. {
  101. for (auto y = 0; y < 15; ++y)
  102. {
  103. if (leds.getUnchecked ((x * 15) + y)->getBounds().contains (e.position.toInt()))
  104. {
  105. auto t = e.eventTime;
  106. if (lastLED == Point<int> (x, y) && t.toMilliseconds() - lastMouseEventTime.toMilliseconds() < 50)
  107. return;
  108. listeners.call ([&] (Listener& l) { l.ledClicked (x, y, e.pressure); });
  109. lastLED = { x, y };
  110. lastMouseEventTime = t;
  111. }
  112. }
  113. }
  114. }
  115. //==============================================================================
  116. /** Sets the colour of one of the LEDComponents */
  117. void setLEDColour (int x, int y, Colour c)
  118. {
  119. x = jmin (x, 14);
  120. y = jmin (y, 14);
  121. leds.getUnchecked ((x * 15) + y)->setColour (c);
  122. }
  123. //==============================================================================
  124. struct Listener
  125. {
  126. virtual ~Listener() {}
  127. /** Called when an LEDComponent has been clicked */
  128. virtual void ledClicked (int x, int y, float z) = 0;
  129. };
  130. void addListener (Listener* l) { listeners.add (l); }
  131. void removeListener (Listener* l) { listeners.remove (l); }
  132. private:
  133. OwnedArray<LEDComponent> leds;
  134. ListenerList<Listener> listeners;
  135. Time lastMouseEventTime;
  136. Point<int> lastLED;
  137. };
  138. //==============================================================================
  139. /**
  140. A struct that handles the setup and layout of the DrumPadGridProgram
  141. */
  142. struct ColourGrid
  143. {
  144. ColourGrid (int cols, int rows)
  145. : numColumns (cols),
  146. numRows (rows)
  147. {
  148. constructGridFillArray();
  149. }
  150. /** Creates a GridFill object for each pad in the grid and sets its colour
  151. and fill before adding it to an array of GridFill objects
  152. */
  153. void constructGridFillArray()
  154. {
  155. gridFillArray.clear();
  156. auto counter = 0;
  157. for (auto i = 0; i < numColumns; ++i)
  158. {
  159. for (auto j = 0; j < numRows; ++j)
  160. {
  161. DrumPadGridProgram::GridFill fill;
  162. Colour colourToUse = colourArray.getUnchecked (counter);
  163. fill.colour = colourToUse.withBrightness (colourToUse == currentColour ? 1.0f : 0.1f);
  164. if (colourToUse == Colours::black)
  165. fill.fillType = DrumPadGridProgram::GridFill::FillType::hollow;
  166. else
  167. fill.fillType = DrumPadGridProgram::GridFill::FillType::filled;
  168. gridFillArray.add (fill);
  169. if (++counter == colourArray.size())
  170. counter = 0;
  171. }
  172. }
  173. }
  174. /** Sets which colour should be active for a given touch co-ordinate. Returns
  175. true if the colour has changed
  176. */
  177. bool setActiveColourForTouch (int x, int y)
  178. {
  179. auto colourHasChanged = false;
  180. auto xindex = x / 5;
  181. auto yindex = y / 5;
  182. auto newColour = colourArray.getUnchecked ((yindex * 3) + xindex);
  183. if (currentColour != newColour)
  184. {
  185. currentColour = newColour;
  186. constructGridFillArray();
  187. colourHasChanged = true;
  188. }
  189. return colourHasChanged;
  190. }
  191. //==============================================================================
  192. int numColumns, numRows;
  193. Array<DrumPadGridProgram::GridFill> gridFillArray;
  194. Array<Colour> colourArray = { Colours::white, Colours::red, Colours::green,
  195. Colours::blue, Colours::hotpink, Colours::orange,
  196. Colours::magenta, Colours::cyan, Colours::black };
  197. Colour currentColour = Colours::hotpink;
  198. //==============================================================================
  199. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ColourGrid)
  200. };
  201. //==============================================================================
  202. /**
  203. The main component
  204. */
  205. class BlocksDrawingDemo : public Component,
  206. public TopologySource::Listener,
  207. private TouchSurface::Listener,
  208. private ControlButton::Listener,
  209. private DrawableLightpadComponent::Listener,
  210. private Timer
  211. {
  212. public:
  213. //==============================================================================
  214. BlocksDrawingDemo()
  215. {
  216. activeLeds.clear();
  217. // Register MainContentComponent as a listener to the PhysicalTopologySource object
  218. topologySource.addListener (this);
  219. infoLabel.setText ("Connect a Lightpad Block to draw.", dontSendNotification);
  220. infoLabel.setJustificationType (Justification::centred);
  221. addAndMakeVisible (infoLabel);
  222. addAndMakeVisible (lightpadComponent);
  223. lightpadComponent.setVisible (false);
  224. lightpadComponent.addListener (this);
  225. clearButton.setButtonText ("Clear");
  226. clearButton.onClick = [this] { clearLEDs(); };
  227. clearButton.setAlwaysOnTop (true);
  228. addAndMakeVisible (clearButton);
  229. brightnessSlider.setRange (0.0, 1.0);
  230. brightnessSlider.setValue (1.0);
  231. brightnessSlider.setAlwaysOnTop (true);
  232. brightnessSlider.setTextBoxStyle (Slider::TextEntryBoxPosition::NoTextBox, false, 0, 0);
  233. brightnessSlider.onValueChange = [this]
  234. {
  235. brightnessLED.setColour (layout.currentColour
  236. .withBrightness (layout.currentColour == Colours::black ? 0.0f
  237. : static_cast<float> (brightnessSlider.getValue())));
  238. };
  239. addAndMakeVisible (brightnessSlider);
  240. brightnessLED.setAlwaysOnTop (true);
  241. brightnessLED.setColour (layout.currentColour.withBrightness (static_cast<float> (brightnessSlider.getValue())));
  242. addAndMakeVisible (brightnessLED);
  243. #if JUCE_IOS
  244. connectButton.setButtonText ("Connect");
  245. connectButton.onClick = [] { BluetoothMidiDevicePairingDialogue::open(); };
  246. connectButton.setAlwaysOnTop (true);
  247. addAndMakeVisible (connectButton);
  248. #endif
  249. setSize (600, 600);
  250. }
  251. ~BlocksDrawingDemo()
  252. {
  253. if (activeBlock != nullptr)
  254. detachActiveBlock();
  255. lightpadComponent.removeListener (this);
  256. }
  257. void resized() override
  258. {
  259. infoLabel.centreWithSize (getWidth(), 100);
  260. auto bounds = getLocalBounds().reduced (20);
  261. // top buttons
  262. auto topButtonArea = bounds.removeFromTop (getHeight() / 20);
  263. topButtonArea.removeFromLeft (20);
  264. clearButton.setBounds (topButtonArea.removeFromLeft (80));
  265. #if JUCE_IOS
  266. topButtonArea.removeFromRight (20);
  267. connectButton.setBounds (topButtonArea.removeFromRight (80));
  268. #endif
  269. bounds.removeFromTop (20);
  270. auto orientation = Desktop::getInstance().getCurrentOrientation();
  271. if (orientation == Desktop::DisplayOrientation::upright
  272. || orientation == Desktop::DisplayOrientation::upsideDown)
  273. {
  274. auto brightnessControlBounds = bounds.removeFromBottom (getHeight() / 10);
  275. brightnessSlider.setSliderStyle (Slider::SliderStyle::LinearHorizontal);
  276. brightnessLED.setBounds (brightnessControlBounds.removeFromLeft (getHeight() / 10));
  277. brightnessSlider.setBounds (brightnessControlBounds);
  278. }
  279. else
  280. {
  281. auto brightnessControlBounds = bounds.removeFromRight (getWidth() / 10);
  282. brightnessSlider.setSliderStyle (Slider::SliderStyle::LinearVertical);
  283. brightnessLED.setBounds (brightnessControlBounds.removeFromTop (getWidth() / 10));
  284. brightnessSlider.setBounds (brightnessControlBounds);
  285. }
  286. // lightpad component
  287. auto sideLength = jmin (bounds.getWidth() - 40, bounds.getHeight() - 40);
  288. lightpadComponent.centreWithSize (sideLength, sideLength);
  289. }
  290. /** Overridden from TopologySource::Listener. Called when the topology changes */
  291. void topologyChanged() override
  292. {
  293. lightpadComponent.setVisible (false);
  294. infoLabel.setVisible (true);
  295. // Reset the activeBlock object
  296. if (activeBlock != nullptr)
  297. detachActiveBlock();
  298. // Get the array of currently connected Block objects from the PhysicalTopologySource
  299. auto blocks = topologySource.getCurrentTopology().blocks;
  300. // Iterate over the array of Block objects
  301. for (auto b : blocks)
  302. {
  303. // Find the first Lightpad
  304. if (b->getType() == Block::Type::lightPadBlock)
  305. {
  306. activeBlock = b;
  307. // Register MainContentComponent as a listener to the touch surface
  308. if (auto surface = activeBlock->getTouchSurface())
  309. surface->addListener (this);
  310. // Register MainContentComponent as a listener to any buttons
  311. for (auto button : activeBlock->getButtons())
  312. button->addListener (this);
  313. // Get the LEDGrid object from the Lightpad and set its program to the program for the current mode
  314. if (auto grid = activeBlock->getLEDGrid())
  315. {
  316. // Work out scale factors to translate X and Y touches to LED indexes
  317. scaleX = (float) (grid->getNumColumns() - 1) / activeBlock->getWidth();
  318. scaleY = (float) (grid->getNumRows() - 1) / activeBlock->getHeight();
  319. setLEDProgram (*activeBlock);
  320. }
  321. // Make the on screen Lighpad component visible
  322. lightpadComponent.setVisible (true);
  323. infoLabel.setVisible (false);
  324. break;
  325. }
  326. }
  327. }
  328. private:
  329. //==============================================================================
  330. /** Overridden from TouchSurface::Listener. Called when a Touch is received on the Lightpad */
  331. void touchChanged (TouchSurface&, const TouchSurface::Touch& touch) override
  332. {
  333. // Translate X and Y touch events to LED indexes
  334. auto xLed = roundToInt (touch.x * scaleX);
  335. auto yLed = roundToInt (touch.y * scaleY);
  336. if (currentMode == colourPalette)
  337. {
  338. if (layout.setActiveColourForTouch (xLed, yLed))
  339. {
  340. if (auto* colourPaletteProgram = getPaletteProgram())
  341. {
  342. colourPaletteProgram->setGridFills (layout.numColumns, layout.numRows, layout.gridFillArray);
  343. brightnessLED.setColour (layout.currentColour
  344. .withBrightness (layout.currentColour == Colours::black ? 0.0f
  345. : static_cast<float> (brightnessSlider.getValue())));
  346. }
  347. }
  348. }
  349. else if (currentMode == canvas)
  350. {
  351. drawLED ((uint32) xLed, (uint32) yLed, touch.z, layout.currentColour);
  352. }
  353. }
  354. /** Overridden from ControlButton::Listener. Called when a button on the Lightpad is pressed */
  355. void buttonPressed (ControlButton&, Block::Timestamp) override {}
  356. /** Overridden from ControlButton::Listener. Called when a button on the Lightpad is released */
  357. void buttonReleased (ControlButton&, Block::Timestamp) override
  358. {
  359. if (currentMode == canvas)
  360. {
  361. // Wait 500ms to see if there is a second press
  362. if (! isTimerRunning())
  363. startTimer (500);
  364. else
  365. doublePress = true;
  366. }
  367. else if (currentMode == colourPalette)
  368. {
  369. // Switch to canvas mode and set the LEDGrid program
  370. currentMode = canvas;
  371. setLEDProgram (*activeBlock);
  372. }
  373. }
  374. void ledClicked (int x, int y, float z) override
  375. {
  376. drawLED ((uint32) x, (uint32) y,
  377. z == 0.0f ? static_cast<float> (brightnessSlider.getValue())
  378. : z * static_cast<float> (brightnessSlider.getValue()), layout.currentColour);
  379. }
  380. void timerCallback() override
  381. {
  382. if (doublePress)
  383. {
  384. clearLEDs();
  385. // Reset the doublePress flag
  386. doublePress = false;
  387. }
  388. else
  389. {
  390. // Switch to colour palette mode and set the LEDGrid program
  391. currentMode = colourPalette;
  392. setLEDProgram (*activeBlock);
  393. }
  394. stopTimer();
  395. }
  396. /** Removes TouchSurface and ControlButton listeners and sets activeBlock to nullptr */
  397. void detachActiveBlock()
  398. {
  399. if (auto surface = activeBlock->getTouchSurface())
  400. surface->removeListener (this);
  401. for (auto button : activeBlock->getButtons())
  402. button->removeListener (this);
  403. activeBlock = nullptr;
  404. }
  405. /** Sets the LEDGrid Program for the selected mode */
  406. void setLEDProgram (Block& block)
  407. {
  408. if (currentMode == canvas)
  409. {
  410. block.setProgram (new BitmapLEDProgram (block));
  411. // Redraw any previously drawn LEDs
  412. redrawLEDs();
  413. }
  414. else if (currentMode == colourPalette)
  415. {
  416. block.setProgram (new DrumPadGridProgram (block));
  417. // Setup the grid layout
  418. if (auto* program = getPaletteProgram())
  419. program->setGridFills (layout.numColumns, layout.numRows, layout.gridFillArray);
  420. }
  421. }
  422. void clearLEDs()
  423. {
  424. if (auto* canvasProgram = getCanvasProgram())
  425. {
  426. // Clear the LED grid
  427. for (uint32 x = 0; x < 15; ++x)
  428. {
  429. for (uint32 y = 0; y < 15; ++ y)
  430. {
  431. canvasProgram->setLED (x, y, Colours::black);
  432. lightpadComponent.setLEDColour ((int) x, (int) y, Colours::black);
  433. }
  434. }
  435. // Clear the ActiveLED array
  436. activeLeds.clear();
  437. }
  438. }
  439. /** Sets an LED on the Lightpad for a given touch co-ordinate and pressure */
  440. void drawLED (uint32 x0, uint32 y0, float z, Colour drawColour)
  441. {
  442. if (auto* canvasProgram = getCanvasProgram())
  443. {
  444. // Check if the activeLeds array already contains an ActiveLED object for this LED
  445. auto index = getLEDAt (x0, y0);
  446. // If the colour is black then just set the LED to black and return
  447. if (drawColour == Colours::black)
  448. {
  449. if (index >= 0)
  450. {
  451. canvasProgram->setLED (x0, y0, Colours::black);
  452. lightpadComponent.setLEDColour ((int) x0, (int) y0, Colours::black);
  453. activeLeds.remove (index);
  454. }
  455. return;
  456. }
  457. // If there is no ActiveLED obejct for this LED then create one,
  458. // add it to the array, set the LED on the Block and return
  459. if (index < 0)
  460. {
  461. ActiveLED led;
  462. led.x = x0;
  463. led.y = y0;
  464. led.colour = drawColour;
  465. led.brightness = z;
  466. activeLeds.add (led);
  467. canvasProgram->setLED (led.x, led.y, led.colour.withBrightness (led.brightness));
  468. lightpadComponent.setLEDColour ((int) led.x, (int) led.y, led.colour.withBrightness (led.brightness));
  469. return;
  470. }
  471. // Get the ActiveLED object for this LED
  472. auto currentLed = activeLeds.getReference (index);
  473. // If the LED colour is the same as the draw colour, add the brightnesses together.
  474. // If it is different, blend the colours
  475. if (currentLed.colour == drawColour)
  476. currentLed.brightness = jmin (currentLed.brightness + z, 1.0f);
  477. else
  478. currentLed.colour = currentLed.colour.interpolatedWith (drawColour, z);
  479. // Set the LED on the Block and change the ActiveLED object in the activeLeds array
  480. if (canvasProgram != nullptr)
  481. canvasProgram->setLED (currentLed.x, currentLed.y, currentLed.colour.withBrightness (currentLed.brightness));
  482. lightpadComponent.setLEDColour ((int) currentLed.x, (int) currentLed.y, currentLed.colour.withBrightness (currentLed.brightness));
  483. activeLeds.set (index, currentLed);
  484. }
  485. }
  486. /** Redraws the LEDs on the Lightpad from the activeLeds array */
  487. void redrawLEDs()
  488. {
  489. if (auto* canvasProgram = getCanvasProgram())
  490. {
  491. // Iterate over the activeLeds array and set the LEDs on the Block
  492. for (auto led : activeLeds)
  493. {
  494. canvasProgram->setLED (led.x, led.y, led.colour.withBrightness (led.brightness));
  495. lightpadComponent.setLEDColour ((int) led.x, (int) led.y, led.colour.withBrightness (led.brightness));
  496. }
  497. }
  498. }
  499. //==============================================================================
  500. BitmapLEDProgram* getCanvasProgram()
  501. {
  502. if (activeBlock != nullptr)
  503. return dynamic_cast<BitmapLEDProgram*> (activeBlock->getProgram());
  504. return nullptr;
  505. }
  506. DrumPadGridProgram* getPaletteProgram()
  507. {
  508. if (activeBlock != nullptr)
  509. return dynamic_cast<DrumPadGridProgram*> (activeBlock->getProgram());
  510. return nullptr;
  511. }
  512. //==============================================================================
  513. /**
  514. A struct that represents an active LED on the Lightpad.
  515. Has a position, colour and brightness.
  516. */
  517. struct ActiveLED
  518. {
  519. uint32 x, y;
  520. Colour colour;
  521. float brightness;
  522. /** Returns true if this LED occupies the given co-ordinates */
  523. bool occupies (uint32 xPos, uint32 yPos) const
  524. {
  525. return xPos == x && yPos == y;
  526. }
  527. };
  528. Array<ActiveLED> activeLeds;
  529. int getLEDAt (uint32 x, uint32 y) const
  530. {
  531. for (auto i = 0; i < activeLeds.size(); ++i)
  532. if (activeLeds.getReference (i).occupies (x, y))
  533. return i;
  534. return -1;
  535. }
  536. //==============================================================================
  537. enum DisplayMode
  538. {
  539. colourPalette = 0,
  540. canvas
  541. };
  542. DisplayMode currentMode = colourPalette;
  543. //==============================================================================
  544. ColourGrid layout { 3, 3 };
  545. PhysicalTopologySource topologySource;
  546. Block::Ptr activeBlock;
  547. float scaleX = 0.0f;
  548. float scaleY = 0.0f;
  549. bool doublePress = false;
  550. Label infoLabel;
  551. DrawableLightpadComponent lightpadComponent;
  552. TextButton clearButton;
  553. LEDComponent brightnessLED;
  554. Slider brightnessSlider;
  555. #if JUCE_IOS
  556. TextButton connectButton;
  557. #endif
  558. //==============================================================================
  559. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlocksDrawingDemo)
  560. };