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.

776 lines
30KB

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