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.

89 lines
2.5KB

  1. /*
  2. ==============================================================================
  3. JUCE demo code - use at your own risk!
  4. ==============================================================================
  5. */
  6. /*
  7. This component represents a horizontal vibrating musical string of fixed height
  8. and variable length. The string can be excited by calling stringPlucked().
  9. */
  10. class StringComponent : public Component,
  11. private Timer
  12. {
  13. public:
  14. StringComponent (int lengthInPixels, Colour stringColour)
  15. : length (lengthInPixels), colour (stringColour)
  16. {
  17. // ignore mouse-clicks so that our parent can get them instead.
  18. setInterceptsMouseClicks (false, false);
  19. setSize (length, height);
  20. startTimerHz (60);
  21. }
  22. //=======================================================================
  23. void stringPlucked (float pluckPositionRelative)
  24. {
  25. amplitude = maxAmplitude * std::sin (pluckPositionRelative * float_Pi);
  26. phase = float_Pi;
  27. }
  28. //=======================================================================
  29. void paint (Graphics& g) override
  30. {
  31. g.setColour (colour);
  32. g.strokePath (generateStringPath(), PathStrokeType (2.0f));
  33. }
  34. Path generateStringPath() const
  35. {
  36. const float y = height / 2.0f;
  37. Path stringPath;
  38. stringPath.startNewSubPath (0, y);
  39. stringPath.quadraticTo (length / 2.0f, y + (std::sin (phase) * amplitude), (float) length, y);
  40. return stringPath;
  41. }
  42. //==============================================================================
  43. void timerCallback() override
  44. {
  45. updateAmplitude();
  46. updatePhase();
  47. repaint();
  48. }
  49. void updateAmplitude()
  50. {
  51. // this determines the decay of the visible string vibration.
  52. amplitude *= 0.99f;
  53. }
  54. void updatePhase()
  55. {
  56. // this determines the visible vibration frequency.
  57. // just an arbitrary number chosen to look OK:
  58. const float phaseStep = 400.0f / length;
  59. phase += phaseStep;
  60. if (phase > float_Pi)
  61. phase -= 2.0f * float_Pi;
  62. }
  63. private:
  64. //=======================================================================
  65. int length;
  66. Colour colour;
  67. int height = 20;
  68. float amplitude = 0.0f;
  69. const float maxAmplitude = 12.0f;
  70. float phase = 0.0f;
  71. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (StringComponent)
  72. };