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.

780 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. ImageType* createType() const override { return new SoftwareImageType(); }
  114. LowLevelGraphicsContext* createLowLevelContext() override { return new LowLevelGraphicsSoftwareRenderer (Image (this)); }
  115. void initialiseBitmapData (Image::BitmapData& bitmap, int x, int y, Image::BitmapData::ReadWriteMode mode) override
  116. {
  117. ignoreUnused (mode);
  118. bitmap.data = imageData + x * pixelStride + y * lineStride;
  119. bitmap.pixelFormat = pixelFormat;
  120. bitmap.lineStride = lineStride;
  121. bitmap.pixelStride = pixelStride;
  122. }
  123. ImagePixelData::Ptr clone() override
  124. {
  125. auto im = new UnityBitmapImage (imageData, width, height);
  126. for (int i = 0; i < height; ++i)
  127. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, (size_t) lineStride);
  128. return im;
  129. }
  130. uint8* imageData;
  131. int pixelStride = 4, lineStride;
  132. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UnityBitmapImage)
  133. };
  134. //==============================================================================
  135. struct MouseWatcher : public Timer
  136. {
  137. MouseWatcher (ComponentPeer& o) : owner (o) {}
  138. void timerCallback() override
  139. {
  140. auto pos = Desktop::getMousePosition();
  141. if (boundsToWatch.contains (pos) && pos != lastMousePos)
  142. {
  143. auto ms = Desktop::getInstance().getMainMouseSource();
  144. if (! ms.getCurrentModifiers().isLeftButtonDown())
  145. owner.handleMouseEvent (juce::MouseInputSource::mouse, owner.globalToLocal (pos.toFloat()), {},
  146. juce::MouseInputSource::invalidPressure, juce::MouseInputSource::invalidOrientation, juce::Time::currentTimeMillis());
  147. lastMousePos = pos;
  148. }
  149. }
  150. void setBoundsToWatch (Rectangle<int> b)
  151. {
  152. if (boundsToWatch != b)
  153. boundsToWatch = b;
  154. startTimer (250);
  155. }
  156. ComponentPeer& owner;
  157. Rectangle<int> boundsToWatch;
  158. Point<int> lastMousePos;
  159. };
  160. //==============================================================================
  161. KeyPress getKeyPress (int keyCode, String name)
  162. {
  163. if (keyCode >= 32 && keyCode <= 64)
  164. return { keyCode, ModifierKeys::currentModifiers, juce::juce_wchar (keyCode) };
  165. if (keyCode >= 91 && keyCode <= 122)
  166. return { keyCode, ModifierKeys::currentModifiers, name[0] };
  167. if (keyCode >= 256 && keyCode <= 265)
  168. return { juce::KeyPress::numberPad0 + (keyCode - 256), ModifierKeys::currentModifiers, juce::String (keyCode - 256).getCharPointer()[0] };
  169. if (keyCode == 8) return { juce::KeyPress::backspaceKey, ModifierKeys::currentModifiers, {} };
  170. if (keyCode == 127) return { juce::KeyPress::deleteKey, ModifierKeys::currentModifiers, {} };
  171. if (keyCode == 9) return { juce::KeyPress::tabKey, ModifierKeys::currentModifiers, {} };
  172. if (keyCode == 13) return { juce::KeyPress::returnKey, ModifierKeys::currentModifiers, {} };
  173. if (keyCode == 27) return { juce::KeyPress::escapeKey, ModifierKeys::currentModifiers, {} };
  174. if (keyCode == 32) return { juce::KeyPress::spaceKey, ModifierKeys::currentModifiers, {} };
  175. if (keyCode == 266) return { juce::KeyPress::numberPadDecimalPoint, ModifierKeys::currentModifiers, {} };
  176. if (keyCode == 267) return { juce::KeyPress::numberPadDivide, ModifierKeys::currentModifiers, {} };
  177. if (keyCode == 268) return { juce::KeyPress::numberPadMultiply, ModifierKeys::currentModifiers, {} };
  178. if (keyCode == 269) return { juce::KeyPress::numberPadSubtract, ModifierKeys::currentModifiers, {} };
  179. if (keyCode == 270) return { juce::KeyPress::numberPadAdd, ModifierKeys::currentModifiers, {} };
  180. if (keyCode == 272) return { juce::KeyPress::numberPadEquals, ModifierKeys::currentModifiers, {} };
  181. if (keyCode == 273) return { juce::KeyPress::upKey, ModifierKeys::currentModifiers, {} };
  182. if (keyCode == 274) return { juce::KeyPress::downKey, ModifierKeys::currentModifiers, {} };
  183. if (keyCode == 275) return { juce::KeyPress::rightKey, ModifierKeys::currentModifiers, {} };
  184. if (keyCode == 276) return { juce::KeyPress::leftKey, ModifierKeys::currentModifiers, {} };
  185. return {};
  186. }
  187. //==============================================================================
  188. Rectangle<int> bounds;
  189. MouseWatcher mouseWatcher;
  190. uint8* pixelData = nullptr;
  191. int textureWidth, textureHeight;
  192. Image renderImage;
  193. //==============================================================================
  194. void setMinimised (bool) override {}
  195. bool isMinimised() const override { return false; }
  196. void setFullScreen (bool) override {}
  197. bool isFullScreen() const override { return false; }
  198. bool setAlwaysOnTop (bool) override { return false; }
  199. void toFront (bool) override {}
  200. void toBehind (ComponentPeer*) override {}
  201. bool isFocused() const override { return true; }
  202. void grabFocus() override {}
  203. void* getNativeHandle() const override { return nullptr; }
  204. BorderSize<int> getFrameSize() const override { return {}; }
  205. void setVisible (bool) override {}
  206. void setTitle (const String&) override {}
  207. void setIcon (const Image&) override {}
  208. void textInputRequired (Point<int>, TextInputTarget&) override {}
  209. void setAlpha (float) override {}
  210. void performAnyPendingRepaintsNow() override {}
  211. void repaint (const Rectangle<int>&) override {}
  212. //==============================================================================
  213. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UnityPeer)
  214. };
  215. ComponentPeer* createUnityPeer (Component& c) { return new UnityPeer (c); }
  216. //==============================================================================
  217. class AudioProcessorUnityWrapper
  218. {
  219. public:
  220. AudioProcessorUnityWrapper (bool isTemporary)
  221. {
  222. pluginInstance.reset (createPluginFilterOfType (AudioProcessor::wrapperType_Unity));
  223. if (! isTemporary && pluginInstance->hasEditor())
  224. {
  225. pluginInstanceEditor.reset (pluginInstance->createEditorIfNeeded());
  226. pluginInstanceEditor->setVisible (true);
  227. pluginInstanceEditor->addToDesktop (0);
  228. }
  229. juceParameters.update (*pluginInstance, false);
  230. }
  231. ~AudioProcessorUnityWrapper()
  232. {
  233. if (pluginInstanceEditor != nullptr)
  234. {
  235. pluginInstanceEditor->removeFromDesktop();
  236. PopupMenu::dismissAllActiveMenus();
  237. pluginInstanceEditor->processor.editorBeingDeleted (pluginInstanceEditor.get());
  238. pluginInstanceEditor = nullptr;
  239. }
  240. }
  241. void create (UnityAudioEffectState* state)
  242. {
  243. // only supported in Unity plugin API > 1.0
  244. if (state->structSize >= sizeof (UnityAudioEffectState))
  245. samplesPerBlock = static_cast<int> (state->dspBufferSize);
  246. pluginInstance->setRateAndBufferSizeDetails (state->sampleRate, samplesPerBlock);
  247. pluginInstance->prepareToPlay (state->sampleRate, samplesPerBlock);
  248. scratchBuffer.setSize (jmax (pluginInstance->getTotalNumInputChannels(), pluginInstance->getTotalNumOutputChannels()), samplesPerBlock);
  249. }
  250. void release()
  251. {
  252. pluginInstance->releaseResources();
  253. }
  254. void reset()
  255. {
  256. pluginInstance->reset();
  257. }
  258. void process (float* inBuffer, float* outBuffer, int bufferSize, int numInChannels, int numOutChannels, bool isBypassed)
  259. {
  260. for (int pos = 0; pos < bufferSize;)
  261. {
  262. auto max = jmin (bufferSize - pos, samplesPerBlock);
  263. processBuffers (inBuffer + (pos * numInChannels), outBuffer + (pos * numOutChannels), max, numInChannels, numOutChannels, isBypassed);
  264. pos += max;
  265. }
  266. }
  267. void declareParameters (UnityAudioEffectDefinition& definition)
  268. {
  269. static std::unique_ptr<UnityAudioParameterDefinition> parametersPtr;
  270. static int numParams = 0;
  271. if (parametersPtr == nullptr)
  272. {
  273. auto paramsCopy = juceParameters.params;
  274. for (auto* parameter : paramsCopy)
  275. {
  276. // Unity only displays parameters using a slider so remove any choice parameters
  277. if (! parameter->getAllValueStrings().isEmpty())
  278. paramsCopy.remove (paramsCopy.indexOf (parameter));
  279. }
  280. numParams = paramsCopy.size();
  281. parametersPtr.reset (static_cast<UnityAudioParameterDefinition*> (std::calloc (static_cast<size_t> (numParams),
  282. sizeof (UnityAudioParameterDefinition))));
  283. parameterDescriptions.clear();
  284. for (int i = 0; i < numParams; ++i)
  285. {
  286. auto* parameter = paramsCopy[i];
  287. auto& paramDef = parametersPtr.get()[i];
  288. strncpy (paramDef.name, parameter->getName (15).toRawUTF8(), 15);
  289. if (parameter->getLabel().isNotEmpty())
  290. strncpy (paramDef.unit, parameter->getLabel().toRawUTF8(), 15);
  291. parameterDescriptions.add (parameter->getName (15));
  292. paramDef.description = parameterDescriptions[i].toRawUTF8();
  293. paramDef.defaultVal = parameter->getDefaultValue();
  294. paramDef.min = 0.0f;
  295. paramDef.max = 1.0f;
  296. float scale = 1.0f;
  297. float exp = 1.0f;
  298. if (auto* floatParam = dynamic_cast<AudioParameterFloat*> (parameter))
  299. {
  300. scale = floatParam->range.end;
  301. exp = floatParam->range.skew;
  302. }
  303. else if (auto* intParam = dynamic_cast<AudioParameterInt*> (parameter))
  304. {
  305. scale = (float) intParam->getRange().getEnd();
  306. }
  307. paramDef.displayScale = scale;
  308. paramDef.displayExponent = exp;
  309. }
  310. }
  311. definition.numParameters = static_cast<uint32> (numParams);
  312. definition.parameterDefintions = parametersPtr.get();
  313. }
  314. void setParameter (int index, float value) { juceParameters.getParamForIndex (index)->setValue (value); }
  315. float getParameter (int index) const noexcept { return juceParameters.getParamForIndex (index)->getValue(); }
  316. String getParameterString (int index) const noexcept
  317. {
  318. auto* param = juceParameters.getParamForIndex (index);
  319. return param->getText (param->getValue(), 16);
  320. }
  321. int getNumInputChannels() const noexcept { return pluginInstance->getTotalNumInputChannels(); }
  322. int getNumOutputChannels() const noexcept { return pluginInstance->getTotalNumOutputChannels(); }
  323. bool hasEditor() const noexcept { return pluginInstance->hasEditor(); }
  324. UnityPeer& getEditorPeer() const
  325. {
  326. auto* peer = dynamic_cast<UnityPeer*> (pluginInstanceEditor->getPeer());
  327. jassert (peer != nullptr);
  328. return *peer;
  329. }
  330. private:
  331. //==============================================================================
  332. void processBuffers (float* inBuffer, float* outBuffer, int bufferSize, int numInChannels, int numOutChannels, bool isBypassed)
  333. {
  334. int ch;
  335. for (ch = 0; ch < numInChannels; ++ch)
  336. {
  337. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst>;
  338. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::Interleaved, AudioData::Const>;
  339. DstSampleType dstData (scratchBuffer.getWritePointer (ch));
  340. SrcSampleType srcData (inBuffer + ch, numInChannels);
  341. dstData.convertSamples (srcData, bufferSize);
  342. }
  343. for (; ch < numOutChannels; ++ch)
  344. scratchBuffer.clear (ch, 0, bufferSize);
  345. {
  346. const ScopedLock sl (pluginInstance->getCallbackLock());
  347. if (pluginInstance->isSuspended())
  348. {
  349. scratchBuffer.clear();
  350. }
  351. else
  352. {
  353. MidiBuffer mb;
  354. if (isBypassed)
  355. pluginInstance->processBlockBypassed (scratchBuffer, mb);
  356. else
  357. pluginInstance->processBlock (scratchBuffer, mb);
  358. }
  359. }
  360. for (ch = 0; ch < numOutChannels; ++ch)
  361. {
  362. using DstSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::Interleaved, AudioData::NonConst>;
  363. using SrcSampleType = AudioData::Pointer<AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const>;
  364. DstSampleType dstData (outBuffer + ch, numOutChannels);
  365. SrcSampleType srcData (scratchBuffer.getReadPointer (ch));
  366. dstData.convertSamples (srcData, bufferSize);
  367. }
  368. }
  369. //==============================================================================
  370. std::unique_ptr<AudioProcessor> pluginInstance;
  371. std::unique_ptr<AudioProcessorEditor> pluginInstanceEditor;
  372. int samplesPerBlock = 1024;
  373. StringArray parameterDescriptions;
  374. AudioBuffer<float> scratchBuffer;
  375. LegacyAudioParametersWrapper juceParameters;
  376. //==============================================================================
  377. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorUnityWrapper)
  378. };
  379. //==============================================================================
  380. HashMap<int, AudioProcessorUnityWrapper*>& getWrapperMap()
  381. {
  382. static HashMap<int, AudioProcessorUnityWrapper*> wrapperMap;
  383. return wrapperMap;
  384. }
  385. static void onWrapperCreation (AudioProcessorUnityWrapper* wrapperToAdd)
  386. {
  387. getWrapperMap().set (std::abs (Random::getSystemRandom().nextInt (65536)), wrapperToAdd);
  388. }
  389. static void onWrapperDeletion (AudioProcessorUnityWrapper* wrapperToRemove)
  390. {
  391. getWrapperMap().removeValue (wrapperToRemove);
  392. }
  393. //==============================================================================
  394. namespace UnityCallbacks
  395. {
  396. int UNITY_INTERFACE_API createCallback (UnityAudioEffectState* state)
  397. {
  398. if (getWrapperMap().size() == 0)
  399. initialiseJuce_GUI();
  400. auto* pluginInstance = new AudioProcessorUnityWrapper (false);
  401. pluginInstance->create (state);
  402. state->effectData = pluginInstance;
  403. onWrapperCreation (pluginInstance);
  404. return 0;
  405. }
  406. int UNITY_INTERFACE_API releaseCallback (UnityAudioEffectState* state)
  407. {
  408. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  409. pluginInstance->release();
  410. onWrapperDeletion (pluginInstance);
  411. delete pluginInstance;
  412. if (getWrapperMap().size() == 0)
  413. shutdownJuce_GUI();
  414. return 0;
  415. }
  416. int UNITY_INTERFACE_API resetCallback (UnityAudioEffectState* state)
  417. {
  418. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  419. pluginInstance->reset();
  420. return 0;
  421. }
  422. int UNITY_INTERFACE_API setPositionCallback (UnityAudioEffectState* state, unsigned int pos)
  423. {
  424. ignoreUnused (state, pos);
  425. return 0;
  426. }
  427. int UNITY_INTERFACE_API setFloatParameterCallback (UnityAudioEffectState* state, int index, float value)
  428. {
  429. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  430. pluginInstance->setParameter (index, value);
  431. return 0;
  432. }
  433. int UNITY_INTERFACE_API getFloatParameterCallback (UnityAudioEffectState* state, int index, float* value, char* valueStr)
  434. {
  435. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  436. *value = pluginInstance->getParameter (index);
  437. strncpy (valueStr, pluginInstance->getParameterString (index).toRawUTF8(), 15);
  438. return 0;
  439. }
  440. int UNITY_INTERFACE_API getFloatBufferCallback (UnityAudioEffectState* state, const char* name, float* buffer, int numSamples)
  441. {
  442. ignoreUnused (numSamples);
  443. auto nameStr = String (name);
  444. if (nameStr == "Editor")
  445. {
  446. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  447. buffer[0] = pluginInstance->hasEditor() ? 1.0f : 0.0f;
  448. }
  449. else if (nameStr == "ID")
  450. {
  451. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  452. for (HashMap<int, AudioProcessorUnityWrapper*>::Iterator i (getWrapperMap()); i.next();)
  453. {
  454. if (i.getValue() == pluginInstance)
  455. {
  456. buffer[0] = (float) i.getKey();
  457. break;
  458. }
  459. }
  460. return 0;
  461. }
  462. else if (nameStr == "Size")
  463. {
  464. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  465. auto& editor = pluginInstance->getEditorPeer().getEditor();
  466. buffer[0] = (float) editor.getBounds().getWidth();
  467. buffer[1] = (float) editor.getBounds().getHeight();
  468. buffer[2] = (float) editor.getConstrainer()->getMinimumWidth();
  469. buffer[3] = (float) editor.getConstrainer()->getMinimumHeight();
  470. buffer[4] = (float) editor.getConstrainer()->getMaximumWidth();
  471. buffer[5] = (float) editor.getConstrainer()->getMaximumHeight();
  472. }
  473. return 0;
  474. }
  475. int UNITY_INTERFACE_API processCallback (UnityAudioEffectState* state, float* inBuffer, float* outBuffer,
  476. unsigned int bufferSize, int numInChannels, int numOutChannels)
  477. {
  478. auto* pluginInstance = state->getEffectData<AudioProcessorUnityWrapper>();
  479. if (pluginInstance != nullptr)
  480. {
  481. auto isPlaying = ((state->flags & stateIsPlaying) != 0);
  482. auto isMuted = ((state->flags & stateIsMuted) != 0);
  483. auto isPaused = ((state->flags & stateIsPaused) != 0);
  484. auto bypassed = ! isPlaying || (isMuted || isPaused);
  485. pluginInstance->process (inBuffer, outBuffer, static_cast<int> (bufferSize), numInChannels, numOutChannels, bypassed);
  486. }
  487. else
  488. {
  489. FloatVectorOperations::clear (outBuffer, static_cast<int> (bufferSize) * numOutChannels);
  490. }
  491. return 0;
  492. }
  493. }
  494. //==============================================================================
  495. static void declareEffect (UnityAudioEffectDefinition& definition)
  496. {
  497. memset (&definition, 0, sizeof (definition));
  498. std::unique_ptr<AudioProcessorUnityWrapper> wrapper = std::make_unique<AudioProcessorUnityWrapper> (true);
  499. String name (JucePlugin_Name);
  500. if (! name.startsWithIgnoreCase ("audioplugin"))
  501. name = "audioplugin_" + name;
  502. strcpy (definition.name, name.toRawUTF8());
  503. definition.structSize = sizeof (UnityAudioEffectDefinition);
  504. definition.parameterStructSize = sizeof (UnityAudioParameterDefinition);
  505. definition.apiVersion = UNITY_AUDIO_PLUGIN_API_VERSION;
  506. definition.pluginVersion = JucePlugin_VersionCode;
  507. // effects must set this to 0, generators > 0
  508. definition.channels = (wrapper->getNumInputChannels() != 0 ? 0 : static_cast<uint32> (wrapper->getNumOutputChannels()));
  509. wrapper->declareParameters (definition);
  510. definition.create = UnityCallbacks::createCallback;
  511. definition.release = UnityCallbacks::releaseCallback;
  512. definition.reset = UnityCallbacks::resetCallback;
  513. definition.setPosition = UnityCallbacks::setPositionCallback;
  514. definition.process = UnityCallbacks::processCallback;
  515. definition.setFloatParameter = UnityCallbacks::setFloatParameterCallback;
  516. definition.getFloatParameter = UnityCallbacks::getFloatParameterCallback;
  517. definition.getFloatBuffer = UnityCallbacks::getFloatBufferCallback;
  518. }
  519. } // namespace juce
  520. UNITY_INTERFACE_EXPORT int UnityGetAudioEffectDefinitions (UnityAudioEffectDefinition*** definitionsPtr)
  521. {
  522. static bool hasSetWrapperType = false;
  523. if (! hasSetWrapperType)
  524. {
  525. juce::PluginHostType::jucePlugInClientCurrentWrapperType = juce::AudioProcessor::wrapperType_Unity;
  526. juce::juce_createUnityPeerFn = juce::createUnityPeer;
  527. hasSetWrapperType = 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 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