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.

787 lines
31KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  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 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #include <juce_core/system/juce_TargetPlatform.h>
  19. #if JucePlugin_Build_Unity
  20. #include "../utility/juce_IncludeModuleHeaders.h"
  21. #include <juce_audio_processors/format_types/juce_LegacyAudioParameter.cpp>
  22. #if JUCE_WINDOWS
  23. #include "../utility/juce_IncludeSystemHeaders.h"
  24. #endif
  25. #include "juce_UnityPluginInterface.h"
  26. //==============================================================================
  27. namespace juce
  28. {
  29. typedef ComponentPeer* (*createUnityPeerFunctionType) (Component&);
  30. extern createUnityPeerFunctionType juce_createUnityPeerFn;
  31. //==============================================================================
  32. class UnityPeer : public ComponentPeer,
  33. public AsyncUpdater
  34. {
  35. public:
  36. UnityPeer (Component& ed)
  37. : ComponentPeer (ed, 0),
  38. mouseWatcher (*this)
  39. {
  40. getEditor().setResizable (false, false);
  41. }
  42. //==============================================================================
  43. Rectangle<int> getBounds() const override { return bounds; }
  44. Point<float> localToGlobal (Point<float> relativePosition) override { return relativePosition + getBounds().getPosition().toFloat(); }
  45. Point<float> globalToLocal (Point<float> screenPosition) override { return screenPosition - getBounds().getPosition().toFloat(); }
  46. using ComponentPeer::localToGlobal;
  47. using ComponentPeer::globalToLocal;
  48. StringArray getAvailableRenderingEngines() override { return StringArray ("Software Renderer"); }
  49. void setBounds (const Rectangle<int>& newBounds, bool) override
  50. {
  51. bounds = newBounds;
  52. mouseWatcher.setBoundsToWatch (bounds);
  53. }
  54. bool contains (Point<int> localPos, bool) const override
  55. {
  56. if (isPositiveAndBelow (localPos.getX(), getBounds().getWidth())
  57. && isPositiveAndBelow (localPos.getY(), getBounds().getHeight()))
  58. return true;
  59. return false;
  60. }
  61. void handleAsyncUpdate() override
  62. {
  63. fillPixels();
  64. }
  65. //==============================================================================
  66. AudioProcessorEditor& getEditor() { return *dynamic_cast<AudioProcessorEditor*> (&getComponent()); }
  67. void setPixelDataHandle (uint8* handle, int width, int height)
  68. {
  69. pixelData = handle;
  70. textureWidth = width;
  71. textureHeight = height;
  72. renderImage = Image (new UnityBitmapImage (pixelData, width, height));
  73. }
  74. // N.B. This is NOT an efficient way to do this and you shouldn't use this method in your own code.
  75. // It works for our purposes here but a much more efficient way would be to use a GL texture.
  76. void fillPixels()
  77. {
  78. if (pixelData == nullptr)
  79. return;
  80. LowLevelGraphicsSoftwareRenderer renderer (renderImage);
  81. renderer.addTransform (AffineTransform::verticalFlip ((float) getComponent().getHeight()));
  82. handlePaint (renderer);
  83. for (int i = 0; i < textureWidth * textureHeight * 4; i += 4)
  84. {
  85. auto r = pixelData[i + 2];
  86. auto g = pixelData[i + 1];
  87. auto b = pixelData[i + 0];
  88. pixelData[i + 0] = r;
  89. pixelData[i + 1] = g;
  90. pixelData[i + 2] = b;
  91. }
  92. }
  93. void forwardMouseEvent (Point<float> position, ModifierKeys mods)
  94. {
  95. ModifierKeys::currentModifiers = mods;
  96. handleMouseEvent (juce::MouseInputSource::mouse, position, mods, juce::MouseInputSource::defaultPressure,
  97. juce::MouseInputSource::defaultOrientation, juce::Time::currentTimeMillis());
  98. }
  99. void forwardKeyPress (int code, String name, ModifierKeys mods)
  100. {
  101. ModifierKeys::currentModifiers = mods;
  102. handleKeyPress (getKeyPress (code, name));
  103. }
  104. private:
  105. //==============================================================================
  106. struct UnityBitmapImage : public ImagePixelData
  107. {
  108. UnityBitmapImage (uint8* data, int w, int h)
  109. : ImagePixelData (Image::PixelFormat::ARGB, w, h),
  110. imageData (data),
  111. lineStride (width * pixelStride)
  112. {
  113. }
  114. std::unique_ptr<ImageType> createType() const override
  115. {
  116. return std::make_unique<SoftwareImageType>();
  117. }
  118. std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() override
  119. {
  120. return std::make_unique<LowLevelGraphicsSoftwareRenderer> (Image (this));
  121. }
  122. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode) override
  123. {
  124. ignoreUnused (mode);
  125. bitmap.data = imageData + x * pixelStride + y * lineStride;
  126. bitmap.pixelFormat = pixelFormat;
  127. bitmap.lineStride = lineStride;
  128. bitmap.pixelStride = pixelStride;
  129. }
  130. ImagePixelData::Ptr clone() override
  131. {
  132. auto im = new UnityBitmapImage (imageData, width, height);
  133. for (int i = 0; i < height; ++i)
  134. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, (size_t) lineStride);
  135. return im;
  136. }
  137. uint8* imageData;
  138. int pixelStride = 4, lineStride;
  139. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UnityBitmapImage)
  140. };
  141. //==============================================================================
  142. struct MouseWatcher : public Timer
  143. {
  144. MouseWatcher (ComponentPeer& o) : owner (o) {}
  145. void timerCallback() override
  146. {
  147. auto pos = Desktop::getMousePosition();
  148. if (boundsToWatch.contains (pos) && pos != lastMousePos)
  149. {
  150. auto ms = Desktop::getInstance().getMainMouseSource();
  151. if (! ms.getCurrentModifiers().isLeftButtonDown())
  152. owner.handleMouseEvent (juce::MouseInputSource::mouse, owner.globalToLocal (pos.toFloat()), {},
  153. juce::MouseInputSource::defaultPressure, juce::MouseInputSource::defaultOrientation, juce::Time::currentTimeMillis());
  154. lastMousePos = pos;
  155. }
  156. }
  157. void setBoundsToWatch (Rectangle<int> b)
  158. {
  159. if (boundsToWatch != b)
  160. boundsToWatch = b;
  161. startTimer (250);
  162. }
  163. ComponentPeer& owner;
  164. Rectangle<int> boundsToWatch;
  165. Point<int> lastMousePos;
  166. };
  167. //==============================================================================
  168. KeyPress getKeyPress (int keyCode, String name)
  169. {
  170. if (keyCode >= 32 && keyCode <= 64)
  171. return { keyCode, ModifierKeys::currentModifiers, juce::juce_wchar (keyCode) };
  172. if (keyCode >= 91 && keyCode <= 122)
  173. return { keyCode, ModifierKeys::currentModifiers, name[0] };
  174. if (keyCode >= 256 && keyCode <= 265)
  175. return { juce::KeyPress::numberPad0 + (keyCode - 256), ModifierKeys::currentModifiers, juce::String (keyCode - 256).getCharPointer()[0] };
  176. if (keyCode == 8) return { juce::KeyPress::backspaceKey, ModifierKeys::currentModifiers, {} };
  177. if (keyCode == 127) return { juce::KeyPress::deleteKey, ModifierKeys::currentModifiers, {} };
  178. if (keyCode == 9) return { juce::KeyPress::tabKey, ModifierKeys::currentModifiers, {} };
  179. if (keyCode == 13) return { juce::KeyPress::returnKey, ModifierKeys::currentModifiers, {} };
  180. if (keyCode == 27) return { juce::KeyPress::escapeKey, ModifierKeys::currentModifiers, {} };
  181. if (keyCode == 32) return { juce::KeyPress::spaceKey, ModifierKeys::currentModifiers, {} };
  182. if (keyCode == 266) return { juce::KeyPress::numberPadDecimalPoint, ModifierKeys::currentModifiers, {} };
  183. if (keyCode == 267) return { juce::KeyPress::numberPadDivide, ModifierKeys::currentModifiers, {} };
  184. if (keyCode == 268) return { juce::KeyPress::numberPadMultiply, ModifierKeys::currentModifiers, {} };
  185. if (keyCode == 269) return { juce::KeyPress::numberPadSubtract, ModifierKeys::currentModifiers, {} };
  186. if (keyCode == 270) return { juce::KeyPress::numberPadAdd, ModifierKeys::currentModifiers, {} };
  187. if (keyCode == 272) return { juce::KeyPress::numberPadEquals, ModifierKeys::currentModifiers, {} };
  188. if (keyCode == 273) return { juce::KeyPress::upKey, ModifierKeys::currentModifiers, {} };
  189. if (keyCode == 274) return { juce::KeyPress::downKey, ModifierKeys::currentModifiers, {} };
  190. if (keyCode == 275) return { juce::KeyPress::rightKey, ModifierKeys::currentModifiers, {} };
  191. if (keyCode == 276) return { juce::KeyPress::leftKey, ModifierKeys::currentModifiers, {} };
  192. return {};
  193. }
  194. //==============================================================================
  195. Rectangle<int> bounds;
  196. MouseWatcher mouseWatcher;
  197. uint8* pixelData = nullptr;
  198. int textureWidth, textureHeight;
  199. Image renderImage;
  200. //==============================================================================
  201. void setMinimised (bool) override {}
  202. bool isMinimised() const override { return false; }
  203. void setFullScreen (bool) override {}
  204. bool isFullScreen() const override { return false; }
  205. bool setAlwaysOnTop (bool) override { return false; }
  206. void toFront (bool) override {}
  207. void toBehind (ComponentPeer*) override {}
  208. bool isFocused() const override { return true; }
  209. void grabFocus() override {}
  210. void* getNativeHandle() const override { return nullptr; }
  211. OptionalBorderSize getFrameSizeIfPresent() const override { return {}; }
  212. BorderSize<int> getFrameSize() const override { return {}; }
  213. void setVisible (bool) override {}
  214. void setTitle (const String&) override {}
  215. void setIcon (const Image&) override {}
  216. void textInputRequired (Point<int>, TextInputTarget&) override {}
  217. void setAlpha (float) override {}
  218. void performAnyPendingRepaintsNow() override {}
  219. void repaint (const Rectangle<int>&) override {}
  220. //==============================================================================
  221. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UnityPeer)
  222. };
  223. ComponentPeer* createUnityPeer (Component& c) { return new UnityPeer (c); }
  224. //==============================================================================
  225. class AudioProcessorUnityWrapper
  226. {
  227. public:
  228. AudioProcessorUnityWrapper (bool isTemporary)
  229. {
  230. pluginInstance.reset (createPluginFilterOfType (AudioProcessor::wrapperType_Unity));
  231. if (! isTemporary && pluginInstance->hasEditor())
  232. {
  233. pluginInstanceEditor.reset (pluginInstance->createEditorIfNeeded());
  234. pluginInstanceEditor->setVisible (true);
  235. pluginInstanceEditor->addToDesktop (0);
  236. }
  237. juceParameters.update (*pluginInstance, false);
  238. }
  239. ~AudioProcessorUnityWrapper()
  240. {
  241. if (pluginInstanceEditor != nullptr)
  242. {
  243. pluginInstanceEditor->removeFromDesktop();
  244. PopupMenu::dismissAllActiveMenus();
  245. pluginInstanceEditor->processor.editorBeingDeleted (pluginInstanceEditor.get());
  246. pluginInstanceEditor = nullptr;
  247. }
  248. }
  249. void create (UnityAudioEffectState* state)
  250. {
  251. // only supported in Unity plugin API > 1.0
  252. if (state->structSize >= sizeof (UnityAudioEffectState))
  253. samplesPerBlock = static_cast<int> (state->dspBufferSize);
  254. #ifdef JucePlugin_PreferredChannelConfigurations
  255. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  256. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  257. jassertquiet (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
  258. pluginInstance->setPlayConfigDetails (configs[0][0], configs[0][1], state->sampleRate, samplesPerBlock);
  259. #else
  260. pluginInstance->setRateAndBufferSizeDetails (state->sampleRate, samplesPerBlock);
  261. #endif
  262. pluginInstance->prepareToPlay (state->sampleRate, samplesPerBlock);
  263. scratchBuffer.setSize (jmax (pluginInstance->getTotalNumInputChannels(), pluginInstance->getTotalNumOutputChannels()), samplesPerBlock);
  264. }
  265. void release()
  266. {
  267. pluginInstance->releaseResources();
  268. }
  269. void reset()
  270. {
  271. pluginInstance->reset();
  272. }
  273. void process (float* inBuffer, float* outBuffer, int bufferSize, int numInChannels, int numOutChannels, bool isBypassed)
  274. {
  275. // If the plugin has a bypass parameter, set it to the current bypass state
  276. if (auto* param = pluginInstance->getBypassParameter())
  277. if (isBypassed != (param->getValue() >= 0.5f))
  278. param->setValueNotifyingHost (isBypassed ? 1.0f : 0.0f);
  279. for (int pos = 0; pos < bufferSize;)
  280. {
  281. auto max = jmin (bufferSize - pos, samplesPerBlock);
  282. processBuffers (inBuffer + (pos * numInChannels), outBuffer + (pos * numOutChannels), max, numInChannels, numOutChannels, isBypassed);
  283. pos += max;
  284. }
  285. }
  286. void declareParameters (UnityAudioEffectDefinition& definition)
  287. {
  288. static std::unique_ptr<UnityAudioParameterDefinition> parametersPtr;
  289. static int numParams = 0;
  290. if (parametersPtr == nullptr)
  291. {
  292. numParams = (int) juceParameters.size();
  293. parametersPtr.reset (static_cast<UnityAudioParameterDefinition*> (std::calloc (static_cast<size_t> (numParams),
  294. sizeof (UnityAudioParameterDefinition))));
  295. parameterDescriptions.clear();
  296. for (int i = 0; i < numParams; ++i)
  297. {
  298. auto* parameter = juceParameters.getParamForIndex (i);
  299. auto& paramDef = parametersPtr.get()[i];
  300. const auto nameLength = (size_t) numElementsInArray (paramDef.name);
  301. const auto unitLength = (size_t) numElementsInArray (paramDef.unit);
  302. parameter->getName ((int) nameLength - 1).copyToUTF8 (paramDef.name, nameLength);
  303. if (parameter->getLabel().isNotEmpty())
  304. parameter->getLabel().copyToUTF8 (paramDef.unit, unitLength);
  305. parameterDescriptions.add (parameter->getName (15));
  306. paramDef.description = parameterDescriptions[i].toRawUTF8();
  307. paramDef.defaultVal = parameter->getDefaultValue();
  308. paramDef.min = 0.0f;
  309. paramDef.max = 1.0f;
  310. paramDef.displayScale = 1.0f;
  311. paramDef.displayExponent = 1.0f;
  312. }
  313. }
  314. definition.numParameters = static_cast<uint32> (numParams);
  315. definition.parameterDefintions = parametersPtr.get();
  316. }
  317. void setParameter (int index, float value) { juceParameters.getParamForIndex (index)->setValueNotifyingHost (value); }
  318. float getParameter (int index) const noexcept { return juceParameters.getParamForIndex (index)->getValue(); }
  319. String getParameterString (int index) const noexcept
  320. {
  321. auto* param = juceParameters.getParamForIndex (index);
  322. return param->getText (param->getValue(), 16);
  323. }
  324. int getNumInputChannels() const noexcept { return pluginInstance->getTotalNumInputChannels(); }
  325. int getNumOutputChannels() const noexcept { return pluginInstance->getTotalNumOutputChannels(); }
  326. bool hasEditor() const noexcept { return pluginInstance->hasEditor(); }
  327. UnityPeer& getEditorPeer() const
  328. {
  329. auto* peer = dynamic_cast<UnityPeer*> (pluginInstanceEditor->getPeer());
  330. jassert (peer != nullptr);
  331. return *peer;
  332. }
  333. private:
  334. //==============================================================================
  335. void processBuffers (float* inBuffer, float* outBuffer, int bufferSize, int numInChannels, int numOutChannels, bool isBypassed)
  336. {
  337. int ch;
  338. for (ch = 0; ch < numInChannels; ++ch)
  339. {
  340. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst>;
  341. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::Interleaved, AudioData::Const>;
  342. DstSampleType dstData (scratchBuffer.getWritePointer (ch));
  343. SrcSampleType srcData (inBuffer + ch, numInChannels);
  344. dstData.convertSamples (srcData, bufferSize);
  345. }
  346. for (; ch < numOutChannels; ++ch)
  347. scratchBuffer.clear (ch, 0, bufferSize);
  348. {
  349. const ScopedLock sl (pluginInstance->getCallbackLock());
  350. if (pluginInstance->isSuspended())
  351. {
  352. scratchBuffer.clear();
  353. }
  354. else
  355. {
  356. MidiBuffer mb;
  357. if (isBypassed && pluginInstance->getBypassParameter() == nullptr)
  358. pluginInstance->processBlockBypassed (scratchBuffer, mb);
  359. else
  360. pluginInstance->processBlock (scratchBuffer, mb);
  361. }
  362. }
  363. for (ch = 0; ch < numOutChannels; ++ch)
  364. {
  365. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::Interleaved, AudioData::NonConst>;
  366. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const>;
  367. DstSampleType dstData (outBuffer + ch, numOutChannels);
  368. SrcSampleType srcData (scratchBuffer.getReadPointer (ch));
  369. dstData.convertSamples (srcData, bufferSize);
  370. }
  371. }
  372. //==============================================================================
  373. std::unique_ptr<AudioProcessor> pluginInstance;
  374. std::unique_ptr<AudioProcessorEditor> pluginInstanceEditor;
  375. int samplesPerBlock = 1024;
  376. StringArray parameterDescriptions;
  377. AudioBuffer<float> scratchBuffer;
  378. LegacyAudioParametersWrapper juceParameters;
  379. //==============================================================================
  380. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorUnityWrapper)
  381. };
  382. //==============================================================================
  383. HashMap<int, AudioProcessorUnityWrapper*>& getWrapperMap()
  384. {
  385. static HashMap<int, AudioProcessorUnityWrapper*> wrapperMap;
  386. return wrapperMap;
  387. }
  388. static void onWrapperCreation (AudioProcessorUnityWrapper* wrapperToAdd)
  389. {
  390. getWrapperMap().set (std::abs (Random::getSystemRandom().nextInt (65536)), wrapperToAdd);
  391. }
  392. static void onWrapperDeletion (AudioProcessorUnityWrapper* wrapperToRemove)
  393. {
  394. getWrapperMap().removeValue (wrapperToRemove);
  395. }
  396. //==============================================================================
  397. namespace UnityCallbacks
  398. {
  399. int UNITY_INTERFACE_API createCallback (UnityAudioEffectState* state)
  400. {
  401. auto* pluginInstance = new AudioProcessorUnityWrapper (false);
  402. pluginInstance->create (state);
  403. state->effectData = pluginInstance;
  404. onWrapperCreation (pluginInstance);
  405. return 0;
  406. }
  407. int UNITY_INTERFACE_API releaseCallback (UnityAudioEffectState* state)
  408. {
  409. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  410. pluginInstance->release();
  411. onWrapperDeletion (pluginInstance);
  412. delete pluginInstance;
  413. if (getWrapperMap().size() == 0)
  414. shutdownJuce_GUI();
  415. return 0;
  416. }
  417. int UNITY_INTERFACE_API resetCallback (UnityAudioEffectState* state)
  418. {
  419. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  420. pluginInstance->reset();
  421. return 0;
  422. }
  423. int UNITY_INTERFACE_API setPositionCallback (UnityAudioEffectState* state, unsigned int pos)
  424. {
  425. ignoreUnused (state, pos);
  426. return 0;
  427. }
  428. int UNITY_INTERFACE_API setFloatParameterCallback (UnityAudioEffectState* state, int index, float value)
  429. {
  430. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  431. pluginInstance->setParameter (index, value);
  432. return 0;
  433. }
  434. int UNITY_INTERFACE_API getFloatParameterCallback (UnityAudioEffectState* state, int index, float* value, char* valueStr)
  435. {
  436. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  437. *value = pluginInstance->getParameter (index);
  438. pluginInstance->getParameterString (index).copyToUTF8 (valueStr, 15);
  439. return 0;
  440. }
  441. int UNITY_INTERFACE_API getFloatBufferCallback (UnityAudioEffectState* state, const char* name, float* buffer, int numSamples)
  442. {
  443. ignoreUnused (numSamples);
  444. auto nameStr = String (name);
  445. if (nameStr == "Editor")
  446. {
  447. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  448. buffer[0] = pluginInstance->hasEditor() ? 1.0f : 0.0f;
  449. }
  450. else if (nameStr == "ID")
  451. {
  452. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  453. for (HashMap<int, AudioProcessorUnityWrapper*>::Iterator i (getWrapperMap()); i.next();)
  454. {
  455. if (i.getValue() == pluginInstance)
  456. {
  457. buffer[0] = (float) i.getKey();
  458. break;
  459. }
  460. }
  461. return 0;
  462. }
  463. else if (nameStr == "Size")
  464. {
  465. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  466. auto& editor = pluginInstance->getEditorPeer().getEditor();
  467. buffer[0] = (float) editor.getBounds().getWidth();
  468. buffer[1] = (float) editor.getBounds().getHeight();
  469. buffer[2] = (float) editor.getConstrainer()->getMinimumWidth();
  470. buffer[3] = (float) editor.getConstrainer()->getMinimumHeight();
  471. buffer[4] = (float) editor.getConstrainer()->getMaximumWidth();
  472. buffer[5] = (float) editor.getConstrainer()->getMaximumHeight();
  473. }
  474. return 0;
  475. }
  476. int UNITY_INTERFACE_API processCallback (UnityAudioEffectState* state, float* inBuffer, float* outBuffer,
  477. unsigned int bufferSize, int numInChannels, int numOutChannels)
  478. {
  479. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  480. if (pluginInstance != nullptr)
  481. {
  482. auto isPlaying = ((state->flags & stateIsPlaying) != 0);
  483. auto isMuted = ((state->flags & stateIsMuted) != 0);
  484. auto isPaused = ((state->flags & stateIsPaused) != 0);
  485. const auto bypassed = ! isPlaying || (isMuted || isPaused);
  486. pluginInstance->process (inBuffer, outBuffer, static_cast<int> (bufferSize), numInChannels, numOutChannels, bypassed);
  487. }
  488. else
  489. {
  490. FloatVectorOperations::clear (outBuffer, static_cast<int> (bufferSize) * numOutChannels);
  491. }
  492. return 0;
  493. }
  494. }
  495. //==============================================================================
  496. static void declareEffect (UnityAudioEffectDefinition& definition)
  497. {
  498. memset (&definition, 0, sizeof (definition));
  499. std::unique_ptr<AudioProcessorUnityWrapper> wrapper = std::make_unique<AudioProcessorUnityWrapper> (true);
  500. String name (JucePlugin_Name);
  501. if (! name.startsWithIgnoreCase ("audioplugin"))
  502. name = "audioplugin_" + name;
  503. name.copyToUTF8 (definition.name, (size_t) numElementsInArray (definition.name));
  504. definition.structSize = sizeof (UnityAudioEffectDefinition);
  505. definition.parameterStructSize = sizeof (UnityAudioParameterDefinition);
  506. definition.apiVersion = UNITY_AUDIO_PLUGIN_API_VERSION;
  507. definition.pluginVersion = JucePlugin_VersionCode;
  508. // effects must set this to 0, generators > 0
  509. definition.channels = (wrapper->getNumInputChannels() != 0 ? 0
  510. : static_cast<uint32> (wrapper->getNumOutputChannels()));
  511. wrapper->declareParameters (definition);
  512. definition.create = UnityCallbacks::createCallback;
  513. definition.release = UnityCallbacks::releaseCallback;
  514. definition.reset = UnityCallbacks::resetCallback;
  515. definition.setPosition = UnityCallbacks::setPositionCallback;
  516. definition.process = UnityCallbacks::processCallback;
  517. definition.setFloatParameter = UnityCallbacks::setFloatParameterCallback;
  518. definition.getFloatParameter = UnityCallbacks::getFloatParameterCallback;
  519. definition.getFloatBuffer = UnityCallbacks::getFloatBufferCallback;
  520. }
  521. } // namespace juce
  522. UNITY_INTERFACE_EXPORT int UNITY_INTERFACE_API UnityGetAudioEffectDefinitions (UnityAudioEffectDefinition*** definitionsPtr)
  523. {
  524. if (juce::getWrapperMap().size() == 0)
  525. juce::initialiseJuce_GUI();
  526. static bool hasInitialised = false;
  527. if (! hasInitialised)
  528. {
  529. juce::PluginHostType::jucePlugInClientCurrentWrapperType = juce::AudioProcessor::wrapperType_Unity;
  530. juce::juce_createUnityPeerFn = juce::createUnityPeer;
  531. hasInitialised = true;
  532. }
  533. auto* definition = new UnityAudioEffectDefinition();
  534. juce::declareEffect (*definition);
  535. *definitionsPtr = &definition;
  536. return 1;
  537. }
  538. //==============================================================================
  539. static juce::ModifierKeys unityModifiersToJUCE (UnityEventModifiers mods, bool mouseDown, int mouseButton = -1)
  540. {
  541. int flags = 0;
  542. if (mouseDown)
  543. {
  544. if (mouseButton == 0)
  545. flags |= juce::ModifierKeys::leftButtonModifier;
  546. else if (mouseButton == 1)
  547. flags |= juce::ModifierKeys::rightButtonModifier;
  548. else if (mouseButton == 2)
  549. flags |= juce::ModifierKeys::middleButtonModifier;
  550. }
  551. if (mods == 0)
  552. return flags;
  553. if ((mods & UnityEventModifiers::shift) != 0) flags |= juce::ModifierKeys::shiftModifier;
  554. if ((mods & UnityEventModifiers::control) != 0) flags |= juce::ModifierKeys::ctrlModifier;
  555. if ((mods & UnityEventModifiers::alt) != 0) flags |= juce::ModifierKeys::altModifier;
  556. if ((mods & UnityEventModifiers::command) != 0) flags |= juce::ModifierKeys::commandModifier;
  557. return { flags };
  558. }
  559. //==============================================================================
  560. static juce::AudioProcessorUnityWrapper* getWrapperChecked (int id)
  561. {
  562. auto* wrapper = juce::getWrapperMap()[id];
  563. jassert (wrapper != nullptr);
  564. return wrapper;
  565. }
  566. //==============================================================================
  567. static void UNITY_INTERFACE_API onRenderEvent (int id)
  568. {
  569. getWrapperChecked (id)->getEditorPeer().triggerAsyncUpdate();
  570. }
  571. UNITY_INTERFACE_EXPORT renderCallback UNITY_INTERFACE_API getRenderCallback()
  572. {
  573. return onRenderEvent;
  574. }
  575. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unityInitialiseTexture (int id, void* data, int w, int h)
  576. {
  577. getWrapperChecked (id)->getEditorPeer().setPixelDataHandle (reinterpret_cast<juce::uint8*> (data), w, h);
  578. }
  579. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unityMouseDown (int id, float x, float y, UnityEventModifiers unityMods, int button)
  580. {
  581. getWrapperChecked (id)->getEditorPeer().forwardMouseEvent ({ x, y }, unityModifiersToJUCE (unityMods, true, button));
  582. }
  583. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unityMouseDrag (int id, float x, float y, UnityEventModifiers unityMods, int button)
  584. {
  585. getWrapperChecked (id)->getEditorPeer().forwardMouseEvent ({ x, y }, unityModifiersToJUCE (unityMods, true, button));
  586. }
  587. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unityMouseUp (int id, float x, float y, UnityEventModifiers unityMods)
  588. {
  589. getWrapperChecked (id)->getEditorPeer().forwardMouseEvent ({ x, y }, unityModifiersToJUCE (unityMods, false));
  590. }
  591. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unityKeyEvent (int id, int code, UnityEventModifiers mods, const char* name)
  592. {
  593. getWrapperChecked (id)->getEditorPeer().forwardKeyPress (code, name, unityModifiersToJUCE (mods, false));
  594. }
  595. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unitySetScreenBounds (int id, float x, float y, float w, float h)
  596. {
  597. getWrapperChecked (id)->getEditorPeer().getEditor().setBounds ({ (int) x, (int) y, (int) w, (int) h });
  598. }
  599. //==============================================================================
  600. #if JUCE_WINDOWS
  601. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID)
  602. {
  603. if (reason == DLL_PROCESS_ATTACH)
  604. juce::Process::setCurrentModuleInstanceHandle (instance);
  605. return true;
  606. }
  607. #endif
  608. #endif