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.

784 lines
30KB

  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::invalidPressure,
  97. juce::MouseInputSource::invalidOrientation, 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::invalidPressure, juce::MouseInputSource::invalidOrientation, 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. BorderSize<int> getFrameSize() const override { return {}; }
  212. void setVisible (bool) override {}
  213. void setTitle (const String&) override {}
  214. void setIcon (const Image&) override {}
  215. void textInputRequired (Point<int>, TextInputTarget&) override {}
  216. void setAlpha (float) override {}
  217. void performAnyPendingRepaintsNow() override {}
  218. void repaint (const Rectangle<int>&) override {}
  219. //==============================================================================
  220. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UnityPeer)
  221. };
  222. ComponentPeer* createUnityPeer (Component& c) { return new UnityPeer (c); }
  223. //==============================================================================
  224. class AudioProcessorUnityWrapper
  225. {
  226. public:
  227. AudioProcessorUnityWrapper (bool isTemporary)
  228. {
  229. pluginInstance.reset (createPluginFilterOfType (AudioProcessor::wrapperType_Unity));
  230. if (! isTemporary && pluginInstance->hasEditor())
  231. {
  232. pluginInstanceEditor.reset (pluginInstance->createEditorIfNeeded());
  233. pluginInstanceEditor->setVisible (true);
  234. pluginInstanceEditor->addToDesktop (0);
  235. }
  236. juceParameters.update (*pluginInstance, false);
  237. }
  238. ~AudioProcessorUnityWrapper()
  239. {
  240. if (pluginInstanceEditor != nullptr)
  241. {
  242. pluginInstanceEditor->removeFromDesktop();
  243. PopupMenu::dismissAllActiveMenus();
  244. pluginInstanceEditor->processor.editorBeingDeleted (pluginInstanceEditor.get());
  245. pluginInstanceEditor = nullptr;
  246. }
  247. }
  248. void create (UnityAudioEffectState* state)
  249. {
  250. // only supported in Unity plugin API > 1.0
  251. if (state->structSize >= sizeof (UnityAudioEffectState))
  252. samplesPerBlock = static_cast<int> (state->dspBufferSize);
  253. #ifdef JucePlugin_PreferredChannelConfigurations
  254. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  255. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  256. jassert (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
  257. ignoreUnused (numConfigs);
  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. for (int pos = 0; pos < bufferSize;)
  276. {
  277. auto max = jmin (bufferSize - pos, samplesPerBlock);
  278. processBuffers (inBuffer + (pos * numInChannels), outBuffer + (pos * numOutChannels), max, numInChannels, numOutChannels, isBypassed);
  279. pos += max;
  280. }
  281. }
  282. void declareParameters (UnityAudioEffectDefinition& definition)
  283. {
  284. static std::unique_ptr<UnityAudioParameterDefinition> parametersPtr;
  285. static int numParams = 0;
  286. if (parametersPtr == nullptr)
  287. {
  288. numParams = juceParameters.params.size();
  289. parametersPtr.reset (static_cast<UnityAudioParameterDefinition*> (std::calloc (static_cast<size_t> (numParams),
  290. sizeof (UnityAudioParameterDefinition))));
  291. parameterDescriptions.clear();
  292. for (int i = 0; i < numParams; ++i)
  293. {
  294. auto* parameter = juceParameters.params[i];
  295. auto& paramDef = parametersPtr.get()[i];
  296. const auto nameLength = (size_t) numElementsInArray (paramDef.name);
  297. const auto unitLength = (size_t) numElementsInArray (paramDef.unit);
  298. parameter->getName ((int) nameLength - 1).copyToUTF8 (paramDef.name, nameLength);
  299. if (parameter->getLabel().isNotEmpty())
  300. parameter->getLabel().copyToUTF8 (paramDef.unit, unitLength);
  301. parameterDescriptions.add (parameter->getName (15));
  302. paramDef.description = parameterDescriptions[i].toRawUTF8();
  303. paramDef.defaultVal = parameter->getDefaultValue();
  304. paramDef.min = 0.0f;
  305. paramDef.max = 1.0f;
  306. paramDef.displayScale = 1.0f;
  307. paramDef.displayExponent = 1.0f;
  308. }
  309. }
  310. definition.numParameters = static_cast<uint32> (numParams);
  311. definition.parameterDefintions = parametersPtr.get();
  312. }
  313. void setParameter (int index, float value) { juceParameters.getParamForIndex (index)->setValueNotifyingHost (value); }
  314. float getParameter (int index) const noexcept { return juceParameters.getParamForIndex (index)->getValue(); }
  315. String getParameterString (int index) const noexcept
  316. {
  317. auto* param = juceParameters.getParamForIndex (index);
  318. return param->getText (param->getValue(), 16);
  319. }
  320. int getNumInputChannels() const noexcept { return pluginInstance->getTotalNumInputChannels(); }
  321. int getNumOutputChannels() const noexcept { return pluginInstance->getTotalNumOutputChannels(); }
  322. bool hasEditor() const noexcept { return pluginInstance->hasEditor(); }
  323. UnityPeer& getEditorPeer() const
  324. {
  325. auto* peer = dynamic_cast<UnityPeer*> (pluginInstanceEditor->getPeer());
  326. jassert (peer != nullptr);
  327. return *peer;
  328. }
  329. private:
  330. //==============================================================================
  331. void processBuffers (float* inBuffer, float* outBuffer, int bufferSize, int numInChannels, int numOutChannels, bool isBypassed)
  332. {
  333. int ch;
  334. for (ch = 0; ch < numInChannels; ++ch)
  335. {
  336. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst>;
  337. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::Interleaved, AudioData::Const>;
  338. DstSampleType dstData (scratchBuffer.getWritePointer (ch));
  339. SrcSampleType srcData (inBuffer + ch, numInChannels);
  340. dstData.convertSamples (srcData, bufferSize);
  341. }
  342. for (; ch < numOutChannels; ++ch)
  343. scratchBuffer.clear (ch, 0, bufferSize);
  344. {
  345. const ScopedLock sl (pluginInstance->getCallbackLock());
  346. if (pluginInstance->isSuspended())
  347. {
  348. scratchBuffer.clear();
  349. }
  350. else
  351. {
  352. MidiBuffer mb;
  353. if (isBypassed)
  354. pluginInstance->processBlockBypassed (scratchBuffer, mb);
  355. else
  356. pluginInstance->processBlock (scratchBuffer, mb);
  357. }
  358. }
  359. for (ch = 0; ch < numOutChannels; ++ch)
  360. {
  361. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::Interleaved, AudioData::NonConst>;
  362. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const>;
  363. DstSampleType dstData (outBuffer + ch, numOutChannels);
  364. SrcSampleType srcData (scratchBuffer.getReadPointer (ch));
  365. dstData.convertSamples (srcData, bufferSize);
  366. }
  367. }
  368. //==============================================================================
  369. std::unique_ptr<AudioProcessor> pluginInstance;
  370. std::unique_ptr<AudioProcessorEditor> pluginInstanceEditor;
  371. int samplesPerBlock = 1024;
  372. StringArray parameterDescriptions;
  373. AudioBuffer<float> scratchBuffer;
  374. LegacyAudioParametersWrapper juceParameters;
  375. //==============================================================================
  376. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorUnityWrapper)
  377. };
  378. //==============================================================================
  379. HashMap<int, AudioProcessorUnityWrapper*>& getWrapperMap()
  380. {
  381. static HashMap<int, AudioProcessorUnityWrapper*> wrapperMap;
  382. return wrapperMap;
  383. }
  384. static void onWrapperCreation (AudioProcessorUnityWrapper* wrapperToAdd)
  385. {
  386. getWrapperMap().set (std::abs (Random::getSystemRandom().nextInt (65536)), wrapperToAdd);
  387. }
  388. static void onWrapperDeletion (AudioProcessorUnityWrapper* wrapperToRemove)
  389. {
  390. getWrapperMap().removeValue (wrapperToRemove);
  391. }
  392. //==============================================================================
  393. namespace UnityCallbacks
  394. {
  395. int UNITY_INTERFACE_API createCallback (UnityAudioEffectState* state)
  396. {
  397. auto* pluginInstance = new AudioProcessorUnityWrapper (false);
  398. pluginInstance->create (state);
  399. state->effectData = pluginInstance;
  400. onWrapperCreation (pluginInstance);
  401. return 0;
  402. }
  403. int UNITY_INTERFACE_API releaseCallback (UnityAudioEffectState* state)
  404. {
  405. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  406. pluginInstance->release();
  407. onWrapperDeletion (pluginInstance);
  408. delete pluginInstance;
  409. if (getWrapperMap().size() == 0)
  410. shutdownJuce_GUI();
  411. return 0;
  412. }
  413. int UNITY_INTERFACE_API resetCallback (UnityAudioEffectState* state)
  414. {
  415. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  416. pluginInstance->reset();
  417. return 0;
  418. }
  419. int UNITY_INTERFACE_API setPositionCallback (UnityAudioEffectState* state, unsigned int pos)
  420. {
  421. ignoreUnused (state, pos);
  422. return 0;
  423. }
  424. int UNITY_INTERFACE_API setFloatParameterCallback (UnityAudioEffectState* state, int index, float value)
  425. {
  426. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  427. pluginInstance->setParameter (index, value);
  428. return 0;
  429. }
  430. int UNITY_INTERFACE_API getFloatParameterCallback (UnityAudioEffectState* state, int index, float* value, char* valueStr)
  431. {
  432. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  433. *value = pluginInstance->getParameter (index);
  434. pluginInstance->getParameterString (index).copyToUTF8 (valueStr, 15);
  435. return 0;
  436. }
  437. int UNITY_INTERFACE_API getFloatBufferCallback (UnityAudioEffectState* state, const char* name, float* buffer, int numSamples)
  438. {
  439. ignoreUnused (numSamples);
  440. auto nameStr = String (name);
  441. if (nameStr == "Editor")
  442. {
  443. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  444. buffer[0] = pluginInstance->hasEditor() ? 1.0f : 0.0f;
  445. }
  446. else if (nameStr == "ID")
  447. {
  448. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  449. for (HashMap<int, AudioProcessorUnityWrapper*>::Iterator i (getWrapperMap()); i.next();)
  450. {
  451. if (i.getValue() == pluginInstance)
  452. {
  453. buffer[0] = (float) i.getKey();
  454. break;
  455. }
  456. }
  457. return 0;
  458. }
  459. else if (nameStr == "Size")
  460. {
  461. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  462. auto& editor = pluginInstance->getEditorPeer().getEditor();
  463. buffer[0] = (float) editor.getBounds().getWidth();
  464. buffer[1] = (float) editor.getBounds().getHeight();
  465. buffer[2] = (float) editor.getConstrainer()->getMinimumWidth();
  466. buffer[3] = (float) editor.getConstrainer()->getMinimumHeight();
  467. buffer[4] = (float) editor.getConstrainer()->getMaximumWidth();
  468. buffer[5] = (float) editor.getConstrainer()->getMaximumHeight();
  469. }
  470. return 0;
  471. }
  472. int UNITY_INTERFACE_API processCallback (UnityAudioEffectState* state, float* inBuffer, float* outBuffer,
  473. unsigned int bufferSize, int numInChannels, int numOutChannels)
  474. {
  475. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  476. if (pluginInstance != nullptr)
  477. {
  478. auto isPlaying = ((state->flags & stateIsPlaying) != 0);
  479. auto isMuted = ((state->flags & stateIsMuted) != 0);
  480. auto isPaused = ((state->flags & stateIsPaused) != 0);
  481. auto bypassed = ! isPlaying || (isMuted || isPaused);
  482. pluginInstance->process (inBuffer, outBuffer, static_cast<int> (bufferSize), numInChannels, numOutChannels, bypassed);
  483. }
  484. else
  485. {
  486. FloatVectorOperations::clear (outBuffer, static_cast<int> (bufferSize) * numOutChannels);
  487. }
  488. return 0;
  489. }
  490. }
  491. //==============================================================================
  492. static void declareEffect (UnityAudioEffectDefinition& definition)
  493. {
  494. memset (&definition, 0, sizeof (definition));
  495. std::unique_ptr<AudioProcessorUnityWrapper> wrapper = std::make_unique<AudioProcessorUnityWrapper> (true);
  496. String name (JucePlugin_Name);
  497. if (! name.startsWithIgnoreCase ("audioplugin"))
  498. name = "audioplugin_" + name;
  499. name.copyToUTF8 (definition.name, (size_t) numElementsInArray (definition.name));
  500. definition.structSize = sizeof (UnityAudioEffectDefinition);
  501. definition.parameterStructSize = sizeof (UnityAudioParameterDefinition);
  502. definition.apiVersion = UNITY_AUDIO_PLUGIN_API_VERSION;
  503. definition.pluginVersion = JucePlugin_VersionCode;
  504. // effects must set this to 0, generators > 0
  505. definition.channels = (wrapper->getNumInputChannels() != 0 ? 0
  506. : static_cast<uint32> (wrapper->getNumOutputChannels()));
  507. wrapper->declareParameters (definition);
  508. definition.create = UnityCallbacks::createCallback;
  509. definition.release = UnityCallbacks::releaseCallback;
  510. definition.reset = UnityCallbacks::resetCallback;
  511. definition.setPosition = UnityCallbacks::setPositionCallback;
  512. definition.process = UnityCallbacks::processCallback;
  513. definition.setFloatParameter = UnityCallbacks::setFloatParameterCallback;
  514. definition.getFloatParameter = UnityCallbacks::getFloatParameterCallback;
  515. definition.getFloatBuffer = UnityCallbacks::getFloatBufferCallback;
  516. }
  517. } // namespace juce
  518. UNITY_INTERFACE_EXPORT int UNITY_INTERFACE_API UnityGetAudioEffectDefinitions (UnityAudioEffectDefinition*** definitionsPtr)
  519. {
  520. if (juce::getWrapperMap().size() == 0)
  521. juce::initialiseJuce_GUI();
  522. static bool hasInitialised = false;
  523. if (! hasInitialised)
  524. {
  525. juce::PluginHostType::jucePlugInClientCurrentWrapperType = juce::AudioProcessor::wrapperType_Unity;
  526. juce::juce_createUnityPeerFn = juce::createUnityPeer;
  527. hasInitialised = true;
  528. }
  529. auto* definition = new UnityAudioEffectDefinition();
  530. juce::declareEffect (*definition);
  531. *definitionsPtr = &definition;
  532. return 1;
  533. }
  534. //==============================================================================
  535. static juce::ModifierKeys unityModifiersToJUCE (UnityEventModifiers mods, bool mouseDown, int mouseButton = -1)
  536. {
  537. int flags = 0;
  538. if (mouseDown)
  539. {
  540. if (mouseButton == 0)
  541. flags |= juce::ModifierKeys::leftButtonModifier;
  542. else if (mouseButton == 1)
  543. flags |= juce::ModifierKeys::rightButtonModifier;
  544. else if (mouseButton == 2)
  545. flags |= juce::ModifierKeys::middleButtonModifier;
  546. }
  547. if (mods == 0)
  548. return flags;
  549. if ((mods & UnityEventModifiers::shift) != 0) flags |= juce::ModifierKeys::shiftModifier;
  550. if ((mods & UnityEventModifiers::control) != 0) flags |= juce::ModifierKeys::ctrlModifier;
  551. if ((mods & UnityEventModifiers::alt) != 0) flags |= juce::ModifierKeys::altModifier;
  552. if ((mods & UnityEventModifiers::command) != 0) flags |= juce::ModifierKeys::commandModifier;
  553. return { flags };
  554. }
  555. //==============================================================================
  556. static juce::AudioProcessorUnityWrapper* getWrapperChecked (int id)
  557. {
  558. auto* wrapper = juce::getWrapperMap()[id];
  559. jassert (wrapper != nullptr);
  560. return wrapper;
  561. }
  562. //==============================================================================
  563. static void UNITY_INTERFACE_API onRenderEvent (int id)
  564. {
  565. getWrapperChecked (id)->getEditorPeer().triggerAsyncUpdate();
  566. }
  567. UNITY_INTERFACE_EXPORT renderCallback UNITY_INTERFACE_API getRenderCallback()
  568. {
  569. return onRenderEvent;
  570. }
  571. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unityInitialiseTexture (int id, void* data, int w, int h)
  572. {
  573. getWrapperChecked (id)->getEditorPeer().setPixelDataHandle (reinterpret_cast<juce::uint8*> (data), w, h);
  574. }
  575. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unityMouseDown (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 unityMouseDrag (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 unityMouseUp (int id, float x, float y, UnityEventModifiers unityMods)
  584. {
  585. getWrapperChecked (id)->getEditorPeer().forwardMouseEvent ({ x, y }, unityModifiersToJUCE (unityMods, false));
  586. }
  587. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unityKeyEvent (int id, int code, UnityEventModifiers mods, const char* name)
  588. {
  589. getWrapperChecked (id)->getEditorPeer().forwardKeyPress (code, name, unityModifiersToJUCE (mods, false));
  590. }
  591. UNITY_INTERFACE_EXPORT void UNITY_INTERFACE_API unitySetScreenBounds (int id, float x, float y, float w, float h)
  592. {
  593. getWrapperChecked (id)->getEditorPeer().getEditor().setBounds ({ (int) x, (int) y, (int) w, (int) h });
  594. }
  595. //==============================================================================
  596. #if JUCE_WINDOWS
  597. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID)
  598. {
  599. if (reason == DLL_PROCESS_ATTACH)
  600. juce::Process::setCurrentModuleInstanceHandle (instance);
  601. return true;
  602. }
  603. #endif
  604. #endif