text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // DCRemoverEffect.h // Bespoke // // Created by Ryan Challinor on 12/2/14. // // #pragma once #include <stdio.h> #include <iostream> #include "IAudioEffect.h" #include "BiquadFilter.h" class DCRemoverEffect : public IAudioEffect { public: DCRemoverEffect(); ~DCRemoverEffect(); static IAudioEffect* Create() { return new DCRemoverEffect(); } //IAudioEffect void ProcessAudio(double time, ChannelBuffer* buffer) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } float GetEffectAmount() override; std::string GetType() override { return "dcremover"; } void CheckboxUpdated(Checkbox* checkbox, double time) override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void GetModuleDimensions(float& width, float& height) override; void DrawModule() override; BiquadFilter mBiquad[ChannelBuffer::kMaxNumChannels]{}; }; ```
/content/code_sandbox/Source/DCRemoverEffect.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
336
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // MidiReader.h // Bespoke // // Created by Ryan Challinor on 3/29/14. // // #pragma once //TODO_PORT(Ryan) make this work class MidiReader { public: MidiReader(); virtual ~MidiReader(); void Read(const char* midiFileName); float GetTempo(double ms); int GetBeat(double ms); void GetMeasurePos(double ms, int& measure, float& measurePos); void SetBeatOffset(int beatOffset) { mBeatOffset = beatOffset; } //MIDISequencer* GetSequencer() { return mSequencer; } private: //MIDIMultiTrack mTracks; //MIDISequencer* mSequencer; int mBeatOffset{ 0 }; }; ```
/content/code_sandbox/Source/MidiReader.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
271
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== AudioSend.h Created: 22 Oct 2017 1:23:39pm Author: Ryan Challinor ============================================================================== */ #pragma once #include <iostream> #include "IAudioProcessor.h" #include "IDrawableModule.h" #include "RollingBuffer.h" #include "PatchCableSource.h" #include "Slider.h" class AudioSend : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener { public: AudioSend(); virtual ~AudioSend(); static IDrawableModule* Create() { return new AudioSend(); } static bool AcceptsAudio() { return true; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void SetSend(float amount, bool crossfade) { mAmount = amount; mCrossfade = crossfade; } //IAudioSource void Process(double time) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } int GetNumTargets() override { return 2; } void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override { w = 86; h = 38; } bool mCrossfade{ false }; Checkbox* mCrossfadeCheckbox{ nullptr }; float mAmount{ 0 }; FloatSlider* mAmountSlider{ nullptr }; RollingBuffer mVizBuffer2; PatchCableSource* mPatchCableSource2{ nullptr }; }; ```
/content/code_sandbox/Source/AudioSend.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
508
```c++ #include "juce_audio_devices/juce_audio_devices.h" #include "juce_audio_formats/juce_audio_formats.h" #include "juce_opengl/juce_opengl.h" using namespace juce::gl; using namespace juce; #include "VersionInfo.h" #include "nanovg/nanovg.h" #define NANOVG_GLES2_IMPLEMENTATION #include "nanovg/nanovg_gl.h" #include "ModularSynth.h" #include "SynthGlobals.h" #include "Push2Control.h" //TODO(Ryan) remove #include "SpaceMouseControl.h" #include "UserPrefs.h" #ifdef JUCE_WINDOWS #include <windows.h> #endif //============================================================================== /* This component lives inside our window, and this is where you should put all your controls and content. */ class MainContentComponent : public OpenGLAppComponent, public AudioIODeviceCallback, public FileDragAndDropTarget, private Timer { public: //============================================================================== MainContentComponent() : mSpaceMouseReader(mSynth) , mLastFpsUpdateTime(0) , mFrameCountAccum(0) , mPixelRatio(1) , mFontBoundsVG(nullptr) , mVG(nullptr) { ofLog() << "bespoke synth " << GetBuildInfoString(); // sigh ofLog isn't a stream so std::hex doesn't work so char jv[256]; snprintf(jv, 255, "%x", JUCE_VERSION); ofLog() << " juce version : " << jv; ofLog() << " python version : " << Bespoke::PYTHON_VERSION; #if BESPOKE_LINUX ofLog() << " install prefix : '" << Bespoke::CMAKE_INSTALL_PREFIX << "'"; #endif ofLog() << " git hash : " << Bespoke::GIT_HASH; ofLog() << " git branch : " << Bespoke::GIT_BRANCH; ofLog() << " build time : " << Bespoke::BUILD_DATE << " at " << Bespoke::BUILD_TIME; ofLog() << " command line : " << JUCEApplication::getCommandLineParameters(); openGLContext.setOpenGLVersionRequired(juce::OpenGLContext::openGL3_2); openGLContext.setContinuousRepainting(false); #if BESPOKE_LINUX //turning this on improves linux framerate, but seems to expose thread safety issues on windows/mac. see git PRs #349 and #396 openGLContext.setComponentPaintingEnabled(false); #endif #ifndef BESPOKE_WINDOWS //windows crash handler is set up in ModularSynth() constructor SystemStats::setApplicationCrashHandler(ModularSynth::CrashHandler); #endif UserPrefs.Init(); int screenWidth, screenHeight; { const MessageManagerLock lock; if (const auto* dpy = Desktop::getInstance().getDisplays().getPrimaryDisplay()) { mPixelRatio = dpy->scale; TheSynth->SetPixelRatio(mPixelRatio); } auto bounds = Desktop::getInstance().getDisplays().getTotalBounds(true); screenWidth = bounds.getWidth(); screenHeight = bounds.getHeight(); ofLog() << "pixel ratio: " << mPixelRatio << " screen width: " << screenWidth << " screen height: " << screenHeight; } int width = UserPrefs.width.Get(); int height = UserPrefs.height.Get(); mDesiredInitialPosition.setXY(INT_MAX, INT_MAX); if (UserPrefs.set_manual_window_position.Get()) { mDesiredInitialPosition.setXY(UserPrefs.position_x.Get(), UserPrefs.position_y.Get()); } else { if (width + getTopLevelComponent()->getPosition().x > screenWidth) width = screenWidth - getTopLevelComponent()->getPosition().x; if (height + getTopLevelComponent()->getPosition().y + 20 > screenHeight) height = screenHeight - getTopLevelComponent()->getPosition().y - 20; } setSize(width, height); setWantsKeyboardFocus(true); Desktop::setScreenSaverEnabled(false); mGlobalManagers.mDeviceManager.getAvailableDeviceTypes(); //scans for device types ("Windows Audio", "DirectSound", etc) } ~MainContentComponent() { shutdownOpenGL(); shutdownAudio(); } void timerCallback() override { static int sRenderFrame = 0; if (sRenderFrame == 0 && mDesiredInitialPosition.x != INT_MAX) getTopLevelComponent()->setTopLeftPosition(mDesiredInitialPosition); static bool sHasGrabbedFocus = false; if (!sHasGrabbedFocus && !hasKeyboardFocus(true) && isVisible()) { grabKeyboardFocus(); sHasGrabbedFocus = true; } mSynth.Poll(); #if DEBUG if (sRenderFrame % 2 == 0) #else if (true) #endif { openGLContext.triggerRepaint(); } ++sRenderFrame; if (sRenderFrame % 30 == 0) { if (const auto* dpy = Desktop::getInstance().getDisplays().getDisplayForRect(getScreenBounds())) { mPixelRatio = dpy->scale; //adjust pixel ratio based on which screen has the majority of the window TheSynth->SetPixelRatio(mPixelRatio); } } mScreenPosition = getScreenPosition(); mSpaceMouseReader.Poll(); } //============================================================================== void audioDeviceAboutToStart(AudioIODevice* device) override { // This function will be called when the audio device is started, or when // its settings (i.e. sample rate, block size, etc) are changed. // You can use this function to initialise any resources you might need, // but be careful - it will be called on the audio thread, not the GUI thread. } void audioDeviceIOCallbackWithContext(const float* const* inputChannelData, int numInputChannels, float* const* outputChannelData, int numOutputChannels, int numSamples, const AudioIODeviceCallbackContext& context) override { ignoreUnused(context); mSynth.AudioIn(inputChannelData, numSamples, numInputChannels); mSynth.AudioOut(outputChannelData, numSamples, numOutputChannels); } void audioDeviceStopped() override { } void shutdownAudio() { mGlobalManagers.mDeviceManager.removeAudioCallback(this); mGlobalManagers.mDeviceManager.closeAudioDevice(); } void initialise() override { #ifdef JUCE_WINDOWS // glewInit(); #endif mVG = nvgCreateGLES2(NVG_ANTIALIAS | NVG_STENCIL_STROKES); mFontBoundsVG = nvgCreateGLES2(NVG_ANTIALIAS | NVG_STENCIL_STROKES); if (mVG == nullptr) printf("Could not init nanovg.\n"); if (mFontBoundsVG == nullptr) printf("Could not init font bounds nanovg.\n"); Push2Control::CreateStaticFramebuffer(); mSynth.LoadResources(mVG, mFontBoundsVG); /*for (auto deviceType : mGlobalManagers.mDeviceManager.getAvailableDeviceTypes()) { ofLog() << "inputs:"; for (auto input : deviceType->getDeviceNames(true)) ofLog() << input.toStdString(); ofLog() << "outputs:"; for (auto output : deviceType->getDeviceNames(false)) ofLog() << output.toStdString(); }*/ const std::string kAutoDevice = "auto"; const std::string kNoneDevice = "none"; if (UserPrefs.devicetype.Get() != kAutoDevice) mGlobalManagers.mDeviceManager.setCurrentAudioDeviceType(UserPrefs.devicetype.Get(), true); SetGlobalSampleRateAndBufferSize(UserPrefs.samplerate.Get(), UserPrefs.buffersize.Get()); mSynth.Setup(&mGlobalManagers.mDeviceManager, &mGlobalManagers.mAudioFormatManager, this, &openGLContext); std::string outputDevice = UserPrefs.audio_output_device.Get(); std::string inputDevice = UserPrefs.audio_input_device.Get(); if (!mGlobalManagers.mDeviceManager.getCurrentDeviceTypeObject()->hasSeparateInputsAndOutputs()) inputDevice = outputDevice; //asio must have identical input and output AudioDeviceManager::AudioDeviceSetup preferredSetupOptions; preferredSetupOptions.sampleRate = gSampleRate / UserPrefs.oversampling.Get(); preferredSetupOptions.bufferSize = gBufferSize / UserPrefs.oversampling.Get(); if (outputDevice != kAutoDevice && outputDevice != kNoneDevice) preferredSetupOptions.outputDeviceName = outputDevice; if (inputDevice != kAutoDevice && inputDevice != kNoneDevice) preferredSetupOptions.inputDeviceName = inputDevice; #ifdef JUCE_WINDOWS CoInitializeEx(0, COINIT_MULTITHREADED); #endif int inputChannels = UserPrefs.max_input_channels.Get(); int outputChannels = UserPrefs.max_output_channels.Get(); if (inputDevice == kNoneDevice) inputChannels = 0; if (outputDevice == kNoneDevice) outputChannels = 0; String audioError = mGlobalManagers.mDeviceManager.initialise(inputChannels, outputChannels, nullptr, true, "", &preferredSetupOptions); if (audioError.isEmpty()) { auto loadedSetup = mGlobalManagers.mDeviceManager.getAudioDeviceSetup(); if (outputDevice != kAutoDevice && outputDevice != kNoneDevice && loadedSetup.outputDeviceName.toStdString() != outputDevice) { mSynth.SetFatalError("error setting output device to '" + outputDevice + "', fix this in userprefs.json (use \"auto\" for default device)" + "\n\n\nvalid devices:\n" + GetAudioDevices()); } else if (inputDevice != kAutoDevice && inputDevice != kNoneDevice && loadedSetup.inputDeviceName.toStdString() != inputDevice) { mSynth.SetFatalError("error setting input device to '" + inputDevice + "', fix this in userprefs.json (use \"auto\" for default device, or \"none\" for no device)" + "\n\n\nvalid devices:\n" + GetAudioDevices()); } else if (loadedSetup.bufferSize != gBufferSize / UserPrefs.oversampling.Get()) { mSynth.SetFatalError("error setting buffer size to " + ofToString(gBufferSize / UserPrefs.oversampling.Get()) + " on device '" + loadedSetup.outputDeviceName.toStdString() + "', fix this in userprefs.json" + "\n\n(a valid buffer size might be: " + ofToString(loadedSetup.bufferSize) + ")"); } else if (loadedSetup.sampleRate != gSampleRate / UserPrefs.oversampling.Get()) { mSynth.SetFatalError("error setting sample rate to " + ofToString(gSampleRate / UserPrefs.oversampling.Get()) + " on device '" + loadedSetup.outputDeviceName.toStdString() + "', fix this in userprefs.json" + "\n\n(a valid sample rate might be: " + ofToString(loadedSetup.sampleRate) + ")"); } else { ofLog() << "output: " << loadedSetup.outputDeviceName << " input: " << loadedSetup.inputDeviceName; int numInputChannels = 0; int64 inputMask = loadedSetup.inputChannels.toInteger(); while (inputMask != 0) { ++numInputChannels; inputMask >>= 1; } int numOutputChannels = 0; int64 outputMask = loadedSetup.outputChannels.toInteger(); while (outputMask != 0) { ++numOutputChannels; outputMask >>= 1; } mSynth.InitIOBuffers(numInputChannels, numOutputChannels); mGlobalManagers.mDeviceManager.addAudioCallback(this); } } else { if (audioError.startsWith("No such device")) audioError += "\n\nfix this in userprefs.json (you can use \"auto\" for the default device)"; else audioError += juce::String("\n\nattempted to set output to: " + outputDevice + " and input to: " + inputDevice + "\n\ninitialization errors could potentially be fixed by changing buffer size, sample rate, or input/output devices in userprefs.json\nto use no input device, specify \"none\" for \"audio_input_device\""); mSynth.SetFatalError("error initializing audio device: " + audioError.toStdString() + "\n\n\nvalid devices:\n" + GetAudioDevices()); } for (int i = 0; i < JUCEApplication::getCommandLineParameterArray().size(); ++i) { juce::String argument = JUCEApplication::getCommandLineParameterArray()[i]; if (argument.endsWith(".bsk") || argument.endsWith(".bskt")) { mSynth.SetStartupSaveStateFile(argument.toStdString()); break; } } UserPrefs.LastTargetFramerate = UserPrefs.target_framerate.Get(); startTimerHz(UserPrefs.target_framerate.Get()); } void shutdown() override { nvgDeleteGLES2(mVG); nvgDeleteGLES2(mFontBoundsVG); } void SetStartupSaveStateFile(const juce::String& bskPath) { mSynth.SetStartupSaveStateFile(bskPath.toStdString()); } void render() override { if (mSynth.IsLoadingState()) return; mSynth.LockRender(true); if (UserPrefs.LastTargetFramerate != UserPrefs.target_framerate.Get()) { stopTimer(); UserPrefs.LastTargetFramerate = UserPrefs.target_framerate.Get(); startTimerHz(UserPrefs.target_framerate.Get()); } juce::Point<int> mouse = Desktop::getMousePosition(); mouse -= mScreenPosition; mSynth.MouseMoved(mouse.x, mouse.y); float width = getWidth(); float height = getHeight(); static float kMotionTrails = .4f; ofVec3f bgColor(ModularSynth::sBackgroundR, ModularSynth::sBackgroundG, ModularSynth::sBackgroundB); glViewport(0, 0, width * mPixelRatio, height * mPixelRatio); glClearColor(bgColor.x, bgColor.y, bgColor.z, 0); if (UserPrefs.motion_trails.Get() <= 0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); nvgBeginFrame(mVG, width, height, mPixelRatio); if (UserPrefs.motion_trails.Get() > 0) { ofSetColor(bgColor.x * 255, bgColor.y * 255, bgColor.z * 255, (1 - (UserPrefs.motion_trails.Get() * kMotionTrails) * (ofGetFrameRate() / 60.0f)) * 255); ofFill(); ofRect(0, 0, width, height); } nvgLineCap(mVG, NVG_ROUND); nvgLineJoin(mVG, NVG_ROUND); static float sSpacing = -.3f; nvgTextLetterSpacing(mVG, sSpacing); nvgTextLetterSpacing(mFontBoundsVG, sSpacing); mSynth.Draw(mVG); nvgEndFrame(mVG); mSynth.PostRender(); mSynth.LockRender(false); ++mFrameCountAccum; int64 time = Time::currentTimeMillis(); const int64 kCalcFpsIntervalMs = 1000; if (time - mLastFpsUpdateTime >= kCalcFpsIntervalMs) { mSynth.UpdateFrameRate(mFrameCountAccum / (kCalcFpsIntervalMs / 1000.0f)); mFrameCountAccum = 0; mLastFpsUpdateTime = time; } } //============================================================================== void paint(Graphics& g) override { } void resized() override { // This is called when the MainContentComponent is resized. // If you add any child components, this is where you should // update their positions. } private: int GetMouseButton(const MouseEvent& e) { if (e.mods.isPopupMenu()) return 2; if (e.mods.isMiddleButtonDown()) return 3; return 1; } void mouseDown(const MouseEvent& e) override { mSynth.MousePressed(e.getMouseDownX(), e.getMouseDownY(), GetMouseButton(e), e.source); } void mouseUp(const MouseEvent& e) override { mSynth.MouseReleased(e.getPosition().x, e.getPosition().y, GetMouseButton(e), e.source); } void mouseDrag(const MouseEvent& e) override { mSynth.MouseDragged(e.getPosition().x, e.getPosition().y, GetMouseButton(e), e.source); } void mouseMove(const MouseEvent& e) override { //Don't do mouse move in here, it really slows UI responsiveness in some scenarios. We do it when we render instead. //mSynth.MouseMoved(e.getPosition().x, e.getPosition().y); } void mouseWheelMove(const MouseEvent& e, const MouseWheelDetails& wheel) override { float invert = 1; if (wheel.isReversed) invert = -1; float scale = 6; if (wheel.isSmooth) scale = 30; if (!wheel.isInertial) mSynth.MouseScrolled(wheel.deltaX * scale, wheel.deltaY * scale * invert, wheel.isSmooth, wheel.isReversed, true); } void mouseMagnify(const MouseEvent& e, float scaleFactor) override { mSynth.MouseMagnify(e.getPosition().x, e.getPosition().y, scaleFactor, e.source); } bool keyPressed(const KeyPress& key) override { /* * This is a temporary fix for 1.0.1. This keyPressed handler * always returns true whether or not Bespoke handles the event * and with juce 6.1.1 it gets all the events. That 'return true' * therefore suppresses the cmd-q/alt-f4 to quit. * * The correct fix is take every key handler and make it have * a return type bool and then at the end return true if any * subordinate key handler returns true, and false if not, * but that touches the entire codebase, so to fix the 1.0 to * 1.0.1. regression with command q on macos, just for now do this * and if it gets merged, open an issue. */ #if BESPOKE_MAC if (key.getKeyCode() == 'Q' && key.getModifiers().isCommandDown()) { return false; } #else if (key.getKeyCode() == KeyPress::F4Key && key.getModifiers().isAltDown()) { return false; } #endif int keyCode = key.getTextCharacter(); if (keyCode < 32 || key.getModifiers().isAltDown()) keyCode = key.getKeyCode(); bool isRepeat = true; if (find(mPressedKeys.begin(), mPressedKeys.end(), keyCode) == mPressedKeys.end()) { mPressedKeys.push_back(keyCode); isRepeat = false; } mSynth.KeyPressed(keyCode, isRepeat); return true; } bool keyStateChanged(bool isKeyDown) override { if (!isKeyDown) { for (int keyCode : mPressedKeys) { if (!KeyPress::isKeyCurrentlyDown(keyCode)) { mPressedKeys.remove(keyCode); mSynth.KeyReleased(keyCode); break; } } } return false; } void focusGained(FocusChangeType cause) override { mSynth.Focus(); } bool isInterestedInFileDrag(const StringArray& files) override { //TODO_PORT(Ryan) return true; } void filesDropped(const StringArray& files, int x, int y) override { std::vector<std::string> strFiles; for (auto file : files) strFiles.push_back(file.toStdString()); mSynth.FilesDropped(strFiles, x, y); } std::string GetAudioDevices() { std::string ret; OwnedArray<AudioIODeviceType> types; mGlobalManagers.mDeviceManager.createAudioDeviceTypes(types); for (int i = 0; i < types.size(); ++i) { String typeName(types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc. types[i]->scanForDevices(); // This must be called before getting the list of devices ret += "output:\n"; { StringArray deviceNames(types[i]->getDeviceNames(false)); for (int j = 0; j < deviceNames.size(); ++j) ret += typeName.toStdString() + ": " + deviceNames[j].toStdString() + "\n"; } ret += "\ninput:\n"; { StringArray deviceNames(types[i]->getDeviceNames(true)); for (int j = 0; j < deviceNames.size(); ++j) ret += typeName.toStdString() + ": " + deviceNames[j].toStdString() + "\n"; } ret += "\n"; } return ret; } struct { juce::AudioDeviceManager mDeviceManager; juce::AudioFormatManager mAudioFormatManager; } mGlobalManagers; ModularSynth mSynth; NVGcontext* mVG; NVGcontext* mFontBoundsVG; int64 mLastFpsUpdateTime; int mFrameCountAccum; std::list<int> mPressedKeys; double mPixelRatio; juce::Point<int> mScreenPosition; juce::Point<int> mDesiredInitialPosition; SpaceMouseMessageWindow mSpaceMouseReader; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainContentComponent) }; // (This function is called by the app startup code to create our main component) Component* createMainContentComponent() { return new MainContentComponent(); } // This function is called when opening the app with a bsk file. void SetStartupSaveStateFile(const juce::String& bskFilePath, Component* component) { auto* mainComponent = dynamic_cast<MainContentComponent*>(component); if (mainComponent == nullptr) ofLog() << "Non main component sent to SetStartupSaveStateFile"; else mainComponent->SetStartupSaveStateFile(bskFilePath); } ```
/content/code_sandbox/Source/MainComponent.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
4,980
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== PulseHocket.h Created: 22 Feb 2020 10:40:15pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "IPulseReceiver.h" #include "Slider.h" #include "TextEntry.h" #include "ClickButton.h" class PulseHocket : public IDrawableModule, public IPulseSource, public IPulseReceiver, public IFloatSliderListener, public ITextEntryListener, public IButtonListener { public: PulseHocket(); virtual ~PulseHocket(); static IDrawableModule* Create() { return new PulseHocket(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return true; } void CreateUIControls() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //IPulseReceiver void OnPulse(double time, float velocity, int flags) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} void TextEntryComplete(TextEntry* entry) override {} void ButtonClicked(ClickButton* button, double time) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; bool IsEnabled() const override { return true; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } void Reseed(); void AdjustHeight(); static const int kMaxDestinations = 16; int mNumDestinations{ 5 }; float mWeight[kMaxDestinations]{}; FloatSlider* mWeightSlider[kMaxDestinations]{}; std::vector<PatchCableSource*> mDestinationCables; float mWidth{ 200 }; float mHeight{ 20 }; bool mDeterministic{ false }; int mSeed{ 0 }; int mRandomIndex{ 0 }; TextEntry* mSeedEntry{ nullptr }; ClickButton* mReseedButton{ nullptr }; ClickButton* mPrevSeedButton{ nullptr }; ClickButton* mNextSeedButton{ nullptr }; }; ```
/content/code_sandbox/Source/PulseHocket.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
607
```c++ #include "UserData.h" #include "OpenFrameworksPort.h" #include "juce_core/juce_core.h" void UpdateUserData(std::string destDirPath) { juce::File bundledDataDir(ofToResourcePath("userdata_original")); juce::File destDataDir(destDirPath); juce::File bundledDataVersionFile(bundledDataDir.getChildFile("userdata_version.txt")); juce::File destDataVersionFile(destDataDir.getChildFile("userdata_version.txt")); if (!bundledDataVersionFile.exists()) return; bool needCopy = false; std::vector<juce::String> preserveOldFileList; std::vector<juce::String> leaveAloneFileList; if (!destDataVersionFile.exists()) { needCopy = true; } else { juce::StringArray bundledVersionLines; juce::StringArray destVersionLines; bundledDataVersionFile.readLines(bundledVersionLines); destDataVersionFile.readLines(destVersionLines); if (bundledVersionLines.isEmpty()) return; if (destVersionLines.isEmpty()) { needCopy = true; } else { int bundledDataVersion = ofToInt(bundledVersionLines[0].toStdString()); int destDataVersion = ofToInt(destVersionLines[0].toStdString()); needCopy = destDataVersion < bundledDataVersion; //I can use the data version in the future to see if special accommodations need to be made for copy/overwriting any specific files preserveOldFileList.push_back(juce::String(destDirPath) + "/layouts/blank.json"); leaveAloneFileList.push_back(juce::String(destDirPath) + "/drums/drums.json"); } } if (needCopy) { ofLog() << "copying data from " + bundledDataDir.getFullPathName().toStdString() + " to " + destDirPath; destDataDir.createDirectory(); for (const auto& entry : juce::RangedDirectoryIterator{ bundledDataDir, true, "*", juce::File::findDirectories }) { juce::String destDirName = juce::String(destDirPath) + "/" + entry.getFile().getRelativePathFrom(bundledDataDir); juce::File(destDirName).createDirectory(); } for (const auto& entry : juce::RangedDirectoryIterator{ bundledDataDir, true }) { juce::String sourceFileName = entry.getFile().getFullPathName(); juce::String destFileName = juce::String(destDirPath) + "/" + entry.getFile().getRelativePathFrom(bundledDataDir).replaceCharacter('\\', '/'); bool copyFile = false; if (!juce::File(destFileName).exists()) copyFile = true; if (juce::File(destFileName).exists() && !juce::File(destFileName).hasIdenticalContentTo(juce::File(sourceFileName))) { if (!VectorContains(destFileName, leaveAloneFileList)) { if (VectorContains(destFileName, preserveOldFileList)) juce::File(destFileName).copyFileTo(destFileName + "_old"); copyFile = true; } } if (copyFile) juce::File(sourceFileName).copyFileTo(destFileName); } } } ```
/content/code_sandbox/Source/UserData.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
729
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // NoteOctaver.cpp // modularSynth // // Created by Ryan Challinor on 5/27/13. // // #include "NoteOctaver.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" #include "UIControlMacros.h" NoteOctaver::NoteOctaver() { } void NoteOctaver::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); INTSLIDER(mOctaveSlider, "octave", &mOctave, -4, 4); CHECKBOX(mRetriggerCheckbox, "retrigger", &mRetrigger); ENDUIBLOCK(mWidth, mHeight); } void NoteOctaver::DrawModule() { if (Minimized() || IsVisible() == false) return; mOctaveSlider->Draw(); mRetriggerCheckbox->Draw(); } void NoteOctaver::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) mNoteOutput.Flush(time); } void NoteOctaver::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (!mEnabled) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); return; } if (pitch >= 0 && pitch < 128) { if (velocity > 0) { mInputNotes[pitch].mOn = true; mInputNotes[pitch].mVelocity = velocity; mInputNotes[pitch].mVoiceIdx = voiceIdx; mInputNotes[pitch].mOutputPitch = pitch + mOctave * TheScale->GetPitchesPerOctave(); } else { mInputNotes[pitch].mOn = false; } } PlayNoteOutput(time, mInputNotes[pitch].mOutputPitch, velocity, mInputNotes[pitch].mVoiceIdx, modulation); } void NoteOctaver::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mOctaveSlider && mEnabled && mRetrigger) { for (int pitch = 0; pitch < 128; ++pitch) { if (mInputNotes[pitch].mOn) { PlayNoteOutput(time + .01, pitch + oldVal, 0, mInputNotes[pitch].mVoiceIdx, ModulationParameters()); PlayNoteOutput(time, pitch + mOctave * TheScale->GetPitchesPerOctave(), mInputNotes[pitch].mVelocity, mInputNotes[pitch].mVoiceIdx, ModulationParameters()); } } } } void NoteOctaver::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void NoteOctaver::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/NoteOctaver.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
745
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== FubbleModule.h Created: 8 Aug 2020 10:03:56am Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "ClickButton.h" #include "Checkbox.h" #include "Transport.h" #include "DropdownList.h" #include "Curve.h" #include "IModulator.h" #include "Slider.h" #include "PerlinNoise.h" namespace { const int kTopControlHeight = 22; const int kTimelineSectionHeight = 50; const int kBottomControlHeight = 58; } class PatchCableSource; class FubbleModule : public IDrawableModule, public IDropdownListener, public IButtonListener, public IFloatSliderListener { public: FubbleModule(); ~FubbleModule(); static IDrawableModule* Create() { return new FubbleModule(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; //IDrawableModule void Init() override; void Poll() override; bool IsResizable() const override { return true; } void Resize(float w, float h) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } void CheckboxUpdated(Checkbox* checkbox, double time) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void ButtonClicked(ClickButton* button, double time) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} void LoadLayout(const ofxJSONElement& moduleInfo) override; void SaveLayout(ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 3; } //IPatchable void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; bool IsEnabled() const override { return mEnabled; } private: float GetPlaybackTime(double time); ofRectangle GetFubbleRect(); ofVec2f GetFubbleMouseCoord(); void RecordPoint(); bool IsHovered(); void Clear(); float GetPerlinNoiseValue(double time, float x, float y, bool horizontal); void UpdatePerlinSeed() { mPerlinSeed = gRandom() % 1000; } //IDrawableModule void DrawModule() override; void DrawModuleUnclipped() override; void GetModuleDimensions(float& width, float& height) override; void OnClicked(float x, float y, bool right) override; bool MouseMoved(float x, float y) override; void MouseReleased() override; struct FubbleAxis : public IModulator { FubbleAxis(FubbleModule* owner, bool horizontal) : mOwner(owner) , mIsHorizontal(horizontal) { } void UpdateControl() { OnModulatorRepatch(); } void SetCableSource(PatchCableSource* cableSource) { mTargetCable = cableSource; } PatchCableSource* GetCableSource() const { return mTargetCable; } //IModulator virtual float Value(int samplesIn = 0) override; virtual bool Active() const override { return mOwner->IsEnabled() && (mHasRecorded || mOwner->mIsRightClicking); } FubbleModule* mOwner{ nullptr }; bool mIsHorizontal{ false }; Curve mCurve{ 0 }; bool mHasRecorded{ false }; }; FubbleAxis mAxisH; FubbleAxis mAxisV; float mLength{ 0 }; bool mQuantizeLength{ false }; Checkbox* mQuantizeLengthCheckbox{ nullptr }; NoteInterval mQuantizeInterval{ NoteInterval::kInterval_4n }; DropdownList* mQuantizeLengthSelector{ nullptr }; float mSpeed{ 1 }; FloatSlider* mSpeedSlider{ nullptr }; ClickButton* mClearButton{ nullptr }; float mWidth{ 220 }; float mHeight{ kTopControlHeight + 200 + kTimelineSectionHeight + kBottomControlHeight }; double mRecordStartOffset{ 0 }; bool mIsDrawing{ false }; bool mIsRightClicking{ false }; float mMouseX{ 0 }; float mMouseY{ 0 }; PerlinNoise mNoise; float mPerlinStrength{ 0 }; FloatSlider* mPerlinStrengthSlider{ nullptr }; float mPerlinScale{ 1 }; FloatSlider* mPerlinScaleSlider{ nullptr }; float mPerlinSpeed{ 1 }; FloatSlider* mPerlinSpeedSlider{ nullptr }; int mPerlinSeed{ 0 }; ClickButton* mUpdatePerlinSeedButton{ nullptr }; }; ```
/content/code_sandbox/Source/FubbleModule.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,206
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // ModuleSaveData.h // modularSynth // // Created by Ryan Challinor on 1/19/14. // // #pragma once #include "TextEntry.h" class ofxJSONElement; class IUIControl; class IntSlider; class FloatSlider; class DropdownList; typedef void (*FillDropdownFn)(DropdownList*); class ModuleSaveData { public: ModuleSaveData(); ~ModuleSaveData(); void Save(ofxJSONElement& moduleInfo); void SetInt(std::string prop, int val); void SetInt(std::string prop, int val, int min, int max, bool isTextField); void SetFloat(std::string prop, float val); void SetFloat(std::string prop, float val, float min, float max, bool isTextField); void SetBool(std::string prop, bool val); void SetString(std::string prop, std::string val); void SetExtents(std::string prop, float min, float max); bool HasProperty(std::string prop); int GetInt(std::string prop); float GetFloat(std::string prop); bool GetBool(std::string prop); std::string GetString(std::string prop); template <class T> T GetEnum(std::string prop) { return (T)GetInt(prop); } int LoadInt(std::string prop, const ofxJSONElement& moduleInfo, int defaultValue = 0, int min = 0, int max = 10, bool isTextField = false); int LoadInt(std::string prop, const ofxJSONElement& moduleInfo, int defaultValue, IntSlider* slider, bool isTextField = false); float LoadFloat(std::string prop, const ofxJSONElement& moduleInfo, float defaultValue = 0, float min = 0, float max = 1, bool isTextField = false); float LoadFloat(std::string prop, const ofxJSONElement& moduleInfo, float defaultValue, FloatSlider* slider, bool isTextField = false); bool LoadBool(std::string prop, const ofxJSONElement& moduleInfo, bool defaultValue = false); std::string LoadString(std::string prop, const ofxJSONElement& moduleInfo, std::string defaultValue = "", FillDropdownFn fillFn = nullptr); template <class T> T LoadEnum(std::string prop, const ofxJSONElement& moduleInfo, int defaultValue, IUIControl* list = nullptr, EnumMap* map = nullptr) { if (list) SetEnumMapFromList(prop, list); if (map) SetEnumMap(prop, map); return (T)LoadInt(prop, moduleInfo, defaultValue); } void UpdatePropertyMax(std::string prop, float max); enum Type { kInt, kFloat, kBool, kString }; struct SaveVal { explicit SaveVal(std::string prop) : mProperty(std::move(prop)) {} std::string mProperty; Type mType{ kInt }; int mInt{ 0 }; float mFloat{ 0 }; bool mBool{ false }; char mString[MAX_TEXTENTRY_LENGTH]{}; float mMin{ 0 }; float mMax{ 10 }; bool mIsTextField{ false }; EnumMap mEnumValues; FillDropdownFn mFillDropdownFn{ nullptr }; }; std::list<SaveVal*>& GetSavedValues() { return mValues; } //generally these are only used internally, needed to expose them for a special case void SetEnumMapFromList(std::string prop, IUIControl* list); void SetEnumMap(std::string prop, EnumMap* map); private: SaveVal* GetVal(std::string prop); std::list<SaveVal*> mValues; }; ```
/content/code_sandbox/Source/ModuleSaveData.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
923
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // PSMoveController.cpp // modularSynth // // Created by Ryan Challinor on 1/18/13. // // #include "PSMoveController.h" #include "SynthGlobals.h" #include "psmove/psmove.h" #include "ModularSynth.h" PSMoveController::PSMoveController() { mMoveMgr.Setup(); mVibration.SetValue(0); } void PSMoveController::Init() { IDrawableModule::Init(); mTransportListenerInfo = TheTransport->AddListener(this, kInterval_4n, OffsetInfo(mMetronomeLagOffset, false), false); } void PSMoveController::CreateUIControls() { IDrawableModule::CreateUIControls(); mConnectButton = new ClickButton(this, "connect", 5, 35); mVibronomeCheckbox = new Checkbox(this, "metronome", 5, 20, &mVibronomeOn); mOffsetSlider = new FloatSlider(this, "offset", 5, 54, 100, 15, &mMetronomeLagOffset, -100, 100); mPitchSlider = new FloatSlider(this, "pitch", 5, 73, 90, 15, &mPitch, 0, 1); mYawSlider = new FloatSlider(this, "yaw", 5, 89, 90, 15, &mYaw, 0, 1); mRollSlider = new FloatSlider(this, "roll", 5, 105, 90, 15, &mRoll, 0, 1); mEnergySlider = new FloatSlider(this, "energy", 5, 121, 90, 15, &mEnergy, 0, 1); mBindPitch = new ClickButton(this, "bindp", 100, 73); mBindYaw = new ClickButton(this, "bindy", 100, 89); mBindRoll = new ClickButton(this, "bindr", 100, 105); mBindEnergy = new ClickButton(this, "binde", 100, 121); } PSMoveController::~PSMoveController() { TheTransport->RemoveListener(this); } void PSMoveController::Poll() { if (!mEnabled) return; mMoveMgr.Update(); mMoveMgr.SetVibration(0, mVibration.Value(gTime)); ofVec3f gyros(0, 0, 0); mMoveMgr.GetGyros(0, gyros); bool isButtonDown = false; if (mMoveMgr.IsButtonDown(0, Btn_MOVE)) { mPitch = ofClamp(mPitch + gyros.x / 50000, 0, 1); if (mPitchUIControl) mPitchUIControl->SetFromMidiCC(mPitch, NextBufferTime(false), false); isButtonDown = true; } if (mMoveMgr.IsButtonDown(0, Btn_SQUARE)) { mYaw = ofClamp(mYaw - gyros.z / 50000, 0, 1); if (mYawUIControl) mYawUIControl->SetFromMidiCC(mYaw, NextBufferTime(false), false); isButtonDown = true; } if (mMoveMgr.IsButtonDown(0, Btn_T)) { mRoll = ofClamp(mRoll + gyros.y / 80000, 0, 1); if (mRollUIControl) mRollUIControl->SetFromMidiCC(mRoll, NextBufferTime(false), false); isButtonDown = true; } if (isButtonDown) mMoveMgr.SetColor(0, mRoll, mYaw, mPitch); else mMoveMgr.SetColor(0, 0, 0, 0); if (mMoveMgr.IsButtonDown(0, Btn_PS)) { if (!mPSButtonDown) { mPSButtonDown = true; mVibronomeOn = !mVibronomeOn; } } else { mPSButtonDown = false; } ofVec3f accel(0, 0, 0); mMoveMgr.GetAccel(0, accel); mEnergy = ofClamp(accel.length() / 5000 - .8f, 0, 1); if (mEnergyUIControl) mEnergyUIControl->SetFromMidiCC(mEnergy, NextBufferTime(false), false); } void PSMoveController::Exit() { IDrawableModule::Exit(); mMoveMgr.Exit(); } void PSMoveController::DrawModule() { if (Minimized() || IsVisible() == false) return; mVibronomeCheckbox->Draw(); mConnectButton->Draw(); mOffsetSlider->Draw(); mPitchSlider->Draw(); mYawSlider->Draw(); mRollSlider->Draw(); mEnergySlider->Draw(); mBindPitch->Draw(); mBindYaw->Draw(); mBindRoll->Draw(); mBindEnergy->Draw(); DrawTextNormal("b: " + ofToString(mMoveMgr.GetBattery(0), 1), 80, 14); } void PSMoveController::CheckboxUpdated(Checkbox* checkbox, double time) { } void PSMoveController::ButtonClicked(ClickButton* button, double time) { if (button == mConnectButton) mMoveMgr.AddMoves(); if (button == mBindPitch) { mPitchUIControl = gBindToUIControl; gBindToUIControl = nullptr; } if (button == mBindYaw) { mYawUIControl = gBindToUIControl; gBindToUIControl = nullptr; } if (button == mBindRoll) { mRollUIControl = gBindToUIControl; gBindToUIControl = nullptr; } if (button == mBindEnergy) { mEnergyUIControl = gBindToUIControl; gBindToUIControl = nullptr; } } void PSMoveController::OnTimeEvent(double time) { if (mVibronomeOn) { float length = 100; if (TheTransport->GetQuantized(time, mTransportListenerInfo) == 0) length = 200; mVibration.Start(1, 0, length); mMoveMgr.SetVibration(0, 1); } } void PSMoveController::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mOffsetSlider) { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) { transportListenerInfo->mInterval = kInterval_4n; transportListenerInfo->mOffsetInfo = OffsetInfo(mMetronomeLagOffset, true); } } } void PSMoveController::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("pitchcontrol", moduleInfo); mModuleSaveData.LoadString("yawcontrol", moduleInfo); mModuleSaveData.LoadString("rollcontrol", moduleInfo); mModuleSaveData.LoadString("energycontrol", moduleInfo); SetUpFromSaveData(); } void PSMoveController::SetUpFromSaveData() { SetPitchControl(TheSynth->FindUIControl(mModuleSaveData.GetString("pitchcontrol"))); SetYawControl(TheSynth->FindUIControl(mModuleSaveData.GetString("yawcontrol"))); SetRollControl(TheSynth->FindUIControl(mModuleSaveData.GetString("rollcontrol"))); SetEnergyControl(TheSynth->FindUIControl(mModuleSaveData.GetString("energycontrol"))); } ```
/content/code_sandbox/Source/PSMoveController.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,799
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== ModulatorExpression.cpp Created: 8 May 2021 5:37:01pm Author: Ryan Challinor ============================================================================== */ #include "ModulatorExpression.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "Profiler.h" namespace { const int kGraphWidth = 100; const int kGraphHeight = 100; const int kGraphX = 115; const int kGraphY = 18; } ModulatorExpression::ModulatorExpression() { } void ModulatorExpression::CreateUIControls() { IDrawableModule::CreateUIControls(); mTextEntry = new TextEntry(this, "y=", 2, 2, MAX_TEXTENTRY_LENGTH - 1, &mEntryString); mTextEntry->SetFlexibleWidth(true); mTextEntry->DrawLabel(true); mExpressionInputSlider = new FloatSlider(this, "input", mTextEntry, kAnchor_Below, 110, 15, &mExpressionInput, 0, 1); mASlider = new FloatSlider(this, "a", mExpressionInputSlider, kAnchor_Below, 110, 15, &mA, -10, 10, 4); mBSlider = new FloatSlider(this, "b", mASlider, kAnchor_Below, 110, 15, &mB, -10, 10, 4); mCSlider = new FloatSlider(this, "c", mBSlider, kAnchor_Below, 110, 15, &mC, -10, 10, 4); mDSlider = new FloatSlider(this, "d", mCSlider, kAnchor_Below, 110, 15, &mD, -10, 10, 4); mESlider = new FloatSlider(this, "e", mDSlider, kAnchor_Below, 110, 15, &mE, -10, 10, 4); mTargetCable = new PatchCableSource(this, kConnectionType_Modulator); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); mSymbolTable.add_variable("x", mExpressionInput); mSymbolTable.add_variable("t", mT); mSymbolTable.add_variable("a", mA); mSymbolTable.add_variable("b", mB); mSymbolTable.add_variable("c", mC); mSymbolTable.add_variable("d", mD); mSymbolTable.add_variable("e", mE); mSymbolTable.add_constants(); mExpression.register_symbol_table(mSymbolTable); mSymbolTableDraw.add_variable("x", mExpressionInputDraw); mSymbolTableDraw.add_variable("t", mT); mSymbolTableDraw.add_variable("a", mA); mSymbolTableDraw.add_variable("b", mB); mSymbolTableDraw.add_variable("c", mC); mSymbolTableDraw.add_variable("d", mD); mSymbolTableDraw.add_variable("e", mE); mSymbolTableDraw.add_constants(); mExpressionDraw.register_symbol_table(mSymbolTableDraw); TextEntryComplete(mTextEntry); } ModulatorExpression::~ModulatorExpression() { } float ModulatorExpression::Value(int samplesIn) { ComputeSliders(samplesIn); if (mExpressionValid) { mT = (gTime + samplesIn * gInvSampleRateMs) * .001; return mExpression.value(); } if (GetSliderTarget()) return GetSliderTarget()->GetMin(); return 0; } void ModulatorExpression::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { OnModulatorRepatch(); if (GetSliderTarget() && fromUserClick) { //mValue1Slider->SetExtents(mSliderTarget->GetMin(), mSliderTarget->GetMax()); //mValue1Slider->SetMode(mSliderTarget->GetMode()); } } void ModulatorExpression::TextEntryComplete(TextEntry* entry) { mExpressionValid = false; exprtk::parser<float> parser; mExpressionValid = parser.compile(mEntryString, mExpression); if (mExpressionValid) parser.compile(mEntryString, mExpressionDraw); } void ModulatorExpression::DrawModule() { if (Minimized() || IsVisible() == false) return; ofPushStyle(); ofPushStyle(); ofSetColor(80, 80, 80, 80 * gModuleDrawAlpha); ofFill(); ofRect(kGraphX, kGraphY, kGraphWidth, kGraphHeight); ofPopStyle(); if (!mExpressionValid) { ofSetColor(255, 0, 0, 60); ofFill(); ofRect(mTextEntry->GetRect(true)); } else { ofPushMatrix(); ofClipWindow(kGraphX, kGraphY, kGraphWidth, kGraphHeight, true); ofPushStyle(); ofSetColor(0, 255, 0, gModuleDrawAlpha); ofNoFill(); ofBeginShape(); float drawMinOutput = mLastDrawMinOutput; float drawMaxOutput = mLastDrawMaxOutput; for (int i = 0; i <= kGraphWidth; ++i) { mExpressionInputDraw = ofMap(i, 0, kGraphWidth, mExpressionInputSlider->GetMin(), mExpressionInputSlider->GetMax()); float output = mExpressionDraw.value(); ofVertex(i + kGraphX, ofMap(output, drawMinOutput, drawMaxOutput, kGraphHeight, 0) + kGraphY); if (i == 0) { mLastDrawMinOutput = output; mLastDrawMaxOutput = output; } else { if (output < mLastDrawMinOutput) mLastDrawMinOutput = output; if (output > mLastDrawMaxOutput) mLastDrawMaxOutput = output; } } ofEndShape(); ofSetColor(245, 58, 135); mExpressionInputDraw = mExpressionInput; ofCircle(kGraphX + ofMap(mExpressionInputDraw, mExpressionInputSlider->GetMin(), mExpressionInputSlider->GetMax(), 0, kGraphWidth), ofMap(mExpressionDraw.value(), mLastDrawMinOutput, mLastDrawMaxOutput, kGraphHeight, 0) + kGraphY, 3); ofPopStyle(); DrawTextNormal(ofToString(drawMinOutput, 2), kGraphX + kGraphWidth * .35f, kGraphY + kGraphHeight - 1); DrawTextNormal(ofToString(drawMaxOutput, 2), kGraphX + kGraphWidth * .35f, kGraphY + 12); DrawTextNormal(ofToString(mExpressionInputSlider->GetMin()), kGraphX + 1, kGraphY + kGraphHeight / 2 + 6); DrawTextRightJustify(ofToString(mExpressionInputSlider->GetMax()), kGraphX + kGraphWidth - 1, kGraphY + kGraphHeight / 2 + 6); ofPopMatrix(); } ofPopStyle(); mTextEntry->Draw(); mExpressionInputSlider->Draw(); mASlider->Draw(); mBSlider->Draw(); mCSlider->Draw(); mDSlider->Draw(); mESlider->Draw(); } void ModulatorExpression::GetModuleDimensions(float& w, float& h) { w = MAX(kGraphX + kGraphWidth + 2, 4 + mTextEntry->GetRect().width); h = kGraphY + kGraphHeight; } void ModulatorExpression::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void ModulatorExpression::SetUpFromSaveData() { } ```
/content/code_sandbox/Source/ModulatorExpression.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,821
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // SampleDrawer.h // Bespoke // // Created by Ryan Challinor on 2/9/15. // // #pragma once #include "OpenFrameworksPort.h" class Sample; class SampleDrawer { public: SampleDrawer() {} void SetSample(Sample* sample) { mSample = sample; } void SetPosition(float x, float y) { mX = x; mY = y; } void SetDimensions(float w, float h) { mWidth = w; mHeight = h; } void SetRange(int startSample, int endSample) { mStartSample = startSample; mEndSample = endSample; } void Draw(int playPosition = -1, float vol = 1, ofColor color = ofColor::black); void DrawLine(int sample, ofColor color); int GetSampleAtMouse(int x, int y); private: Sample* mSample{ nullptr }; int mStartSample{ 0 }; int mEndSample{ 0 }; float mX{ 0 }; float mY{ 0 }; float mWidth{ 1 }; float mHeight{ 1 }; }; ```
/content/code_sandbox/Source/SampleDrawer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
359
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // ModwheelToVibrato.cpp // Bespoke // // Created by Ryan Challinor on 1/4/16. // // #include "ModwheelToVibrato.h" #include "OpenFrameworksPort.h" #include "ModularSynth.h" ModwheelToVibrato::ModwheelToVibrato() { } ModwheelToVibrato::~ModwheelToVibrato() { } void ModwheelToVibrato::CreateUIControls() { IDrawableModule::CreateUIControls(); mVibratoSlider = new FloatSlider(this, "vibrato", 3, 3, 90, 15, &mVibratoAmount, 0, 1); mIntervalSelector = new DropdownList(this, "vibinterval", 96, 3, (int*)(&mVibratoInterval)); mIntervalSelector->AddLabel("1n", kInterval_1n); mIntervalSelector->AddLabel("2n", kInterval_2n); mIntervalSelector->AddLabel("4n", kInterval_4n); mIntervalSelector->AddLabel("4nt", kInterval_4nt); mIntervalSelector->AddLabel("8n", kInterval_8n); mIntervalSelector->AddLabel("8nt", kInterval_8nt); mIntervalSelector->AddLabel("16n", kInterval_16n); mIntervalSelector->AddLabel("16nt", kInterval_16nt); mIntervalSelector->AddLabel("32n", kInterval_32n); } void ModwheelToVibrato::DrawModule() { if (Minimized() || IsVisible() == false) return; mVibratoSlider->Draw(); mIntervalSelector->Draw(); } void ModwheelToVibrato::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled) { mModulation.GetPitchBend(voiceIdx)->AppendTo(modulation.pitchBend); mModulation.GetPitchBend(voiceIdx)->SetLFO(mVibratoInterval, mVibratoAmount); mModulation.GetPitchBend(voiceIdx)->MultiplyIn(modulation.modWheel); modulation.pitchBend = mModulation.GetPitchBend(voiceIdx); modulation.modWheel = nullptr; } PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void ModwheelToVibrato::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void ModwheelToVibrato::DropdownUpdated(DropdownList* list, int oldVal, double time) { } void ModwheelToVibrato::CheckboxUpdated(Checkbox* checkbox, double time) { } void ModwheelToVibrato::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void ModwheelToVibrato::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/ModwheelToVibrato.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
765
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // PeakTracker.cpp // modularSynth // // Created by Ryan Challinor on 1/4/14. // // #include "PeakTracker.h" #include "SynthGlobals.h" #include "Profiler.h" void PeakTracker::Process(float* buffer, int bufferSize) { PROFILER(PeakTracker); for (int j = 0; j < bufferSize; ++j) { float scalar = powf(0.5f, 1.0f / (mDecayTime * gSampleRate)); float input = fabsf(buffer[j]); if (input >= mPeak) { /* When we hit a peak, ride the peak to the top. */ mPeak = input; if (mLimit > std::numeric_limits<float>::epsilon() && mPeak >= mLimit) { mPeak = mLimit; mHitLimitTime = gTime; } } else { /* Exponential decay of output when signal is low. */ mPeak = mPeak * scalar; if (mPeak < std::numeric_limits<float>::epsilon()) mPeak = 0.0; } } } ```
/content/code_sandbox/Source/PeakTracker.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
350
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // AudioRouter.cpp // modularSynth // // Created by Ryan Challinor on 4/7/13. // // #include "AudioRouter.h" #include "ModularSynth.h" #include "Profiler.h" #include "PatchCableSource.h" AudioRouter::AudioRouter() : IAudioProcessor(gBufferSize) , mBlankVizBuffer(VIZ_BUFFER_SECONDS * gSampleRate) { } void AudioRouter::CreateUIControls() { IDrawableModule::CreateUIControls(); mRouteSelector = new RadioButton(this, "route", 5, 3, &mRouteIndex); GetPatchCableSource()->SetEnabled(false); } AudioRouter::~AudioRouter() { } void AudioRouter::Process(double time) { PROFILER(AudioRouter); SyncBuffers(); mBlankVizBuffer.SetNumChannels(GetBuffer()->NumActiveChannels()); for (size_t i = 0; i < mDestinationCables.size(); ++i) { if ((int)i == mRouteIndex) mDestinationCables[i]->SetOverrideVizBuffer(nullptr); else mDestinationCables[i]->SetOverrideVizBuffer(&mBlankVizBuffer); } bool doSwitchAndRamp = false; if (mRouteIndex != mLastProcessedRouteIndex) { doSwitchAndRamp = true; mLastProcessedRouteIndex = mRouteIndex; } IAudioReceiver* target = GetTarget(mRouteIndex + 1); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { float* outputBuffer = GetBuffer()->GetChannel(ch); if (doSwitchAndRamp) mSwitchAndRampIn[ch].Start(time, outputBuffer[0], 0, time + 100); if (abs(mSwitchAndRampIn[ch].Value(time)) > .01f) { BufferCopy(gWorkBuffer, outputBuffer, GetBuffer()->BufferSize()); outputBuffer = gWorkBuffer; for (int i = 0; i < GetBuffer()->BufferSize(); ++i) outputBuffer[i] -= mSwitchAndRampIn[ch].Value(time + i * gInvSampleRateMs); } if (target != nullptr) { Add(target->GetBuffer()->GetChannel(ch), outputBuffer, GetBuffer()->BufferSize()); GetVizBuffer()->WriteChunk(outputBuffer, GetBuffer()->BufferSize(), ch); } } GetBuffer()->Reset(); } void AudioRouter::Poll() { for (int i = 0; i < (int)mDestinationCables.size(); ++i) mDestinationCables[i]->SetShowing(!mOnlyShowActiveCable || i == mRouteIndex || mDestinationCables[i]->GetIsPartOfCircularDependency()); } void AudioRouter::DrawModule() { if (Minimized() || IsVisible() == false) return; mRouteSelector->Draw(); for (int i = 0; i < (int)mDestinationCables.size(); ++i) { ofVec2f pos = mRouteSelector->GetOptionPosition(i) - mRouteSelector->GetPosition(); mDestinationCables[i]->SetManualPosition(pos.x + 10, pos.y + 4); } } void AudioRouter::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { IAudioSource::PostRepatch(cableSource, fromUserClick); for (int i = 0; i < (int)mDestinationCables.size(); ++i) { if (cableSource == mDestinationCables[i]) { IClickable* target = cableSource->GetTarget(); std::string name = target ? target->Name() : " "; mRouteSelector->SetLabel(name.c_str(), i); } } } void AudioRouter::GetModuleDimensions(float& width, float& height) { float w, h; mRouteSelector->GetDimensions(w, h); width = 10 + w; height = 8 + h; } void AudioRouter::RadioButtonUpdated(RadioButton* radio, int oldVal, double time) { if (radio == mRouteSelector) { } } void AudioRouter::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadInt("num_items", moduleInfo, 2, 1, 99, K(isTextField)); mModuleSaveData.LoadBool("only_show_active_cable", moduleInfo, false); SetUpFromSaveData(); } void AudioRouter::SetUpFromSaveData() { int numItems = mModuleSaveData.GetInt("num_items"); int oldNumItems = (int)mDestinationCables.size(); if (numItems > oldNumItems) { for (int i = oldNumItems; i < numItems; ++i) { mRouteSelector->AddLabel(" ", i); auto* additionalCable = new PatchCableSource(this, kConnectionType_Audio); AddPatchCableSource(additionalCable); mDestinationCables.push_back(additionalCable); } } else if (numItems < oldNumItems) { for (int i = oldNumItems - 1; i >= numItems; --i) { mRouteSelector->RemoveLabel(i); RemovePatchCableSource(mDestinationCables[i]); } mDestinationCables.resize(numItems); } mOnlyShowActiveCable = mModuleSaveData.GetBool("only_show_active_cable"); } void AudioRouter::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["num_items"] = (int)mDestinationCables.size(); } ```
/content/code_sandbox/Source/AudioRouter.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,329
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // IAudioReceiver.h // modularSynth // // Created by Ryan Challinor on 12/11/12. // // #pragma once #include "ChannelBuffer.h" class IAudioReceiver { public: enum InputMode { kInputMode_Mono, kInputMode_Multichannel }; IAudioReceiver(int bufferSize) : mInputBuffer(bufferSize) {} virtual ~IAudioReceiver() {} virtual ChannelBuffer* GetBuffer() { return &mInputBuffer; } virtual InputMode GetInputMode() { return kInputMode_Multichannel; } protected: void SyncInputBuffer(); private: ChannelBuffer mInputBuffer; }; ```
/content/code_sandbox/Source/IAudioReceiver.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
247
```c++ #include "PerlinNoise.h" #include <cmath> #include <random> #include <algorithm> #include <numeric> // THIS IS A DIRECT TRANSLATION TO C++11 FROM THE REFERENCE // JAVA IMPLEMENTATION OF THE IMPROVED PERLIN FUNCTION (see path_to_url~perlin/noise/) // THE ORIGINAL JAVA IMPLEMENTATION IS COPYRIGHT 2002 KEN PERLIN // I ADDED AN EXTRA METHOD THAT GENERATES A NEW PERMUTATION VECTOR (THIS IS NOT PRESENT IN THE ORIGINAL IMPLEMENTATION) // Initialize with the reference values for the permutation vector PerlinNoise::PerlinNoise() { // Initialize the permutation vector with the reference values p = { 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 }; // Duplicate the permutation vector p.insert(p.end(), p.begin(), p.end()); } // Generate a new permutation vector based on the value of seed PerlinNoise::PerlinNoise(unsigned int seed) { p.resize(256); // Fill p with values from 0 to 255 std::iota(p.begin(), p.end(), 0); // Initialize a random engine with seed std::default_random_engine engine(seed); // Suffle using the above random engine std::shuffle(p.begin(), p.end(), engine); // Duplicate the permutation vector p.insert(p.end(), p.begin(), p.end()); } double PerlinNoise::noise(double x, double y, double z) { // Find the unit cube that contains the point int X = (int)floor(x) & 255; int Y = (int)floor(y) & 255; int Z = (int)floor(z) & 255; // Find relative x, y,z of point in cube x -= floor(x); y -= floor(y); z -= floor(z); // Compute fade curves for each of x, y, z double u = fade(x); double v = fade(y); double w = fade(z); // Hash coordinates of the 8 cube corners int A = p[X] + Y; int AA = p[A] + Z; int AB = p[A + 1] + Z; int B = p[X + 1] + Y; int BA = p[B] + Z; int BB = p[B + 1] + Z; // Add blended results from 8 corners of cube double res = lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), grad(p[BA], x - 1, y, z)), lerp(u, grad(p[AB], x, y - 1, z), grad(p[BB], x - 1, y - 1, z))), lerp(v, lerp(u, grad(p[AA + 1], x, y, z - 1), grad(p[BA + 1], x - 1, y, z - 1)), lerp(u, grad(p[AB + 1], x, y - 1, z - 1), grad(p[BB + 1], x - 1, y - 1, z - 1)))); return (res + 1.0) / 2.0; } double PerlinNoise::fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } double PerlinNoise::lerp(double t, double a, double b) { return a + t * (b - a); } double PerlinNoise::grad(int hash, double x, double y, double z) { int h = hash & 15; // Convert lower 4 bits of hash into 12 gradient directions double u = h < 8 ? x : y, v = h < 4 ? y : h == 12 || h == 14 ? x : z; return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v); } ```
/content/code_sandbox/Source/PerlinNoise.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,657
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // NoteStepSequencer.cpp // modularSynth // // Created by Ryan Challinor on 11/3/13. // // #include "NoteStepSequencer.h" #include "OpenFrameworksPort.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "LaunchpadInterpreter.h" #include "Profiler.h" #include "FillSaveDropdown.h" #include "UIControlMacros.h" #include "PatchCableSource.h" #include "MathUtils.h" NoteStepSequencer::NoteStepSequencer() { for (int i = 0; i < NSS_MAX_STEPS; ++i) { mVels[i] = ofRandom(1) < .5f ? 127 : 0; mNoteLengths[i] = ofRandom(1) < .5f ? .5f : 1; } RandomizePitches(false); TheScale->AddListener(this); } void NoteStepSequencer::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK(130); DROPDOWN(mIntervalSelector, "interval", (int*)(&mInterval), 40); UIBLOCK_SHIFTRIGHT(); UIBLOCK_SHIFTX(4) BUTTON(mRandomizeAllButton, "random"); UIBLOCK_SHIFTRIGHT(); BUTTON(mRandomizePitchButton, "pitch"); UIBLOCK_SHIFTRIGHT(); BUTTON(mRandomizeVelocityButton, "vel"); UIBLOCK_SHIFTRIGHT(); BUTTON(mRandomizeLengthButton, "len"); UIBLOCK_SHIFTRIGHT(); UIBLOCK_SHIFTX(8); UICONTROL_CUSTOM(mGridControlTarget, new GridControlTarget(UICONTROL_BASICS("grid"))); UIBLOCK_SHIFTRIGHT(); INTSLIDER(mGridControlOffsetXSlider, "x offset", &mGridControlOffsetX, 0, 16); UIBLOCK_SHIFTRIGHT(); INTSLIDER(mGridControlOffsetYSlider, "y offset", &mGridControlOffsetY, 0, 16); UIBLOCK_NEWLINE(); UIBLOCK_PUSHSLIDERWIDTH(150); INTSLIDER(mLengthSlider, "length", &mLength, 1, NSS_MAX_STEPS); UIBLOCK_SHIFTRIGHT(); BUTTON(mShiftBackButton, "<"); UIBLOCK_SHIFTRIGHT(); BUTTON(mShiftForwardButton, ">"); UIBLOCK_SHIFTRIGHT(); BUTTON(mClearButton, "clear"); UIBLOCK_NEWLINE(); UIBLOCK_POPSLIDERWIDTH(); INTSLIDER(mOctaveSlider, "octave", &mOctave, 0, 7); UIBLOCK_SHIFTRIGHT(); DROPDOWN(mNoteModeSelector, "notemode", (int*)(&mNoteMode), 80); UIBLOCK_NEWLINE(); ENDUIBLOCK0(); UIBLOCK(220, 20, 150); FLOATSLIDER(mRandomizePitchChanceSlider, "rand pitch chance", &mRandomizePitchChance, 0, 1); INTSLIDER(mRandomizePitchVarietySlider, "rand pitch variety", &mRandomizePitchVariety, 1, 10); UIBLOCK_NEWCOLUMN(); FLOATSLIDER(mRandomizeLengthChanceSlider, "rand len chance", &mRandomizeLengthChance, 0, 1); FLOATSLIDER(mRandomizeLengthRangeSlider, "rand len range", &mRandomizeLengthRange, 0, 1); UIBLOCK_NEWCOLUMN(); FLOATSLIDER(mRandomizeVelocityChanceSlider, "rand vel chance", &mRandomizeVelocityChance, 0, 1); FLOATSLIDER(mRandomizeVelocityDensitySlider, "rand vel density", &mRandomizeVelocityDensity, 0, 1); ENDUIBLOCK0(); mGrid = new UIGrid("notegrid", 5, 55, 210, 110, 8, 24, this); mVelocityGrid = new UIGrid("velocitygrid", 5, 147, 200, 45, 8, 1, this); mLoopResetPointSlider = new IntSlider(this, "loop reset", -1, -1, 100, 15, &mLoopResetPoint, 0, mLength); mGrid->SetClickValueSubdivisions(mStepLengthSubdivisions); for (int i = 0; i < NSS_MAX_STEPS; ++i) { mToneDropdowns[i] = new DropdownList(this, ("tone" + ofToString(i)).c_str(), -1, -1, &(mTones[i]), 40); mToneDropdowns[i]->SetDrawTriangle(false); mToneDropdowns[i]->SetShowing(false); mVelocitySliders[i] = new IntSlider(this, ("vel" + ofToString(i)).c_str(), -1, -1, 30, 15, &mVels[i], 0, 127); mVelocitySliders[i]->SetShowName(false); mVelocitySliders[i]->SetShowing(false); mLengthSliders[i] = new FloatSlider(this, ("len" + ofToString(i)).c_str(), -1, -1, 30, 15, &mNoteLengths[i], 0.01f, 1, 1); mLengthSliders[i]->SetShowName(false); mLengthSliders[i]->SetShowing(false); } SetUpStepControls(); mIntervalSelector->AddLabel("4", kInterval_4); mIntervalSelector->AddLabel("3", kInterval_3); mIntervalSelector->AddLabel("2", kInterval_2); mIntervalSelector->AddLabel("1n", kInterval_1n); mIntervalSelector->AddLabel("2n", kInterval_2n); mIntervalSelector->AddLabel("4n", kInterval_4n); mIntervalSelector->AddLabel("4nt", kInterval_4nt); mIntervalSelector->AddLabel("8n", kInterval_8n); mIntervalSelector->AddLabel("8nt", kInterval_8nt); mIntervalSelector->AddLabel("16n", kInterval_16n); mIntervalSelector->AddLabel("16nt", kInterval_16nt); mIntervalSelector->AddLabel("32n", kInterval_32n); mIntervalSelector->AddLabel("64n", kInterval_64n); mIntervalSelector->AddLabel("none", kInterval_None); mNoteModeSelector->AddLabel("scale", kNoteMode_Scale); mNoteModeSelector->AddLabel("chromatic", kNoteMode_Chromatic); mNoteModeSelector->AddLabel("pentatonic", kNoteMode_Pentatonic); mNoteModeSelector->AddLabel("5ths", kNoteMode_Fifths); mGrid->SetSingleColumnMode(true); mGrid->SetFlip(true); mGrid->SetListener(this); mGrid->SetGridMode(UIGrid::kHorislider); mGrid->SetRequireShiftForMultislider(true); mVelocityGrid->SetGridMode(UIGrid::kMultisliderBipolar); mVelocityGrid->SetListener(this); mLoopResetPointSlider->SetShowing(mHasExternalPulseSource); for (int i = 0; i < NSS_MAX_STEPS; ++i) { mStepCables[i] = new AdditionalNoteCable(); mStepCables[i]->SetPatchCableSource(new PatchCableSource(this, kConnectionType_Note)); mStepCables[i]->GetPatchCableSource()->SetOverrideCableDir(ofVec2f(0, 1), PatchCableSource::Side::kBottom); AddPatchCableSource(mStepCables[i]->GetPatchCableSource()); } } NoteStepSequencer::~NoteStepSequencer() { TheTransport->RemoveListener(this); TheTransport->RemoveAudioPoller(this); TheScale->RemoveListener(this); } void NoteStepSequencer::SetMidiController(std::string name) { if (mController) mController->RemoveListener(this); mController = TheSynth->FindMidiController(name); if (mController) mController->AddListener(this, 0); UpdateLights(); } void NoteStepSequencer::Init() { IDrawableModule::Init(); SyncGridToSeq(); mTransportListenerInfo = TheTransport->AddListener(this, mInterval, OffsetInfo(0, true), true); TheTransport->AddAudioPoller(this); } void NoteStepSequencer::Poll() { if (mGridSyncQueued) { SyncGridToSeq(); mGridSyncQueued = false; } UpdateGridControllerLights(false); } void NoteStepSequencer::DrawModule() { if (Minimized() || IsVisible() == false) return; ofSetColor(255, 255, 255, gModuleDrawAlpha); mLoopResetPointSlider->SetShowing(mHasExternalPulseSource); mGridControlOffsetXSlider->SetShowing((mGridControlTarget->GetGridController() != nullptr && mLength > mGridControlTarget->GetGridController()->NumCols()) || mPush2GridDisplayMode == Push2GridDisplayMode::GridView); mGridControlOffsetYSlider->SetShowing((mGridControlTarget->GetGridController() != nullptr && mNoteRange > mGridControlTarget->GetGridController()->NumRows()) || mPush2GridDisplayMode == Push2GridDisplayMode::GridView); mIntervalSelector->Draw(); mLengthSlider->Draw(); mOctaveSlider->Draw(); mNoteModeSelector->Draw(); mShiftBackButton->Draw(); mShiftForwardButton->Draw(); mClearButton->Draw(); mRandomizeAllButton->Draw(); mRandomizePitchButton->Draw(); mRandomizeLengthButton->Draw(); mRandomizeVelocityButton->Draw(); mLoopResetPointSlider->Draw(); mGridControlTarget->Draw(); mGridControlOffsetXSlider->Draw(); mGridControlOffsetYSlider->Draw(); mRandomizePitchChanceSlider->Draw(); mRandomizePitchVarietySlider->Draw(); mRandomizeLengthChanceSlider->Draw(); mRandomizeLengthRangeSlider->Draw(); mRandomizeVelocityChanceSlider->Draw(); mRandomizeVelocityDensitySlider->Draw(); int majorColSize = Transport::IsTripletInterval(mInterval) ? 3 : 4; if (majorColSize < mLength) mGrid->SetMajorColSize(majorColSize); else mGrid->SetMajorColSize(-1); mGrid->Draw(); mVelocityGrid->Draw(); ofPushStyle(); ofSetColor(128, 128, 128, gModuleDrawAlpha * .8f); for (int i = 0; i < mGrid->GetRows(); ++i) { ofVec2f pos = mGrid->GetCellPosition(0, i - 1) + mGrid->GetPosition(true); float scale = MIN(mGrid->IClickable::GetDimensions().y / mGrid->GetRows() - 2, 18); DrawTextNormal(NoteName(RowToPitch(i), false, true) + "(" + ofToString(RowToPitch(i)) + ")", pos.x + 1, pos.y - (scale / 8), scale); } ofPopStyle(); if (mGridControlTarget->GetGridController() || mPush2GridDisplayMode == Push2GridDisplayMode::GridView) { int controllerCols = 8; int controllerRows = 8; if (mGridControlTarget->GetGridController() != nullptr) { controllerCols = mGridControlTarget->GetGridController()->NumCols(); controllerRows = mGridControlTarget->GetGridController()->NumRows(); } ofPushStyle(); ofNoFill(); ofSetLineWidth(4); ofSetColor(255, 0, 0, 50); float squareh = float(mGrid->GetHeight()) / mNoteRange; float squarew = float(mGrid->GetWidth()) / mLength; ofRectangle gridRect = mGrid->GetRect(K(local)); ofRect(gridRect.x + squarew * mGridControlOffsetX, gridRect.y + gridRect.height - squareh * (mGridControlOffsetY + controllerRows), squarew * controllerCols, squareh * controllerRows); ofPopStyle(); } ofPushStyle(); ofFill(); float gridX, gridY, gridW, gridH; mGrid->GetPosition(gridX, gridY, true); gridW = mGrid->GetWidth(); gridH = mGrid->GetHeight(); float boxHeight = (float(gridH) / mNoteRange); float boxWidth = (float(gridW) / mGrid->GetCols()); for (int i = 0; i < mGrid->GetCols() - 1; ++i) { if (mNoteLengths[i] == 1 && mTones[i] == mTones[i + 1] && mVels[i] > mVels[i + 1] && mVels[i + 1] != 0) { ofSetColor(255, 255, 255, 255); ofFill(); float y = gridY + gridH - mTones[i] * boxHeight; ofRect(gridX + boxWidth * i + 1, y - boxHeight + 1, boxWidth * 1.5f - 2, boxHeight - 2); } } for (int i = 0; i < mNoteRange; ++i) { if (RowToPitch(i) % TheScale->GetPitchesPerOctave() == TheScale->ScaleRoot() % TheScale->GetPitchesPerOctave()) ofSetColor(0, 255, 0, 80); else if (TheScale->GetPitchesPerOctave() == 12 && RowToPitch(i) % TheScale->GetPitchesPerOctave() == (TheScale->ScaleRoot() + 7) % TheScale->GetPitchesPerOctave()) ofSetColor(200, 150, 0, 80); else if (mNoteMode == kNoteMode_Chromatic && TheScale->IsInScale(RowToPitch(i))) ofSetColor(100, 75, 0, 80); else continue; float y = gridY + gridH - i * boxHeight; ofRect(gridX, y - boxHeight, gridW, boxHeight); } for (int i = 0; i < mGrid->GetCols(); ++i) { const float kPlayHighlightDurationMs = 250; if (mLastStepPlayTime[i] != -1) { if (gTime - mLastStepPlayTime[i] < kPlayHighlightDurationMs) { if (gTime - mLastStepPlayTime[i] > 0) { float fade = (1 - (gTime - mLastStepPlayTime[i]) / kPlayHighlightDurationMs); ofPushStyle(); ofNoFill(); ofSetLineWidth(3 * fade); ofVec2f pos = mGrid->GetCellPosition(i, mTones[i]) + mGrid->GetPosition(true); float xsize = float(mGrid->GetWidth()) / mGrid->GetCols(); float ysize = float(mGrid->GetHeight()) / mGrid->GetRows(); ofSetColor(ofColor::white, fade * 255); ofRect(pos.x, pos.y, xsize, ysize); ofPopStyle(); } } else { mLastStepPlayTime[i] = -1; } } } float controlYPos = gridY + gridH + mVelocityGrid->GetHeight(); float moduleWidth, moduleHeight; GetModuleDimensions(moduleWidth, moduleHeight); if (mLoopResetPointSlider->IsShowing()) controlYPos += 19; for (int i = 0; i < NSS_MAX_STEPS; ++i) { if (i < mLength) { mToneDropdowns[i]->SetShowing(mShowStepControls); mToneDropdowns[i]->SetPosition(gridX + boxWidth * i, controlYPos); mToneDropdowns[i]->SetWidth(std::min(boxWidth, 30.0f)); mToneDropdowns[i]->Draw(); mVelocitySliders[i]->SetShowing(mShowStepControls); mVelocitySliders[i]->SetPosition(gridX + boxWidth * i, controlYPos + 17); mVelocitySliders[i]->SetDimensions(boxWidth, 15); mVelocitySliders[i]->Draw(); mLengthSliders[i]->SetShowing(mShowStepControls); mLengthSliders[i]->SetPosition(gridX + boxWidth * i, controlYPos + 32); mLengthSliders[i]->SetDimensions(boxWidth, 15); mLengthSliders[i]->Draw(); } else { mToneDropdowns[i]->SetShowing(false); mVelocitySliders[i]->SetShowing(false); mLengthSliders[i]->SetShowing(false); } if (i < mLength && mShowStepControls) { ofVec2f pos = mVelocityGrid->GetCellPosition(i, 0) + mVelocityGrid->GetPosition(true); pos.x += mVelocityGrid->GetWidth() / float(mLength) * .5f; pos.y = moduleHeight - 7; mStepCables[i]->GetPatchCableSource()->SetManualPosition(pos.x, pos.y); mStepCables[i]->GetPatchCableSource()->SetEnabled(true); } else { mStepCables[i]->GetPatchCableSource()->SetEnabled(false); } } ofPopStyle(); } void NoteStepSequencer::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); mGrid->TestClick(x, y, right); mVelocityGrid->TestClick(x, y, right); } void NoteStepSequencer::MouseReleased() { IDrawableModule::MouseReleased(); mGrid->MouseReleased(); mVelocityGrid->MouseReleased(); } bool NoteStepSequencer::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); mGrid->NotifyMouseMoved(x, y); mVelocityGrid->NotifyMouseMoved(x, y); return false; } bool NoteStepSequencer::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) { mGrid->NotifyMouseScrolled(x, y, scrollX, scrollY, isSmoothScroll, isInvertedScroll); mVelocityGrid->NotifyMouseScrolled(x, y, scrollX, scrollY, isSmoothScroll, isInvertedScroll); return false; } void NoteStepSequencer::SetEnabled(bool on) { mEnabled = on; if (!on) mNoteOutput.Flush(gTime); } void NoteStepSequencer::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) mNoteOutput.Flush(time); } void NoteStepSequencer::GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) { if (grid == mGrid) { for (int i = 0; i < mGrid->GetCols(); ++i) { bool colHasPitch = false; for (int j = 0; j < mGrid->GetRows(); ++j) { float val = mGrid->GetVal(i, j); if (val > 0) { mTones[i] = j; mNoteLengths[i] = val; colHasPitch = true; break; } } if (!colHasPitch) mVels[i] = 0; else if (colHasPitch && mVels[i] == 0) mVels[i] = 127; mVelocityGrid->SetVal(i, 0, mVels[i] / 127.0f, false); } } if (grid == mVelocityGrid) { for (int i = 0; i < mVelocityGrid->GetCols(); ++i) mVels[i] = mVelocityGrid->GetVal(i, 0) * 127; SyncGridToSeq(); } } int NoteStepSequencer::RowToPitch(int row) { row += mRowOffset; int numPitchesInScale = TheScale->NumTonesInScale(); switch (mNoteMode) { case kNoteMode_Scale: return TheScale->GetPitchFromTone(row + mOctave * numPitchesInScale + TheScale->GetScaleDegree()); case kNoteMode_Chromatic: return row + mOctave * TheScale->GetPitchesPerOctave(); case kNoteMode_Pentatonic: { bool isMinor = TheScale->IsInScale(TheScale->ScaleRoot() + 3); const int minorPentatonic[5] = { 0, 3, 5, 7, 10 }; const int majorPentatonic[5] = { 0, 2, 4, 7, 9 }; if (isMinor) return TheScale->ScaleRoot() + (row / 5 + mOctave) * TheScale->GetPitchesPerOctave() + minorPentatonic[row % 5]; else return TheScale->ScaleRoot() + (row / 5 + mOctave) * TheScale->GetPitchesPerOctave() + majorPentatonic[row % 5]; } case kNoteMode_Fifths: { int oct = (row / 2) * numPitchesInScale; bool isFifth = row % 2 == 1; int fifths = oct; if (isFifth) fifths += 4; return TheScale->GetPitchFromTone(fifths + mOctave * numPitchesInScale + TheScale->GetScaleDegree()); } } return row; } int NoteStepSequencer::PitchToRow(int pitch) { for (int i = 0; i < mGrid->GetRows(); ++i) { if (pitch == RowToPitch(i)) return i; } return -1; } void NoteStepSequencer::SetStep(int index, int row, int velocity, float length) { if (index >= 0 && index < NSS_MAX_STEPS) { mTones[index] = std::clamp(row, 0, MAX_GRID_ROWS - 1); mVels[index] = ofClamp(velocity, 0, 127); mNoteLengths[index] = length; SyncGridToSeq(); } } void NoteStepSequencer::SetPitch(int index, int pitch, int velocity, float length) { if (index >= 0 && index < NSS_MAX_STEPS) { mTones[index] = PitchToRow(pitch); mVels[index] = ofClamp(velocity, 0, 127); mNoteLengths[index] = length; SyncGridToSeq(); } } void NoteStepSequencer::GetPush2Layout(int& sequenceRows, int& pitchCols, int& pitchRows) { sequenceRows = (mLength - 1) / 8 + 1; if (mNoteMode == kNoteMode_Scale && TheScale->NumTonesInScale() == 7) pitchCols = 7; else pitchCols = 8; pitchRows = (mNoteRange - 1) / pitchCols + 1; } bool NoteStepSequencer::OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue) { if (mPush2GridDisplayMode == Push2GridDisplayMode::PerStep) { int sequenceRows, pitchCols, pitchRows; GetPush2Layout(sequenceRows, pitchCols, pitchRows); if (type == kMidiMessage_Note) { if (controlIndex == 12) { mPush2VelocityHeld = (midiValue > 0); return true; } if (controlIndex >= 36 && controlIndex <= 99) { int gridIndex = controlIndex - 36; int x = gridIndex % 8; int y = 7 - gridIndex / 8; if (gridIndex >= 0 && gridIndex < 64 && y < sequenceRows) { int index = x + y * 8; if (midiValue > 0) { mPush2HeldStep = index; mPush2HeldStepWasEdited = false; mPush2ButtonPressTime = gTime; } else if (index == mPush2HeldStep) { if (mVels[mPush2HeldStep] == 0) mVels[mPush2HeldStep] = mQueuedPush2Vel; else if (!mPush2HeldStepWasEdited && gTime - mPush2ButtonPressTime < 500) mVels[index] = 0; mPush2HeldStep = -1; } } else if (y < sequenceRows + pitchRows) { if (midiValue > 0) { int index = x + (pitchRows - 1 - (y - sequenceRows)) * pitchCols; if (index < 0 || index >= mNoteRange || x >= pitchCols) { //out of range mQueuedPush2Tone = -2; } else if (mPush2HeldStep != -1) { mTones[mPush2HeldStep] = index; mPush2HeldStepWasEdited = true; } else { mQueuedPush2Tone = index; } } } else if (y == 7) { if (midiValue > 0) { mPush2LengthHeld = true; if (mPush2HeldStep != -1) { mNoteLengths[mPush2HeldStep] = (x + 1) / 8.0f; mPush2HeldStepWasEdited = true; } else { mQueuedPush2Length = (x + 1) / 8.0f; } } else { mPush2LengthHeld = false; } } SyncGridToSeq(); return true; } } } else if (mPush2GridDisplayMode == Push2GridDisplayMode::GridView) { if (type == kMidiMessage_Note) { int gridIndex = controlIndex - 36; int x = gridIndex % 8; int y = 7 - gridIndex / 8; int col = x + mGridControlOffsetX; int row = y - mGridControlOffsetY; if (gridIndex >= 0 && gridIndex < 64 && col >= 0 && col < mLength && row >= 8 - mNoteRange && row < 8) { if (midiValue > 0) { mPush2HeldStep = col; mPush2HeldStepWasEdited = false; mPush2ButtonPressTime = gTime; } int tone = 8 - 1 - row; if (mTones[col] == tone && mVels[col] > 0) { if (midiValue == 0 && !mPush2HeldStepWasEdited && gTime - mPush2ButtonPressTime < 500) { if (mNoteLengths[col] < 1) mNoteLengths[col] = 1; else mVels[col] = 0; SyncGridToSeq(); } } else { if (midiValue > 0) { mTones[col] = tone; mVels[col] = mQueuedPush2Vel; mNoteLengths[col] = .5f; mPush2HeldStepWasEdited = true; SyncGridToSeq(); } } if (midiValue == 0) mPush2HeldStep = -1; } return true; } } if (type == kMidiMessage_Control) { if (controlIndex == push2->GetGridControllerOption1Control()) { if (midiValue > 0) { if (mPush2GridDisplayMode == Push2GridDisplayMode::PerStep) mPush2GridDisplayMode = Push2GridDisplayMode::GridView; else mPush2GridDisplayMode = Push2GridDisplayMode::PerStep; } return true; } } if (type == kMidiMessage_PitchBend) { float val = midiValue / MidiDevice::kPitchBendMax; if (mPush2HeldStep != -1) { mVels[mPush2HeldStep] = int(val * 127); mPush2HeldStepWasEdited = true; } else { mQueuedPush2Vel = int(val * 127); } SyncGridToSeq(); return true; } return false; } void NoteStepSequencer::UpdatePush2Leds(Push2Control* push2) { int sequenceRows, pitchCols, pitchRows; GetPush2Layout(sequenceRows, pitchCols, pitchRows); int displayStep = std::clamp(mArpIndex, 0, mLength - 1); if (mPush2HeldStep != -1) displayStep = mPush2HeldStep; for (int x = 0; x < 8; ++x) { for (int y = 0; y < 8; ++y) { int pushColor = 0; if (mPush2GridDisplayMode == Push2GridDisplayMode::PerStep) { if (y < sequenceRows) { int index = x + y * 8; if (index >= mLength) pushColor = 0; else if (index == mPush2HeldStep) pushColor = 125; else if (index == displayStep) pushColor = 101; else if (mVels[index] > 0) pushColor = mNoteLengths[index] == 1 ? 93 : 95; else pushColor = 92; } else if (y < sequenceRows + pitchRows) { int index = x + (pitchRows - 1 - (y - sequenceRows)) * pitchCols; int pitch = RowToPitch(index); if (x >= pitchCols || index < 0 || index >= mNoteRange) pushColor = mQueuedPush2Tone == -2 ? 126 : 0; else if (index == mQueuedPush2Tone) pushColor = 126; else if (index == mTones[displayStep] && ((mVels[displayStep] > 0 && !mAlreadyDidNoteOff) || mPush2HeldStep != -1)) pushColor = gTime - mLastStepPlayTime[displayStep] < 100 ? 127 : 2; else if (TheScale->IsRoot(pitch)) pushColor = 69; else if (TheScale->IsInPentatonic(pitch)) pushColor = 77; else pushColor = 78; } else if (y == 7) { float displayLength = 0; if (mPush2LengthHeld && mPush2HeldStep == -1) displayLength = mQueuedPush2Length; else if (mVels[displayStep] > 0) displayLength = mNoteLengths[displayStep]; if (displayLength * 8 - 1 >= x) pushColor = 83; else pushColor = 84; } } else if (mPush2GridDisplayMode == Push2GridDisplayMode::GridView) { int column = x + mGridControlOffsetX; int row = y - mGridControlOffsetY; if (column >= 0 && column < mLength && row >= 8 - mNoteRange && row < 8) { bool isHighlightCol = (column == mGrid->GetHighlightCol(NextBufferTime(true))); int pitch = RowToPitch(row); if (TheScale->IsRoot(pitch)) pushColor = 69; else if (TheScale->IsInPentatonic(pitch)) pushColor = 77; else pushColor = 78; if (isHighlightCol) pushColor = 83; if (mTones[column] == 8 - 1 - row && mVels[column] > 0) { if (column == mPush2HeldStep) pushColor = 127; else if (isHighlightCol) pushColor = 126; else pushColor = mNoteLengths[column] == 1 ? 125 : 95; } } } push2->SetLed(kMidiMessage_Note, x + (7 - y) * 8 + 36, pushColor); } } std::string touchStripLights = { 0x00, 0x21, 0x1D, 0x01, 0x01, 0x19 }; int displayVel = mVels[displayStep]; if (mPush2VelocityHeld && mPush2HeldStep == -1) displayVel = mQueuedPush2Vel; for (int i = 0; i < 16; ++i) { int ledLow = ((i * 2) / 32.0f) < displayVel / 127.0f; int ledHigh = ((i * 2 + 1) / 32.0f) < displayVel / 127.0f; unsigned char c = ledLow + (ledHigh << 3); touchStripLights += c; } push2->GetDevice()->SendSysEx(touchStripLights); push2->SetLed(kMidiMessage_Control, push2->GetGridControllerOption1Control(), 127); } void NoteStepSequencer::OnTransportAdvanced(float amount) { PROFILER(NoteStepSequencer); ComputeSliders(0); if ((mLastNoteLength < 1 || mHasExternalPulseSource) && !mAlreadyDidNoteOff) { if (NextBufferTime(true) > mLastNoteEndTime) { PlayNoteOutput(mLastNoteEndTime, mLastPitch, 0); if (mShowStepControls && mLastStepIndex < (int)mStepCables.size() && mLastStepIndex != -1) SendNoteToCable(mLastStepIndex, mLastNoteEndTime, mLastPitch, 0); mAlreadyDidNoteOff = true; } } } void NoteStepSequencer::OnPulse(double time, float velocity, int flags) { mHasExternalPulseSource = true; Step(time, velocity, flags); } void NoteStepSequencer::OnTimeEvent(double time) { if (!mHasExternalPulseSource) Step(time, 1, 0); } void NoteStepSequencer::Step(double time, float velocity, int pulseFlags) { if (!mEnabled) return; int direction = 1; if (pulseFlags & kPulseFlag_Backward) direction = -1; if (pulseFlags & kPulseFlag_Repeat) direction = 0; mArpIndex += direction; if (direction > 0 && mArpIndex >= mLength) mArpIndex -= (mLength - mLoopResetPoint); if (direction < 0 && mArpIndex < mLoopResetPoint) mArpIndex += (mLength - mLoopResetPoint); if (pulseFlags & kPulseFlag_Reset) mArpIndex = 0; else if (pulseFlags & kPulseFlag_Random) mArpIndex = gRandom() % mLength; if (!mHasExternalPulseSource || (pulseFlags & kPulseFlag_SyncToTransport)) { mArpIndex = TheTransport->GetSyncedStep(time, this, mTransportListenerInfo, mLength); } if (pulseFlags & kPulseFlag_Align) { int stepsPerMeasure = TheTransport->GetStepsPerMeasure(this); int numMeasures = ceil(float(mLength) / stepsPerMeasure); int measure = TheTransport->GetMeasure(time) % numMeasures; int step = ((TheTransport->GetQuantized(time, mTransportListenerInfo) % stepsPerMeasure) + measure * stepsPerMeasure) % mLength; mArpIndex = step; } int offPitch = -1; int offStep = -1; if (mLastPitch >= 0 && !mAlreadyDidNoteOff) { offPitch = mLastPitch; offStep = mLastStepIndex; } if (mQueuedPush2Tone != -1) { if (mQueuedPush2Tone == -2) { mVels[mArpIndex] = 0; } else { mTones[mArpIndex] = mQueuedPush2Tone; mVels[mArpIndex] = mQueuedPush2Vel; mNoteLengths[mArpIndex] = mQueuedPush2Length; } mQueuedPush2Tone = -1; mGridSyncQueued = true; } int current = mTones[mArpIndex]; if (mVels[mArpIndex] <= 1) { mLastPitch = -1; } else { int outPitch = RowToPitch(current); if (mLastPitch == outPitch && !mAlreadyDidNoteOff) //same note, play noteoff first { PlayNoteOutput(time, mLastPitch, 0, -1); if (mShowStepControls && mLastStepIndex < (int)mStepCables.size() && mLastStepIndex != -1) SendNoteToCable(mLastStepIndex, time, mLastPitch, 0); mAlreadyDidNoteOff = true; offPitch = -1; } if (mVels[mArpIndex] > 1) { PlayNoteOutput(time, outPitch, mVels[mArpIndex] * velocity, -1); if (mShowStepControls && mArpIndex < (int)mStepCables.size()) SendNoteToCable(mArpIndex, time, outPitch, mVels[mArpIndex] * velocity); mLastPitch = outPitch; mLastStepIndex = mArpIndex; mLastNoteLength = mNoteLengths[mArpIndex]; mLastNoteEndTime = time + mLastNoteLength * TheTransport->GetDuration(mInterval); mLastStepPlayTime[mArpIndex] = time; mAlreadyDidNoteOff = false; } } if (offPitch != -1) { PlayNoteOutput(time, offPitch, 0, -1); if (mShowStepControls && offStep < (int)mStepCables.size()) SendNoteToCable(offStep, time, offPitch, 0); if (offPitch == mLastPitch) { mLastPitch = -1; } } mGrid->SetHighlightCol(time, mArpIndex); mVelocityGrid->SetHighlightCol(time, mArpIndex); UpdateLights(); UpdateGridControllerLights(false); } void NoteStepSequencer::SendNoteToCable(int index, double time, int pitch, int velocity) { mStepCables[index]->PlayNoteOutput(time, pitch, velocity); } void NoteStepSequencer::UpdateLights() { if (mController) { for (int i = 0; i < NSS_MAX_STEPS; ++i) { int button = StepToButton(i); int color = 0; if (i < mLength) { if (i == mGrid->GetHighlightCol(NextBufferTime(true))) { color = LaunchpadInterpreter::LaunchpadColor(0, 3); } else if (mVels[i] > 1) { int level = (mVels[i] / 50) + 1; color = LaunchpadInterpreter::LaunchpadColor(level, level); } else { color = LaunchpadInterpreter::LaunchpadColor(1, 0); } } mController->SendNote(0, button, color); } } } int NoteStepSequencer::ButtonToStep(int button) { if ((button >= 9 && button <= 12) || (button >= 25 && button <= 28)) { return button <= 12 ? (button - 9) : (button - 21); } return -1; } int NoteStepSequencer::StepToButton(int step) { return step < 4 ? (step + 9) : (step + 21); } float NoteStepSequencer::ExtraWidth() const { return 10; } float NoteStepSequencer::ExtraHeight() const { float height = 103; if (mLoopResetPointSlider->IsShowing()) height += 17; if (mShowStepControls) height += 17 * 3 + 5; return height; } void NoteStepSequencer::GetModuleDimensions(float& width, float& height) { width = mGrid->GetWidth() + ExtraWidth(); height = mGrid->GetHeight() + ExtraHeight(); } void NoteStepSequencer::Resize(float w, float h) { mGrid->SetDimensions(MAX(w - ExtraWidth(), 210), MAX(h - ExtraHeight(), 80)); UpdateVelocityGridPos(); } void NoteStepSequencer::UpdateVelocityGridPos() { mVelocityGrid->SetDimensions(mGrid->GetWidth(), 45); float gridX, gridY; mGrid->GetPosition(gridX, gridY, true); mVelocityGrid->SetPosition(gridX, gridY + mGrid->GetHeight()); mLoopResetPointSlider->PositionTo(mVelocityGrid, kAnchor_Below); mLoopResetPointSlider->SetDimensions(mVelocityGrid->GetWidth(), 15); } void NoteStepSequencer::OnMidiNote(MidiNote& note) { int step = ButtonToStep(note.mPitch); if (step != -1 && note.mVelocity > 0) { if (mSetLength) { mLength = step + 1; UpdateLights(); } else { mArpIndex = step - 1; } } } void NoteStepSequencer::OnMidiControl(MidiControl& control) { if (control.mControl >= 21 && control.mControl <= 28) { int step = control.mControl - 21; mTones[step] = MIN(control.mValue / 127.0f * mNoteRange, mNoteRange - 1); SyncGridToSeq(); } if (control.mControl >= 41 && control.mControl <= 48) { int step = control.mControl - 41; if (control.mValue >= 1) mVels[step] = control.mValue; SyncGridToSeq(); UpdateLights(); } if (control.mControl == 115) { mSetLength = control.mValue > 0; if (mController) mController->SendCC(0, 116, control.mValue); } } void NoteStepSequencer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (velocity > 0) { mHasExternalPulseSource = true; mArpIndex = pitch % mLength; Step(time, velocity / 127.0f, kPulseFlag_Repeat); } } void NoteStepSequencer::ShiftSteps(int amount) { int newTones[NSS_MAX_STEPS]; int newVels[NSS_MAX_STEPS]; float newLengths[NSS_MAX_STEPS]; memcpy(newTones, mTones, NSS_MAX_STEPS * sizeof(int)); memcpy(newVels, mVels, NSS_MAX_STEPS * sizeof(int)); memcpy(newLengths, mNoteLengths, NSS_MAX_STEPS * sizeof(float)); for (int i = 0; i < mLength; ++i) { int dest = (i + mLength + amount) % mLength; newTones[dest] = mTones[i]; newVels[dest] = mVels[i]; newLengths[dest] = mNoteLengths[i]; } memcpy(mTones, newTones, NSS_MAX_STEPS * sizeof(int)); memcpy(mVels, newVels, NSS_MAX_STEPS * sizeof(int)); memcpy(mNoteLengths, newLengths, NSS_MAX_STEPS * sizeof(float)); SyncGridToSeq(); } void NoteStepSequencer::UpdateGridControllerLights(bool force) { if (mGridControlTarget->GetGridController()) { for (int x = 0; x < mGridControlTarget->GetGridController()->NumCols(); ++x) { for (int y = 0; y < mGridControlTarget->GetGridController()->NumRows(); ++y) { int column = x + mGridControlOffsetX; int row = y - mGridControlOffsetY; GridColor color = GridColor::kGridColorOff; bool isHighlightCol = (column == mGrid->GetHighlightCol(NextBufferTime(true))); if (isHighlightCol) color = GridColor::kGridColor2Dim; if (column < mLength) { if (mTones[column] == mGridControlTarget->GetGridController()->NumRows() - 1 - row && mVels[column] > 0) { if (isHighlightCol) color = GridColor::kGridColor3Bright; else color = GridColor::kGridColor1Bright; } } mGridControlTarget->GetGridController()->SetLight(x, y, color, force); } } } } void NoteStepSequencer::OnControllerPageSelected() { UpdateGridControllerLights(true); } void NoteStepSequencer::OnGridButton(int x, int y, float velocity, IGridController* grid) { int col = x + mGridControlOffsetX; int row = y - mGridControlOffsetY; if (grid == mGridControlTarget->GetGridController() && col >= 0 && col < mLength && velocity > 0) { int tone = mGridControlTarget->GetGridController()->NumRows() - 1 - row; if (mTones[col] == tone && mVels[col] > 0) { mVels[col] = 0; } else { mTones[col] = tone; mVels[col] = velocity * 127; } SyncGridToSeq(); UpdateGridControllerLights(false); } } void NoteStepSequencer::ButtonClicked(ClickButton* button, double time) { if (button == mShiftBackButton) ShiftSteps(-1); if (button == mShiftForwardButton) ShiftSteps(1); if (button == mClearButton) { for (int i = 0; i < mLength; ++i) mVels[i] = 0; SyncGridToSeq(); } if (button == mRandomizeAllButton) { RandomizePitches(GetKeyModifiers() & kModifier_Shift); RandomizeVelocities(); RandomizeLengths(); SyncGridToSeq(); } if (button == mRandomizePitchButton) { RandomizePitches(GetKeyModifiers() & kModifier_Shift); SyncGridToSeq(); } if (button == mRandomizeVelocityButton) { RandomizeVelocities(); SyncGridToSeq(); } if (button == mRandomizeLengthButton) { RandomizeLengths(); SyncGridToSeq(); } } void NoteStepSequencer::RandomizePitches(bool fifths) { if (fifths) { for (int i = 0; i < mLength; ++i) { if (ofRandom(1) <= mRandomizePitchChance) { switch (gRandom() % 5) { default: case 0: mTones[i] = 0; break; case 1: mTones[i] = 4; break; case 2: mTones[i] = 7; break; case 3: mTones[i] = 11; break; case 4: mTones[i] = 14; break; } } } } else { //reduce overall randomness: choose from a limited pool of pitches std::vector<int> newTones; for (int i = 0; i < mRandomizePitchVariety; ++i) newTones.push_back(ofClamp(int(ofRandom(0, mNoteRange) + .5f), 0, mNoteRange - 1)); for (int i = 0; i < mLength; ++i) { if (ofRandom(1) <= mRandomizePitchChance) mTones[i] = newTones[gRandom() % newTones.size()]; } } } void NoteStepSequencer::RandomizeVelocities() { for (int i = 0; i < mLength; ++i) { if (ofRandom(1) <= mRandomizeVelocityChance) { int newVelocity = 0; if (ofRandom(1) < mRandomizeVelocityDensity) { switch (gRandom() % 4) { case 0: newVelocity = 50; break; case 1: newVelocity = 80; break; case 2: newVelocity = 110; break; default: newVelocity = 127; break; } } mVels[i] = newVelocity; } } } void NoteStepSequencer::RandomizeLengths() { for (int i = 0; i < mLength; ++i) { if (ofRandom(1) <= mRandomizeLengthChance) { float newLength = ofClamp(ofRandom(2), FLT_EPSILON, 1); mNoteLengths[i] = ofLerp(mNoteLengths[i], newLength, mRandomizeLengthRange); } } } void NoteStepSequencer::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mIntervalSelector) { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) transportListenerInfo->mInterval = mInterval; } if (list == mNoteModeSelector) { if (mNoteMode != oldVal) mRowOffset = 0; SetUpStepControls(); } for (int i = 0; i < NSS_MAX_STEPS; ++i) { if (list == mToneDropdowns[i]) SyncGridToSeq(); } } void NoteStepSequencer::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { for (int i = 0; i < NSS_MAX_STEPS; ++i) { if (slider == mLengthSliders[i]) SyncGridToSeq(); } } void NoteStepSequencer::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mLoopResetPointSlider || slider == mLengthSlider) mLoopResetPoint = MIN(mLoopResetPoint, mLength - 1); if (slider == mLengthSlider) { mLength = MIN(mLength, NSS_MAX_STEPS); if (mLength > oldVal) { //slice the loop into the nearest power of 2 and loop new steps from there int oldLengthPow2 = std::max(1, MathUtils::HighestPow2(oldVal)); for (int i = oldVal; i < mLength; ++i) { int loopedFrom = i % oldLengthPow2; mTones[i] = mTones[loopedFrom]; mVels[i] = mVels[loopedFrom]; mNoteLengths[i] = mNoteLengths[loopedFrom]; } } mGrid->SetGrid(mLength, mNoteRange); mVelocityGrid->SetGrid(mLength, 1); mLoopResetPointSlider->SetExtents(0, mLength); SyncGridToSeq(); } if (slider == mOctaveSlider) SetUpStepControls(); for (int i = 0; i < NSS_MAX_STEPS; ++i) { if (slider == mVelocitySliders[i]) SyncGridToSeq(); } if (slider == mGridControlOffsetXSlider || slider == mGridControlOffsetYSlider) UpdateGridControllerLights(false); } void NoteStepSequencer::SyncGridToSeq() { mGrid->Clear(); for (int i = 0; i < NSS_MAX_STEPS; ++i) { if (mTones[i] < 0) continue; mGrid->SetVal(i, mTones[i], mVels[i] > 0 ? mNoteLengths[i] : 0, false); mVelocityGrid->SetVal(i, 0, mVels[i] / 127.0f, false); } mGrid->SetGrid(mLength, mNoteRange); mVelocityGrid->SetGrid(mLength, 1); if (mGridControlTarget->GetGridController()) { int maxXOffset = mLength - mGridControlTarget->GetGridController()->NumCols(); if (maxXOffset >= 0) mGridControlOffsetXSlider->SetExtents(0, maxXOffset); int maxYOffset = mNoteRange - mGridControlTarget->GetGridController()->NumRows(); if (maxYOffset >= 0) mGridControlOffsetYSlider->SetExtents(0, maxYOffset); mGridControlOffsetX = MAX(MIN(mGridControlOffsetX, maxXOffset), 0); mGridControlOffsetY = MAX(MIN(mGridControlOffsetY, maxYOffset), 0); } } void NoteStepSequencer::OnScaleChanged() { SetUpStepControls(); } void NoteStepSequencer::SetUpStepControls() { if (TheSynth->IsLoadingModule()) return; for (int i = 0; i < NSS_MAX_STEPS; ++i) { mToneDropdowns[i]->Clear(); for (int j = mNoteRange - 1; j >= 0; --j) mToneDropdowns[i]->AddLabel(NoteName(RowToPitch(j), false, true), j); } } void NoteStepSequencer::SaveLayout(ofxJSONElement& moduleInfo) { } void NoteStepSequencer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadString("controller", moduleInfo, "", FillDropdown<MidiController*>); mModuleSaveData.LoadInt("gridrows", moduleInfo, 15, 1, 127, K(isTextField)); mModuleSaveData.LoadInt("gridsteps", moduleInfo, 8, 1, NSS_MAX_STEPS, K(isTextField)); mModuleSaveData.LoadBool("stepcontrols", moduleInfo, false); mModuleSaveData.LoadInt("steplengthsubdivisions", moduleInfo, 2, 1, 8, K(isTextField)); SetUpFromSaveData(); } void NoteStepSequencer::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); SetMidiController(mModuleSaveData.GetString("controller")); mNoteRange = mModuleSaveData.GetInt("gridrows"); mShowStepControls = mModuleSaveData.GetBool("stepcontrols"); mStepLengthSubdivisions = mModuleSaveData.GetInt("steplengthsubdivisions"); UpdateVelocityGridPos(); SyncGridToSeq(); SetUpStepControls(); mGrid->SetClickValueSubdivisions(mStepLengthSubdivisions); } void NoteStepSequencer::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); mGrid->SaveState(out); mVelocityGrid->SaveState(out); out << mHasExternalPulseSource; float width, height; GetModuleDimensions(width, height); out << width; out << height; } void NoteStepSequencer::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); mGrid->LoadState(in); mVelocityGrid->LoadState(in); GridUpdated(mGrid, 0, 0, 0, 0); GridUpdated(mVelocityGrid, 0, 0, 0, 0); if (rev >= 2) in >> mHasExternalPulseSource; if (rev >= 3) { float width, height; in >> width; in >> height; Resize(width, height); } } ```
/content/code_sandbox/Source/NoteStepSequencer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
13,130
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== ModulatorMult.h Created: 29 Nov 2017 8:56:31pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "Slider.h" #include "IModulator.h" class PatchCableSource; class ModulatorMult : public IDrawableModule, public IFloatSliderListener, public IModulator { public: ModulatorMult(); virtual ~ModulatorMult(); static IDrawableModule* Create() { return new ModulatorMult(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; //IModulator float Value(int samplesIn = 0) override; bool Active() const override { return mEnabled; } bool CanAdjustRange() const override { return false; } FloatSlider* GetTarget() { return GetSliderTarget(); } //IFloatSliderListener void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} void SaveLayout(ofxJSONElement& moduleInfo) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override { w = 106; h = 17 * 2 + 4; } float mValue1{ 0 }; float mValue2{ 0 }; FloatSlider* mValue1Slider{ nullptr }; FloatSlider* mValue2Slider{ nullptr }; }; ```
/content/code_sandbox/Source/ModulatorMult.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
527
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // ModWheel.cpp // Bespoke // // Created by Ryan Challinor on 1/4/16. // // #include "ModWheel.h" #include "OpenFrameworksPort.h" #include "ModularSynth.h" ModWheel::ModWheel() { } void ModWheel::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } ModWheel::~ModWheel() { TheTransport->RemoveAudioPoller(this); } void ModWheel::CreateUIControls() { IDrawableModule::CreateUIControls(); mModWheelSlider = new FloatSlider(this, "modwheel", 5, 2, 110, 15, &mModWheel, 0, 1); } void ModWheel::DrawModule() { if (Minimized() || IsVisible() == false) return; mModWheelSlider->Draw(); } void ModWheel::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled) { mModulation.GetModWheel(voiceIdx)->AppendTo(modulation.modWheel); modulation.modWheel = mModulation.GetModWheel(voiceIdx); } PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void ModWheel::OnTransportAdvanced(float amount) { ComputeSliders(0); } void ModWheel::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mModWheelSlider) mModulation.GetModWheel(-1)->SetValue(mModWheel); } void ModWheel::CheckboxUpdated(Checkbox* checkbox, double time) { } void ModWheel::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void ModWheel::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/ModWheel.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
515
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // StutterControl.h // Bespoke // // Created by Ryan Challinor on 2/25/15. // // #pragma once #include <iostream> #include "IDrawableModule.h" #include "OpenFrameworksPort.h" #include "Checkbox.h" #include "Stutter.h" #include "Slider.h" #include "IAudioProcessor.h" #include "GridController.h" #include "INoteReceiver.h" #include "Push2Control.h" class StutterControl : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public IGridControllerListener, public INoteReceiver, public IPush2GridController { public: StutterControl(); ~StutterControl(); static IDrawableModule* Create() { return new StutterControl(); } static bool AcceptsAudio() { return true; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Init() override; //IAudioSource void Process(double time) override; //IGridControllerListener void OnControllerPageSelected() override; void OnGridButton(int x, int y, float velocity, IGridController* grid) override; //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) override; void SendCC(int control, int value, int voiceIdx) override {} //IPush2GridController bool OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue) override; void UpdatePush2Leds(Push2Control* push2) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return true; } private: enum StutterType { kHalf, kQuarter, k8th, k16th, k32nd, k64th, kReverse, kRampIn, kRampOut, kTumbleUp, kTumbleDown, kHalfSpeed, kDoubleSpeed, kDotted8th, kQuarterTriplets, kFree, kNumStutterTypes }; StutterType GetStutterFromKey(int key); void SendStutter(double time, StutterParams stutter, bool on); StutterParams GetStutter(StutterType type); //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; void UpdateGridLights(); Stutter mStutterProcessor; Checkbox* mStutterCheckboxes[StutterType::kNumStutterTypes]{ nullptr }; bool mStutter[StutterType::kNumStutterTypes]{}; FloatSlider* mFreeLengthSlider{ nullptr }; FloatSlider* mFreeSpeedSlider{ nullptr }; GridControlTarget* mGridControlTarget{ nullptr }; }; ```
/content/code_sandbox/Source/StutterControl.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
795
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // VelocityScaler.h // Bespoke // // Created by Ryan Challinor on 5/6/16. // // #pragma once #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "INoteSource.h" #include "Slider.h" class VelocityScaler : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener { public: VelocityScaler(); static IDrawableModule* Create() { return new VelocityScaler(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = 108; height = 22; } float mScale{ 1 }; FloatSlider* mScaleSlider{ nullptr }; }; ```
/content/code_sandbox/Source/VelocityScaler.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
420
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== MultitapDelay.cpp Created: 25 Nov 2018 11:16:38am Author: Ryan Challinor ============================================================================== */ #include "MultitapDelay.h" #include "Sample.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Profiler.h" #include "ModulationChain.h" const float mBufferX = 5; const float mBufferY = 50; const float mBufferW = 800; const float mBufferH = 200; MultitapDelay::MultitapDelay() : IAudioProcessor(gBufferSize) , mWriteBuffer(gBufferSize) , mDelayBuffer(5 * gSampleRate) { mTaps.resize(mNumTaps); for (int i = 0; i < mNumTaps; ++i) mTaps[i].mOwner = this; for (int i = 0; i < kNumMPETaps; ++i) mMPETaps[i].mOwner = this; } void MultitapDelay::CreateUIControls() { IDrawableModule::CreateUIControls(); mDryAmountSlider = new FloatSlider(this, "dry", 5, 10, 150, 15, &mDryAmount, 0, 1); mDisplayLengthSlider = new FloatSlider(this, "display length", mDryAmountSlider, kAnchor_Below, 150, 15, &mDisplayLength, .1f, mDelayBuffer.Size() / gSampleRate); mDisplayLength = mDisplayLengthSlider->GetMax(); for (int i = 0; i < mNumTaps; ++i) { float y = mBufferY + mBufferH + 10 + i * 100; mTaps[i].mDelayMsSlider = new FloatSlider(this, ("delay " + ofToString(i + 1)).c_str(), 10, y, 150, 15, &mTaps[i].mDelayMs, gBufferSize / gSampleRateMs, mDelayBuffer.Size() / gSampleRateMs); mTaps[i].mGainSlider = new FloatSlider(this, ("gain " + ofToString(i + 1)).c_str(), mTaps[i].mDelayMsSlider, kAnchor_Below, 150, 15, &mTaps[i].mGain, 0, 1); mTaps[i].mFeedbackSlider = new FloatSlider(this, ("feedback " + ofToString(i + 1)).c_str(), mTaps[i].mGainSlider, kAnchor_Below, 150, 15, &mTaps[i].mFeedback, 0, 1); mTaps[i].mPanSlider = new FloatSlider(this, ("pan " + ofToString(i + 1)).c_str(), mTaps[i].mFeedbackSlider, kAnchor_Below, 150, 15, &mTaps[i].mPan, -1, 1); } } MultitapDelay::~MultitapDelay() { } void MultitapDelay::Process(double time) { PROFILER(MultitapDelay); IAudioReceiver* target = GetTarget(); if (target == nullptr) return; SyncBuffers(); if (!mEnabled) { for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { Add(target->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize()); GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize(), ch); } GetBuffer()->Reset(); return; } mWriteBuffer.SetNumActiveChannels(GetBuffer()->NumActiveChannels()); mDelayBuffer.SetNumChannels(GetBuffer()->NumActiveChannels()); for (int t = 0; t < mNumTaps; ++t) mTaps[t].mTapBuffer.SetNumActiveChannels(mWriteBuffer.NumActiveChannels()); int bufferSize = target->GetBuffer()->BufferSize(); assert(bufferSize == gBufferSize); mWriteBuffer.Clear(); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { BufferCopy(mWriteBuffer.GetChannel(ch), GetBuffer()->GetChannel(ch), bufferSize); Mult(mWriteBuffer.GetChannel(ch), mDryAmount, bufferSize); mDelayBuffer.WriteChunk(GetBuffer()->GetChannel(ch), bufferSize, ch); } for (int i = 0; i < bufferSize; ++i) { ComputeSliders(i); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { for (int t = 0; t < mNumTaps; ++t) mTaps[t].Process(&mWriteBuffer.GetChannel(ch)[i], i, ch); for (int t = 0; t < kNumMPETaps; ++t) mMPETaps[t].Process(&mWriteBuffer.GetChannel(ch)[i], i, ch); } } for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { Add(target->GetBuffer()->GetChannel(ch), mWriteBuffer.GetChannel(ch), bufferSize); GetVizBuffer()->WriteChunk(mWriteBuffer.GetChannel(ch), bufferSize, ch); } GetBuffer()->Reset(); } void MultitapDelay::DrawModule() { if (Minimized() || IsVisible() == false) return; mDryAmountSlider->Draw(); mDisplayLengthSlider->Draw(); for (int i = 0; i < mNumTaps; ++i) { mTaps[i].mDelayMsSlider->Draw(); mTaps[i].mGainSlider->Draw(); mTaps[i].mFeedbackSlider->Draw(); mTaps[i].mPanSlider->Draw(); } for (int ch = 0; ch < mDelayBuffer.NumChannels(); ++ch) mDelayBuffer.Draw(mBufferX, mBufferY + mBufferH / mDelayBuffer.NumChannels() * ch, mBufferW, mBufferH / mDelayBuffer.NumChannels(), mDisplayLength * gSampleRate, ch); ofPushMatrix(); ofTranslate(mBufferX, mBufferY); for (int i = 0; i < kNumMPETaps; ++i) mMPETaps[i].Draw(mBufferW, mBufferH); for (int i = 0; i < mNumTaps; ++i) mTaps[i].Draw(mBufferW, mBufferH); ofPopMatrix(); } void MultitapDelay::DropdownClicked(DropdownList* list) { } void MultitapDelay::DropdownUpdated(DropdownList* list, int oldVal, double time) { } void MultitapDelay::ButtonClicked(ClickButton* button, double time) { } void MultitapDelay::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); } void MultitapDelay::MouseReleased() { IDrawableModule::MouseReleased(); } bool MultitapDelay::MouseMoved(float x, float y) { return IDrawableModule::MouseMoved(x, y); } void MultitapDelay::CheckboxUpdated(Checkbox* checkbox, double time) { } void MultitapDelay::GetModuleDimensions(float& width, float& height) { width = mBufferW + 10; height = mBufferY + mBufferH + 10 + 100 * mNumTaps; } void MultitapDelay::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void MultitapDelay::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void MultitapDelay::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (voiceIdx == -1 || voiceIdx >= kNumMPETaps) return; /*if (velocity > 0) mMPETaps[voiceIdx].mADSR.Start(time, 1); else mMPETaps[voiceIdx].mADSR.Stop(time); mMPETaps[voiceIdx].mPitch = pitch; mMPETaps[voiceIdx].mPlay = 0; mMPETaps[voiceIdx].mPitchBend = modulation.pitchBend; mMPETaps[voiceIdx].mPressure = modulation.pressure; mMPETaps[voiceIdx].mModWheel = modulation.modWheel;*/ } void MultitapDelay::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void MultitapDelay::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); } void MultitapDelay::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); mDelayBuffer.SaveState(out); } void MultitapDelay::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); mDelayBuffer.LoadState(in); } void MultitapDelay::DelayMPETap::Process(float* sampleOut, int offset, int ch) { /*if (!mADSR.IsDone(gTime) && sampleLength > 0) { double time = gTime; for (int i=0; i<outLength; ++i) { float pitchBend = mPitchBend ? mPitchBend->GetValue(i) : ModulationParameters::kDefaultPitchBend; float pressure = mPressure ? mPressure->GetValue(i) : ModulationParameters::kDefaultPressure; float modwheel = mModWheel ? mModWheel->GetValue(i) : ModulationParameters::kDefaultModWheel; if (pressure > 0) { mGranulator.mGrainOverlap = ofMap(pressure * pressure, 0, 1, 3, MAX_GRAINS); mGranulator.mPosRandomizeMs = ofMap(pressure * pressure, 0, 1, 100, .03f); } mGranulator.mGrainLengthMs = ofMap(modwheel, -1, 1, 150-140, 150+140); float blend = .0005f; mGain = mGain * (1-blend) + pressure * blend; ChannelBuffer temp(sample, sampleLength); float outSample[1]; outSample[0] = 0; float pos = (mPitch + pitchBend + MIN(.125f, mPlay) - mOwner->mKeyboardBasePitch) / mOwner->mKeyboardNumPitches; mGranulator.Process(time, &temp, sampleLength, ofLerp(mOwner->mDisplayStartSamples, mOwner->mDisplayEndSamples, pos), outSample); outSample[0] *= sqrtf(mGain); outSample[0] *= mADSR.Value(time); out[i] += outSample[0]; time += gInvSampleRateMs; mPlay += .001f; } } else { mGranulator.ClearGrains(); }*/ } void MultitapDelay::DelayMPETap::Draw(float w, float h) { /*if (!mADSR.IsDone(gTime)) { if (mPitch - mOwner->mKeyboardBasePitch >= 0 && mPitch - mOwner->mKeyboardBasePitch < mOwner->mKeyboardNumPitches) { float pitchBend = mPitchBend ? mPitchBend->GetValue(0) : 0; float pressure = mPressure ? mPressure->GetValue(0) : 0; ofPushStyle(); ofFill(); float keyX = (mPitch - mOwner->mKeyboardBasePitch) / mOwner->mKeyboardNumPitches * w; float keyXTop = keyX + pitchBend * w / mOwner->mKeyboardNumPitches; ofBeginShape(); ofVertex(keyX, h); ofVertex(keyXTop, h - pressure * h); ofVertex(keyXTop +10, h - pressure * h); ofVertex(keyX+10, h); ofEndShape(); ofPopStyle(); } mGranulator.Draw(0, 0, w, h, mOwner->mDisplayStartSamples, mOwner->mDisplayEndSamples - mOwner->mDisplayStartSamples, mOwner->mSample->LengthInSamples()); }*/ } MultitapDelay::DelayTap::DelayTap() : mTapBuffer(gBufferSize) { } void MultitapDelay::DelayTap::Process(float* sampleOut, int offset, int ch) { if (mGain > 0) { float delaySamps = mDelayMs / gInvSampleRateMs; delaySamps = ofClamp(delaySamps - offset, 0.1f, mOwner->mDelayBuffer.Size() - 2); int sampsAgoA = int(delaySamps); int sampsAgoB = sampsAgoA + 1; float sample = mOwner->mDelayBuffer.GetSample(sampsAgoA, ch); float nextSample = mOwner->mDelayBuffer.GetSample(sampsAgoB, ch); float a = delaySamps - sampsAgoA; float delayedSample = (1 - a) * sample + a * nextSample; //interpolate float outputSample = delayedSample * mGain; mTapBuffer.GetChannel(ch)[offset] = outputSample; *sampleOut += outputSample; float panGain = ch == 0 ? GetLeftPanGain(mPan) : GetRightPanGain(mPan); mOwner->mDelayBuffer.Accum(gBufferSize - offset, outputSample * mFeedback * panGain, ch); } } void MultitapDelay::DelayTap::Draw(float w, float h) { ofPushStyle(); ofFill(); float x = ofClamp(1 - (mDelayMs * gSampleRateMs) / (mOwner->mDisplayLength * gSampleRate), 0, 1) * w; float y = h - mGain * h; ofLine(x, y, x, h); ofRect(x - 5, y - 5, 10, 10); ofPopStyle(); } ```
/content/code_sandbox/Source/MultitapDelay.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
3,314
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // ModulationChain.h // Bespoke // // Created by Ryan Challinor on 12/26/15. // // #pragma once #include "Ramp.h" #include "LFO.h" class ModulationChain { public: ModulationChain(float initialValue); float GetValue(int samplesIn) const; float GetIndividualValue(int samplesIn) const; void SetValue(float value); void RampValue(double time, float from, float to, double length); void SetLFO(NoteInterval interval, float amount); void AppendTo(ModulationChain* chain); void SetSidechain(ModulationChain* chain); void MultiplyIn(ModulationChain* chain); void CreateBuffer(); void FillBuffer(float* buffer); float GetBufferValue(int sampleIdx); private: Ramp mRamp; LFO mLFO; float mLFOAmount{ 0 }; float* mBuffer{ nullptr }; ModulationChain* mPrev{ nullptr }; ModulationChain* mSidechain{ nullptr }; ModulationChain* mMultiplyIn{ nullptr }; }; struct ModulationParameters { ModulationParameters() {} ModulationParameters(ModulationChain* _pitchBend, ModulationChain* _modWheel, ModulationChain* _pressure, float _pan) : pitchBend(_pitchBend) , modWheel(_modWheel) , pressure(_pressure) , pan(_pan) {} ModulationChain* pitchBend{ nullptr }; ModulationChain* modWheel{ nullptr }; ModulationChain* pressure{ nullptr }; float pan{ 0 }; static constexpr float kDefaultPitchBend{ 0 }; static constexpr float kDefaultModWheel{ .5f }; static constexpr float kDefaultPressure{ .5f }; }; struct ModulationCollection { ModulationChain mPitchBend{ ModulationParameters::kDefaultPitchBend }; ModulationChain mModWheel{ ModulationParameters::kDefaultModWheel }; ModulationChain mPressure{ ModulationParameters::kDefaultPressure }; }; class Modulations { public: Modulations(bool isGlobalEffect); //isGlobalEffect: is the effect that we're using this on a global effect that affects all voices (pitch bend all voices that come through here the same way) or a voice effect (affect individual voices that come through here individually)? ModulationChain* GetPitchBend(int voiceIdx); ModulationChain* GetModWheel(int voiceIdx); ModulationChain* GetPressure(int voiceIdx); private: ModulationCollection mGlobalModulation; std::vector<ModulationCollection> mVoiceModulations; }; ```
/content/code_sandbox/Source/ModulationChain.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
666
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // PitchToValue.cpp // Bespoke // // Created by Andrius Merkys on 12/20/23. // // #include "PitchToValue.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "ModulationChain.h" PitchToValue::PitchToValue() : mValue(0) { } PitchToValue::~PitchToValue() { } void PitchToValue::CreateUIControls() { IDrawableModule::CreateUIControls(); mTargetCable = new PatchCableSource(this, kConnectionType_Modulator); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); } void PitchToValue::DrawModule() { if (Minimized() || IsVisible() == false) return; } void PitchToValue::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { OnModulatorRepatch(); } void PitchToValue::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled && velocity > 0) { mValue = pitch; } } float PitchToValue::Value(int samplesIn) { return mValue; } void PitchToValue::SaveLayout(ofxJSONElement& moduleInfo) { } void PitchToValue::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void PitchToValue::SetUpFromSaveData() { } ```
/content/code_sandbox/Source/PitchToValue.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
433
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== GainStage.h Created: 24 Apr 2021 3:47:25pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IAudioEffect.h" #include "Slider.h" #include "Checkbox.h" class GainStageEffect : public IAudioEffect, public IFloatSliderListener { public: GainStageEffect(); static IAudioEffect* Create() { return new GainStageEffect(); } void CreateUIControls() override; //IAudioEffect void ProcessAudio(double time, ChannelBuffer* buffer) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } std::string GetType() override { return "gainstage"; } void CheckboxUpdated(Checkbox* checkbox, double time) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = 120; height = 20; } float mGain{ 1 }; FloatSlider* mGainSlider{ nullptr }; }; ```
/content/code_sandbox/Source/GainStageEffect.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
364
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== VelocityToChance.h Created: 29 Jan 2020 9:17:02pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "NoteEffectBase.h" #include "Slider.h" #include "ClickButton.h" #include "TextEntry.h" class VelocityToChance : public NoteEffectBase, public IFloatSliderListener, public IIntSliderListener, public IDrawableModule, public IButtonListener, public ITextEntryListener { public: VelocityToChance(); virtual ~VelocityToChance(); static IDrawableModule* Create() { return new VelocityToChance(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override {} void CheckboxUpdated(Checkbox* checkbox, double time) override {} void TextEntryComplete(TextEntry* entry) override {} void ButtonClicked(ClickButton* button, double time) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; void Reseed(); bool mFullVelocity{ true }; Checkbox* mFullVelocityCheckbox{ nullptr }; float mLastRejectTime{ 0 }; float mLastAcceptTime{ 0 }; bool mDeterministic{ false }; int mLength{ 4 }; IntSlider* mLengthSlider{ nullptr }; int mSeed{ 0 }; TextEntry* mSeedEntry{ nullptr }; ClickButton* mReseedButton{ nullptr }; ClickButton* mPrevSeedButton{ nullptr }; ClickButton* mNextSeedButton{ nullptr }; }; ```
/content/code_sandbox/Source/VelocityToChance.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
599
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== VelocityToChance.cpp Created: 29 Jan 2020 9:17:02pm Author: Ryan Challinor ============================================================================== */ #include "VelocityToChance.h" #include "SynthGlobals.h" #include "UIControlMacros.h" VelocityToChance::VelocityToChance() { Reseed(); } VelocityToChance::~VelocityToChance() { } void VelocityToChance::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); CHECKBOX(mFullVelocityCheckbox, "full velocity", &mFullVelocity); UIBLOCK_SHIFTY(5); INTSLIDER(mLengthSlider, "beat length", &mLength, 1, 16); TEXTENTRY_NUM(mSeedEntry, "seed", 4, &mSeed, 0, 9999); UIBLOCK_SHIFTRIGHT(); BUTTON(mPrevSeedButton, "<"); UIBLOCK_SHIFTRIGHT(); BUTTON(mReseedButton, "*"); UIBLOCK_SHIFTRIGHT(); BUTTON(mNextSeedButton, ">"); ENDUIBLOCK0(); mSeedEntry->DrawLabel(true); mPrevSeedButton->PositionTo(mSeedEntry, kAnchor_Right); mReseedButton->PositionTo(mPrevSeedButton, kAnchor_Right); mNextSeedButton->PositionTo(mReseedButton, kAnchor_Right); } void VelocityToChance::DrawModule() { if (Minimized() || IsVisible() == false) return; mFullVelocityCheckbox->Draw(); if (gTime - mLastAcceptTime > 0 && gTime - mLastAcceptTime < 200) { ofPushStyle(); ofSetColor(0, 255, 0, 255 * (1 - (gTime - mLastAcceptTime) / 200)); ofFill(); ofRect(106, 2, 10, 7); ofPopStyle(); } if (gTime - mLastRejectTime > 0 && gTime - mLastRejectTime < 200) { ofPushStyle(); ofSetColor(255, 0, 0, 255 * (1 - (gTime - mLastRejectTime) / 200)); ofFill(); ofRect(106, 9, 10, 7); ofPopStyle(); } mLengthSlider->SetShowing(mDeterministic); mLengthSlider->Draw(); mSeedEntry->SetShowing(mDeterministic); mSeedEntry->Draw(); mPrevSeedButton->SetShowing(mDeterministic); mPrevSeedButton->Draw(); mReseedButton->SetShowing(mDeterministic); mReseedButton->Draw(); mNextSeedButton->SetShowing(mDeterministic); mNextSeedButton->Draw(); if (mDeterministic) { ofRectangle lengthRect = mLengthSlider->GetRect(true); ofPushStyle(); ofSetColor(0, 255, 0); ofFill(); float pos = fmod(TheTransport->GetMeasureTime(gTime) * TheTransport->GetTimeSigTop() / mLength, 1); const float kPipSize = 3; float moduleWidth, moduleHeight; GetModuleDimensions(moduleWidth, moduleHeight); ofRect(ofMap(pos, 0, 1, 0, moduleWidth - kPipSize), lengthRect.y - 5, kPipSize, kPipSize); ofPopStyle(); } } void VelocityToChance::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (!mEnabled) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); return; } float random; if (mDeterministic) { const int kStepResolution = 128; uint64_t step = int(TheTransport->GetMeasureTime(time) * kStepResolution); int randomIndex = step % ((mLength * kStepResolution) / TheTransport->GetTimeSigTop()); random = ((abs(DeterministicRandom(mSeed + pitch * 13, randomIndex)) % 10000) / 10000.0f); } else { random = ofRandom(1); } bool accept = (random <= velocity / 127.0f); if (accept) PlayNoteOutput(time, pitch, mFullVelocity ? 127 : velocity, voiceIdx, modulation); if (velocity > 0) { if (accept) mLastAcceptTime = time; else mLastRejectTime = time; } else { PlayNoteOutput(time, pitch, 0, voiceIdx, modulation); } } void VelocityToChance::Reseed() { mSeed = gRandom() % 10000; } void VelocityToChance::ButtonClicked(ClickButton* button, double time) { if (button == mPrevSeedButton) mSeed = (mSeed - 1 + 10000) % 10000; if (button == mReseedButton) Reseed(); if (button == mNextSeedButton) mSeed = (mSeed + 1) % 10000; } void VelocityToChance::GetModuleDimensions(float& width, float& height) { width = 118; height = mDeterministic ? 60 : 20; } void VelocityToChance::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadBool("deterministic", moduleInfo, false); SetUpFromSaveData(); } void VelocityToChance::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); mDeterministic = mModuleSaveData.GetBool("deterministic"); } ```
/content/code_sandbox/Source/VelocityToChance.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,370
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // LaunchpadInterpreter.cpp // modularSynth // // Created by Ryan Challinor on 11/24/12. // // #include "LaunchpadInterpreter.h" #include "MidiController.h" LaunchpadInterpreter::LaunchpadInterpreter(ILaunchpadListener* listener) : mListener(listener) { } void LaunchpadInterpreter::SetController(MidiController* controller, int page) { mController = controller; mControllerPage = page; } void LaunchpadInterpreter::OnMidiNote(MidiNote& note) { int x = note.mPitch % 16; int y = 7 - note.mPitch / 16; if (x == 8) x = -1; if (IsMonome()) { x = note.mPitch % 8; y = 7 - note.mPitch / 8; } mListener->OnButtonPress(x, y, note.mVelocity > 0); } void LaunchpadInterpreter::OnMidiControl(MidiControl& control) { if (control.mControl >= 104 && control.mControl <= 111) { mListener->OnButtonPress(control.mControl - 104, -1, control.mValue > 0); } } bool LaunchpadInterpreter::IsMonome() const { if (mController == nullptr) return false; return strcmp(mController->Name(), "monome") == 0; } void LaunchpadInterpreter::UpdateLights(std::vector<LightUpdate> lightUpdates, bool force /*=false*/) { if (mController == nullptr) return; for (int i = 0; i < lightUpdates.size(); ++i) { int x = lightUpdates[i].mX; int y = lightUpdates[i].mY; int color = LaunchpadColor(lightUpdates[i].mR, lightUpdates[i].mG); int lookup; if (x == -1 && y == -1) continue; else if (x >= 8 || y >= 8) continue; else if (x == -1) lookup = 64 + y; else if (y == -1) lookup = 64 + 8 + x; else lookup = x + y * 8; int val; if (IsMonome()) val = lightUpdates[i].mIntensity * 127; else val = color; if (mLights[lookup] != val || force) { if (IsMonome()) { if (x >= 0 && y >= 0) mController->SendNote(mControllerPage, x + (7 - y) * 8, val); } else { if (x == -1) mController->SendNote(mControllerPage, 8 + (7 - y) * 16, val); else if (y == -1) mController->SendData(mControllerPage, 176, x + 104, val); else mController->SendNote(mControllerPage, x + (7 - y) * 16, val); } mLights[lookup] = val; } } } void LaunchpadInterpreter::Draw(ofVec2f vPos) { } void LaunchpadInterpreter::ResetLaunchpad() { if (mController) mController->SendData(mControllerPage, 176, 0, 0); //reset code if (IsMonome()) { for (int i = 0; i < 64; ++i) mController->SendNote(mControllerPage, i, 0); } } int LaunchpadInterpreter::LaunchpadColor(int r, int g) { return r + (g << 4); } ```
/content/code_sandbox/Source/LaunchpadInterpreter.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
912
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== PulseGate.cpp Created: 22 Feb 2020 10:39:40pm Author: Ryan Challinor ============================================================================== */ #include "PulseGate.h" #include "SynthGlobals.h" #include "UIControlMacros.h" #include "Checkbox.h" PulseGate::PulseGate() { } PulseGate::~PulseGate() { } void PulseGate::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); CHECKBOX(mAllowCheckbox, "allow", &mAllow); ENDUIBLOCK(mWidth, mHeight); } void PulseGate::DrawModule() { if (Minimized() || IsVisible() == false) return; mAllowCheckbox->Draw(); } void PulseGate::OnPulse(double time, float velocity, int flags) { ComputeSliders(0); if (mAllow) DispatchPulse(GetPatchCableSource(), time, velocity, flags); } void PulseGate::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void PulseGate::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/PulseGate.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
369
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // NoiseEffect.cpp // modularSynth // // Created by Ryan Challinor on 4/16/13. // // #include "NoiseEffect.h" #include "SynthGlobals.h" #include "Profiler.h" NoiseEffect::NoiseEffect() { } void NoiseEffect::CreateUIControls() { IDrawableModule::CreateUIControls(); mAmountSlider = new FloatSlider(this, "amount", 5, 20, 110, 15, &mAmount, 0, 1); mWidthSlider = new IntSlider(this, "width", 5, 37, 110, 15, &mWidth, 1, 100); } void NoiseEffect::ProcessAudio(double time, ChannelBuffer* buffer) { PROFILER(NoiseEffect); if (!mEnabled) return; float bufferSize = buffer->BufferSize(); ComputeSliders(0); for (int i = 0; i < bufferSize; ++i) { if (mSampleCounter < mWidth - 1) { ++mSampleCounter; } else { mRandom = ofRandom(mAmount) + (1 - mAmount); mSampleCounter = 0; } for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) buffer->GetChannel(ch)[i] *= mRandom; } } void NoiseEffect::DrawModule() { mWidthSlider->Draw(); mAmountSlider->Draw(); } float NoiseEffect::GetEffectAmount() { if (!mEnabled) return 0; return mAmount; } void NoiseEffect::CheckboxUpdated(Checkbox* checkbox, double time) { } void NoiseEffect::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void NoiseEffect::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } ```
/content/code_sandbox/Source/NoiseEffect.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
504
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // Slider.cpp // modularSynth // // Created by Ryan Challinor on 12/4/12. // // #include "Slider.h" #include "IDrawableModule.h" #include "SynthGlobals.h" #include "FloatSliderLFOControl.h" #include "LFOController.h" #include "FileStream.h" #include "ModularSynth.h" #include "IModulator.h" #include "Push2Control.h" FloatSlider::FloatSlider(IFloatSliderListener* owner, const char* label, int x, int y, int w, int h, float* var, float min, float max, int digits /* = -1 */) : mVar(var) , mWidth(w) , mHeight(h) , mMin(min) , mMax(max) , mModulatorMin(min) , mModulatorMax(max) , mShowDigits(digits) , mOwner(owner) { assert(owner); SetName(label); SetPosition(x, y); (dynamic_cast<IDrawableModule*>(owner))->AddUIControl(this); SetParent(dynamic_cast<IClickable*>(owner)); mLastComputeCacheTime = new double[gBufferSize]; mLastComputeCacheValue = new float[gBufferSize]; } FloatSlider::FloatSlider(IFloatSliderListener* owner, const char* label, IUIControl* anchor, AnchorDirection anchorDir, int w, int h, float* var, float min, float max, int digits /* = -1 */) : FloatSlider(owner, label, -1, -1, w, h, var, min, max, digits) { PositionTo(anchor, anchorDir); } FloatSlider::~FloatSlider() { if (mIsSmoothing) TheTransport->RemoveAudioPoller(this); } void FloatSlider::Init() { if (mVar) mOriginalValue = *mVar; } FloatSliderLFOControl* FloatSlider::AcquireLFO() { if (mLFOControl == nullptr) { if (GetParent() != TheSynth->GetTopModalFocusItem()) //popups don't get these SetLFO(LFOPool::GetLFO(this)); } return mLFOControl; } void FloatSlider::SetLFO(FloatSliderLFOControl* lfo) { if (lfo != mLFOControl) { SetModulator(lfo); mLFOControl = lfo; } } void FloatSlider::SetModulator(IModulator* modulator) { if (modulator != mModulator) { IModulator* oldModulator = mModulator; mModulator = modulator; mLFOControl = nullptr; if (oldModulator != nullptr) oldModulator->OnRemovedFrom(this); } } void FloatSlider::Poll() { if (mLastComputeTime + .1f < gTime) Compute(); } void FloatSlider::Render() { float normalWidth = mWidth; float normalHeight = mHeight; if (Push2Control::sDrawingPush2Display) { mWidth = 100; mHeight = 15; } mLastDisplayedValue = *mVar; ofPushStyle(); ofColor color; ofColor textColor; IUIControl::GetColors(color, textColor); ofFill(); ofSetColor(0, 0, 0, gModuleDrawAlpha * .5f); ofRect(mX + 1, mY + 1, mWidth, mHeight); ofSetColor(color); ofRect(mX, mY, mWidth, mHeight); ofNoFill(); bool showSmoothAdjustmentUI = AdjustSmooth() && (gHoveredUIControl == this || mSmooth > 0); if (mIsSmoothing && !showSmoothAdjustmentUI) { ofPushStyle(); ofSetColor(255, 255, 0, gModuleDrawAlpha); float val = ofClamp(mSmoothTarget, mMin, mMax); float screenPos = mX + 1 + (mWidth - 2) * ValToPos(val, false); ofSetLineWidth(1); ofFill(); ofCircle(screenPos, mY + mHeight / 2, 3); ofPopStyle(); } float screenPos; if (mModulator && mModulator->Active() && !showSmoothAdjustmentUI) { screenPos = mX + 1 + (mWidth - 2) * ValToPos(*mVar, true); float lfomax = ofClamp(mModulator->GetMax(), mMin, mMax); float screenPosMax = mX + 1 + (mWidth - 2) * ValToPos(lfomax, true); float lfomin = ofClamp(mModulator->GetMin(), mMin, mMax); float screenPosMin = mX + 1 + (mWidth - 2) * ValToPos(lfomin, true); ofPushStyle(); ofSetColor(0, 200, 0, gModuleDrawAlpha * .5f); ofFill(); ofRect(screenPosMin, mY, screenPos - screenPosMin, mHeight, 1); //lfo bar ofPopStyle(); ofPushStyle(); ofSetColor(0, 255, 0, gModuleDrawAlpha); ofSetLineWidth(2); ofLine(screenPosMin, mY + 1, screenPosMin, mY + mHeight - 1); //min bar ofLine(screenPosMax, mY + 1, screenPosMax, mY + mHeight - 1); //max bar ofPopStyle(); } else { ofPushStyle(); if (*mVar >= mMin && *mVar <= mMax) ofSetColor(255, 0, 0, gModuleDrawAlpha); else ofSetColor(30, 30, 30, gModuleDrawAlpha); if (showSmoothAdjustmentUI) ofSetColor(255, 255, 0, gModuleDrawAlpha); float val = ofClamp(*mVar, mMin, mMax); screenPos = mX + 1 + (mWidth - 2) * ValToPos(val, false); ofSetLineWidth(2); ofLine(screenPos, mY + 1, screenPos, mY + mHeight - 1); //value bar ofPopStyle(); } DrawBeacon(screenPos, mY + mHeight / 2); DrawHover(mX, mY, mWidth, mHeight); std::string display; float textSize = 13; if (showSmoothAdjustmentUI) { display = "smooth: " + ofToString(mSmooth, 3); textSize = 9; } else { if (mShowName) display = GetDisplayName(); if (display.length() > 0) //only show a colon if there's a label display += ":"; if (mFloatEntry) { ofSetColor(255, 255, 100); display += mFloatEntry->GetText(); } else { display += GetDisplayValue(*mVar); } } if (mMaxEntry || mMinEntry) display = ""; ofSetColor(textColor); DrawTextNormal(display, mX + 2, mY + 5 + mHeight / 2, textSize); ofPopStyle(); if (mMaxEntry) { ofPushStyle(); ofFill(); ofSetColor(120, 120, 120, 255); ofRectangle rect = mMaxEntry->GetRect(K(local)); ofRect(rect.x - 28, rect.y, rect.width + 28, rect.height); mMaxEntry->Draw(); ofSetColor(255, 255, 255); DrawTextRightJustify("max:", rect.x, rect.y + 5 + mHeight / 2); ofPopStyle(); } if (mMinEntry) { ofPushStyle(); ofFill(); ofSetColor(120, 120, 120, 255); ofRectangle rect = mMinEntry->GetRect(K(local)); ofRect(rect.x - 28, rect.y, rect.width + 28, rect.height); mMinEntry->Draw(); ofSetColor(255, 255, 255); DrawTextRightJustify("min:", rect.x, rect.y + 5 + mHeight / 2); ofPopStyle(); } if (gHoveredUIControl == this && (GetKeyModifiers() & kModifier_Command) && mAllowMinMaxAdjustment && mMinEntry == nullptr && mMaxEntry == nullptr && !IUIControl::WasLastHoverSetManually()) { ofPushStyle(); ofFill(); ofSetColor(120, 120, 120, 255); ofRect(mX, mY, mWidth * .4f, mHeight); ofRect(mX + mWidth * .6f, mY, mWidth * .4f, mHeight); ofNoFill(); ofSetColor(255, 255, 255); ofRect(mX, mY, mWidth * .4f, mHeight); ofRect(mX + mWidth * .6f, mY, mWidth * .4f, mHeight); ofPushMatrix(); ofClipWindow(mX, mY, mWidth * .4f, mHeight, true); DrawTextNormal(ofToString(mMin), mX + 2, mY + 4 + mHeight / 2, 10); ofPopMatrix(); ofPushMatrix(); ofClipWindow(mX + mWidth * .6f, mY, mWidth * .4f, mHeight, true); DrawTextRightJustify(ofToString(mMax), mX + mWidth - 2, mY + 4 + mHeight / 2, 10); ofPopMatrix(); ofPopStyle(); } mWidth = normalWidth; mHeight = normalHeight; } void FloatSlider::DisplayLFOControl() { FloatSliderLFOControl* lfo = AcquireLFO(); if (lfo) { if (lfo->IsPinned()) return; float thisx, thisy; GetPosition(thisx, thisy); lfo->SetLFOEnabled(true); float w, h; lfo->GetDimensions(w, h); lfo->SetPosition(thisx, thisy + 15); lfo->SetOwningContainer(GetModuleParent()->GetOwningContainer()); TheSynth->PushModalFocusItem(lfo); if (TheLFOController) TheLFOController->SetSlider(this); } } void FloatSlider::OnClicked(float x, float y, bool right) { if (right) { DisplayLFOControl(); return; } if ((GetKeyModifiers() & kModifier_Command) && mAllowMinMaxAdjustment && !IUIControl::WasLastHoverSetManually()) { bool adjustMax; if (x > mWidth / 2) adjustMax = true; else adjustMax = false; if (adjustMax) { if (mMaxEntry != nullptr) mMaxEntry->Delete(); mMaxEntry = new TextEntry(this, "", mX + mWidth - 5 * 9, mY, 5, &mMax, -FLT_MAX, FLT_MAX); mMaxEntry->MakeActiveTextEntry(true); } else { if (mMinEntry != nullptr) mMinEntry->Delete(); //mMinEntry = new TextEntry(this, "", mX, mY, 5, &mMin, -FLT_MAX, FLT_MAX); mMinEntry = new TextEntry(this, "", mX + mWidth - 5 * 9, mY, 5, &mMin, -FLT_MAX, FLT_MAX); mMinEntry->MakeActiveTextEntry(true); } return; } mFineRefX = ofMap(ValToPos(*GetModifyValue(), false), 0.0f, 1.0f, mX + 1, mX + mWidth - 1, true) - mX; mRefY = y; SetValueForMouse(x, y); mMouseDown = true; mTouching = true; UpdateTouching(); } void FloatSlider::MouseReleased() { if (mMouseDown) mTouching = false; mMouseDown = false; mRefY = -999; if (mRelative && (mModulator == nullptr || mModulator->Active() == false)) SetValue(0, NextBufferTime(false)); } bool FloatSlider::MouseMoved(float x, float y) { CheckHover(x, y); if (mMouseDown) SetValueForMouse(x, y); return mMouseDown; } void FloatSlider::SetValueForMouse(float x, float y) { float* var = GetModifyValue(); float fX = x; if (GetKeyModifiers() & kModifier_Shift) { if (mFineRefX == -999) { mFineRefX = x; } float precision = mShowDigits != -1 ? 100 : 10; fX = mFineRefX + (fX - mFineRefX) / precision; } else { mFineRefX = -999; } float oldVal = *var; float pos = ofMap(fX + mX, mX + 1, mX + mWidth - 1, 0.0f, 1.0f); if (AdjustSmooth()) { mSmooth = PosToVal(pos, false); SmoothUpdated(); return; } *var = PosToVal(pos, false); if (mRelative && (mModulator == nullptr || mModulator->Active() == false)) { if (!mTouching || mRelativeOffset == -999) { mRelativeOffset = *var; *var = 0; } else { *var -= mRelativeOffset; } } *var = ofClamp(*var, mMin, mMax); if (oldVal != *var) { mOwner->FloatSliderUpdated(this, oldVal, NextBufferTime(false)); } if (mModulator && mModulator->Active() && mModulator->CanAdjustRange()) { float move = (y - mRefY) * -.003f; float change = move * (mMax - mMin); mModulator->GetMin() = ofClamp(mModulator->GetMin() + change, mMin, mModulator->GetMax()); mRefY = y; } } bool FloatSlider::AdjustSmooth() const { return (GetKeyModifiers() & kModifier_Alt) && mComputeHasBeenCalledOnce; //no smoothing if we're not calling Compute() } void FloatSlider::SmoothUpdated() { if (mSmooth > 0 && !mIsSmoothing) { TheTransport->AddAudioPoller(this); mSmoothTarget = *mVar; mRamp.SetValue(mSmoothTarget); mIsSmoothing = true; } else if (mSmooth <= 0 && mIsSmoothing) { TheTransport->RemoveAudioPoller(this); mIsSmoothing = false; } } void FloatSlider::SetFromMidiCC(float slider, double time, bool setViaModulator) { SetValue(GetValueForMidiCC(slider), time); } float FloatSlider::GetValueForMidiCC(float slider) const { slider = ofClamp(slider, 0, 1); return PosToVal(slider, true); } float FloatSlider::PosToVal(float pos, bool ignoreSmooth) const { if (AdjustSmooth() && !ignoreSmooth) { if (pos < 0) return 0; if (pos > 1) return 1; return pos * pos; } if (pos < 0) return mMin; if (pos > 1) return mMax; if (mMode == kNormal) return mMin + pos * (mMax - mMin); if (mMode == kLogarithmic) return mMin * powf(mMax / mMin, pos); if (mMode == kSquare) return mMin + pos * pos * (mMax - mMin); if (mMode == kBezier) { float y = pos * (pos * (pos * (mMax - mMin) + 3 * mMin - 3 * mBezierControl) - 3 * mMin + 3 * mBezierControl) + mMin; return y; } assert(false); return 0; } float FloatSlider::ValToPos(float val, bool ignoreSmooth) const { val = ofClamp(val, mMin, mMax); if (AdjustSmooth() && (gHoveredUIControl == this || mSmooth > 0) && !ignoreSmooth) return sqrtf(mSmooth); if (mMode == kNormal) return (val - mMin) / (mMax - mMin); if (mMode == kLogarithmic) return log(val / mMin) / log(mMax / mMin); if (mMode == kSquare) return sqrtf((val - mMin) / (mMax - mMin)); if (mMode == kBezier) { float closest = 0; float closestDist = FLT_MAX; for (float pos = 0; pos < 1; pos += .001f) { float dist = fabsf(PosToVal(pos, true) - val); if (dist < closestDist) { closestDist = dist; closest = pos; } } return closest; } return 0; } void FloatSlider::SetValue(float value, double time, bool forceUpdate /*= false*/) { if (TheLFOController && TheLFOController->WantsBinding(this)) { TheLFOController->SetSlider(this); return; } float* var = GetModifyValue(); float oldVal = *var; if (mRelative) { if (!mTouching || mRelativeOffset == -999) { mRelativeOffset = value; value = 0; } else { value -= mRelativeOffset; } } /*if (mClamped) *var = ofClamp(value,mMin,mMax); else*/ *var = value; DisableLFO(); if (oldVal != *var || forceUpdate) { mOwner->FloatSliderUpdated(this, oldVal, time); } } void FloatSlider::UpdateTouching() { if (mRelative && (mModulator == nullptr || mModulator->Active() == false)) { if (!mTouching) SetValue(0, NextBufferTime(false)); mRelativeOffset = -999; } } void FloatSlider::MatchExtents(FloatSlider* slider) { mMax = slider->mMax; mMin = slider->mMin; } void FloatSlider::DisableLFO() { if (mLFOControl) mLFOControl->SetEnabled(false); } float FloatSlider::GetValue() const { return *mVar; } float FloatSlider::GetMidiValue() const { if (mMin == mMax) return 0; return ValToPos(*mVar, true); } std::string FloatSlider::GetDisplayValue(float val) const { if (val == mMin && mMinValueDisplay != "") return mMinValueDisplay; if (val == mMax && mMaxValueDisplay != "") return mMaxValueDisplay; int decDigits = 3; if (mShowDigits != -1) decDigits = mShowDigits; else if (mMax - mMin > 1000) decDigits = 0; else if (mMax - mMin > 100) decDigits = 1; else if (mMax - mMin > 10) decDigits = 2; float displayVar = val; if (decDigits == 0) //round down if we're showing int value displayVar = (int)displayVar; return ofToString(displayVar, decDigits); } void FloatSlider::DoCompute(int samplesIn /*= 0*/) { if (mLastComputeTime == gTime && mLastComputeSamplesIn == samplesIn) return; //we've just calculated this, no need to do it again! earlying out avoids wasted work and circular modulation loops if (mLFOControl && mLFOControl->Active() && mLFOControl->InLowResMode() && samplesIn != 0) return; //only do the math on Compute(0) for low res mode mLastComputeTime = gTime; mLastComputeSamplesIn = samplesIn; float oldVal = *mVar; const bool kUseCache = true; if (kUseCache && IsAudioThread() && samplesIn >= 0 && samplesIn < gBufferSize && mLastComputeCacheTime[samplesIn] == gTime) { *mVar = mLastComputeCacheValue[samplesIn]; } else { if (mModulator && mModulator->Active()) { if (mIsSmoothing) mSmoothTarget = mModulator->Value(samplesIn); else *mVar = mModulator->Value(samplesIn); } if (mIsSmoothing) *mVar = mRamp.Value(gTime + samplesIn * gInvSampleRateMs); if (IsAudioThread() && samplesIn >= 0 && samplesIn < gBufferSize && mLastComputeCacheTime[samplesIn] != gTime) { mLastComputeCacheValue[samplesIn] = *mVar; mLastComputeCacheTime[samplesIn] = gTime; } } if (oldVal != *mVar) mOwner->FloatSliderUpdated(this, oldVal, gTime + samplesIn * gInvSampleRateMs); } float* FloatSlider::GetModifyValue() { if (!TheSynth->IsLoadingModule() && mModulator && mModulator->Active() && mModulator->CanAdjustRange()) return &mModulator->GetMax(); if (mIsSmoothing) return &mSmoothTarget; return mVar; } void FloatSlider::Double() { float doubl = *GetModifyValue() * 2.0f; if (doubl >= mMin && doubl <= mMax) SetValue(doubl, NextBufferTime(false)); } void FloatSlider::Halve() { float half = *GetModifyValue() * .5f; if (half >= mMin && half <= mMax) SetValue(half, NextBufferTime(false)); } void FloatSlider::Increment(float amount) { float val = *GetModifyValue() + amount; if (val >= mMin && val <= mMax) SetValue(val, NextBufferTime(false)); } void FloatSlider::ResetToOriginal() { SetValue(mOriginalValue, NextBufferTime(false)); } bool FloatSlider::CheckNeedsDraw() { if (IUIControl::CheckNeedsDraw()) return true; return *mVar != mLastDisplayedValue; } bool FloatSlider::AttemptTextInput() { if (mFloatEntry) mFloatEntry->Delete(); mFloatEntry = new TextEntry(this, "", HIDDEN_UICONTROL, HIDDEN_UICONTROL, 10, mEntryString); mFloatEntry->MakeActiveTextEntry(true); mFloatEntry->SetRequireEnter(true); mFloatEntry->ClearInput(); return true; } void FloatSlider::TextEntryComplete(TextEntry* entry) { if (entry == mFloatEntry) { mFloatEntry->Delete(); mFloatEntry = nullptr; float evaluated = 0; bool expressionValid = EvaluateExpression(mEntryString, *GetModifyValue(), evaluated); if (expressionValid && ((evaluated >= mMin && evaluated <= mMax) || (GetKeyModifiers() & kModifier_Shift))) SetValue(evaluated, NextBufferTime(false)); } if (entry == mMaxEntry) { mMaxEntry->Delete(); mMaxEntry = nullptr; } if (entry == mMinEntry) { mMinEntry->Delete(); mMinEntry = nullptr; } } void FloatSlider::TextEntryCancelled(TextEntry* entry) { if (entry == mFloatEntry) { mFloatEntry->Delete(); mFloatEntry = nullptr; } } void FloatSlider::OnTransportAdvanced(float amount) { mRamp.Start(gTime, mSmoothTarget, gTime + (amount * TheTransport->MsPerBar() * (mSmooth * 300))); } namespace { const int kFloatSliderSaveStateRev = 6; } void FloatSlider::SaveState(FileStreamOut& out) { out << kFloatSliderSaveStateRev; out << (float)*mVar; out << mModulatorMin; out << mModulatorMax; out << mSmooth; out << mSmoothTarget; out << mIsSmoothing; out << mMin; out << mMax; out << (int)mMode; bool hasLFO = mLFOControl && mLFOControl->Active(); out << hasLFO; if (hasLFO) mLFOControl->SaveState(out); } void FloatSlider::LoadState(FileStreamIn& in, bool shouldSetValue) { int rev; in >> rev; float var; in >> var; mRamp.SetValue(var); if (rev < 5) { bool hasLFO; in >> hasLFO; if (hasLFO) { FloatSliderLFOControl* lfo = AcquireLFO(); if (shouldSetValue) lfo->SetLFOEnabled(true); if (rev == 0) { mLFOControl->GetLFOSettings()->LoadState(in); } else if (rev > 0) { mLFOControl->LoadState(in, mLFOControl->LoadModuleSaveStateRev(in)); } if (shouldSetValue) lfo->UpdateFromSettings(); } } if (rev >= 2) { in >> mModulatorMin; in >> mModulatorMax; } if (rev >= 3) { in >> mSmooth; in >> mSmoothTarget; in >> mIsSmoothing; if (mIsSmoothing) TheTransport->AddAudioPoller(this); } if (rev >= 4) { in >> mMin; in >> mMax; } if (rev >= 6) { int modeInt; in >> modeInt; mMode = (Mode)modeInt; } if (rev >= 5) { bool hasLFO; in >> hasLFO; if (hasLFO) { FloatSliderLFOControl* lfo = AcquireLFO(); if (shouldSetValue) lfo->SetLFOEnabled(true); if (rev == 0) { mLFOControl->GetLFOSettings()->LoadState(in); } else if (rev > 0) { mLFOControl->LoadState(in, mLFOControl->LoadModuleSaveStateRev(in)); } if (shouldSetValue) lfo->UpdateFromSettings(); } } if (shouldSetValue && (mModulator == nullptr || !mModulator->Active())) SetValueDirect(var, gTime); } IntSlider::IntSlider(IIntSliderListener* owner, const char* label, int x, int y, int w, int h, int* var, int min, int max) : mVar(var) , mWidth(w) , mHeight(h) , mMin(min) , mMax(max) , mMouseDown(false) , mOwner(owner) , mOriginalValue(0) , mSliderVal(0) , mShowName(true) , mIntEntry(nullptr) , mAllowMinMaxAdjustment(true) , mMinEntry(nullptr) , mMaxEntry(nullptr) { assert(owner); SetName(label); SetPosition(x, y); (dynamic_cast<IDrawableModule*>(owner))->AddUIControl(this); SetParent(dynamic_cast<IClickable*>(owner)); CalcSliderVal(); } IntSlider::IntSlider(IIntSliderListener* owner, const char* label, IUIControl* anchor, AnchorDirection anchorDir, int w, int h, int* var, int min, int max) : IntSlider(owner, label, -1, -1, w, h, var, min, max) { PositionTo(anchor, anchorDir); } IntSlider::~IntSlider() { } void IntSlider::Init() { if (mVar) mOriginalValue = *mVar; } void IntSlider::Poll() { if (*mVar != mLastSetValue) CalcSliderVal(); } void IntSlider::Render() { float normalWidth = mWidth; float normalHeight = mHeight; if (Push2Control::sDrawingPush2Display) { mWidth = 100; mHeight = 15; } mLastDisplayedValue = *mVar; ofPushStyle(); ofColor color, textColor; IUIControl::GetColors(color, textColor); ofFill(); ofSetColor(0, 0, 0, gModuleDrawAlpha * .5f); ofRect(mX + 1, mY + 1, mWidth, mHeight); ofSetColor(color); ofRect(mX, mY, mWidth, mHeight); ofNoFill(); if (mWidth / MAX(1, (mMax - mMin)) > 3) //hash marks { ofPushStyle(); ofSetColor(100, 100, 100, gModuleDrawAlpha); for (int i = mMin + 1; i < mMax; ++i) { float x = mX + 1 + (mWidth - 2) * ((i - mMin) / float(mMax - mMin)); ofLine(x, mY + 1, x, mY + mHeight - 1); } ofPopStyle(); } int val = ofClamp(*mVar, mMin, mMax); ofPushStyle(); ofSetLineWidth(2); ofSetColor(255, 100, 0); float xposfloat = mX + 1 + (mWidth - 2) * mSliderVal; ofLine(xposfloat, mY + mHeight / 2 - 1, xposfloat, mY + mHeight / 2 + 1); if (*mVar >= mMin && *mVar <= mMax) ofSetColor(255, 0, 0, gModuleDrawAlpha); else ofSetColor(30, 30, 30, gModuleDrawAlpha); float xpos = mX + 1 + (mWidth - 2) * ((val - mMin) / float(mMax - mMin)); ofLine(xpos, mY + 1, xpos, mY + mHeight - 1); ofPopStyle(); DrawBeacon(xpos, mY + mHeight / 2); DrawHover(mX, mY, mWidth, mHeight); std::string display; if (mShowName) display = GetDisplayName(); if (display.length() > 0) //only show a colon if there's a label display += ":"; if (mIntEntry) { ofSetColor(255, 255, 100); display += mIntEntry->GetText(); } else { display += GetDisplayValue(*mVar); } if (mMaxEntry || mMinEntry) display = ""; ofSetColor(textColor); DrawTextNormal(display, mX + 2, mY + 5 + mHeight / 2); ofPopStyle(); if (mMaxEntry) { ofPushStyle(); ofFill(); ofSetColor(120, 120, 120, 255); ofRectangle rect = mMaxEntry->GetRect(K(local)); ofRect(rect.x - 28, rect.y, rect.width + 28, rect.height); mMaxEntry->Draw(); ofSetColor(255, 255, 255); DrawTextRightJustify("max:", rect.x, rect.y + 5 + mHeight / 2); ofPopStyle(); } if (mMinEntry) { ofPushStyle(); ofFill(); ofSetColor(120, 120, 120, 255); ofRectangle rect = mMinEntry->GetRect(K(local)); ofRect(rect.x - 28, rect.y, rect.width + 28, rect.height); mMinEntry->Draw(); ofSetColor(255, 255, 255); DrawTextRightJustify("min:", rect.x, rect.y + 5 + mHeight / 2); ofPopStyle(); } if (gHoveredUIControl == this && (GetKeyModifiers() & kModifier_Command) && mAllowMinMaxAdjustment && mMinEntry == nullptr && mMaxEntry == nullptr && !IUIControl::WasLastHoverSetManually()) { ofPushStyle(); ofFill(); ofSetColor(120, 120, 120, 255); ofRect(mX, mY, mWidth * .4f, mHeight); ofRect(mX + mWidth * .6f, mY, mWidth * .4f, mHeight); ofNoFill(); ofSetColor(255, 255, 255); ofRect(mX, mY, mWidth * .4f, mHeight); ofRect(mX + mWidth * .6f, mY, mWidth * .4f, mHeight); DrawTextNormal(ofToString(mMin), mX + 2, mY + 4 + mHeight / 2, 10); DrawTextRightJustify(ofToString(mMax), mX + mWidth - 2, mY + 4 + mHeight / 2, 10); ofPopStyle(); } mWidth = normalWidth; mHeight = normalHeight; } void IntSlider::CalcSliderVal() { mLastSetValue = *mVar; mSliderVal = ofMap(*mVar, mMin, mMax, 0.0f, 1.0f, K(clamp)); } void IntSlider::OnClicked(float x, float y, bool right) { if (right) return; if ((GetKeyModifiers() & kModifier_Command) && mAllowMinMaxAdjustment && !IUIControl::WasLastHoverSetManually()) { bool adjustMax; if (x > mWidth / 2) adjustMax = true; else adjustMax = false; if (adjustMax) { if (mMaxEntry != nullptr) mMaxEntry->Delete(); mMaxEntry = new TextEntry(this, "", mX + mWidth - 5 * 9, mY, 5, &mMax, -INT_MAX, INT_MAX); mMaxEntry->MakeActiveTextEntry(true); } else { if (mMinEntry != nullptr) mMinEntry->Delete(); //mMinEntry = new TextEntry(this, "", mX, mY, 5, &mMin, -FLT_MAX, FLT_MAX); mMinEntry = new TextEntry(this, "", mX + mWidth - 5 * 9, mY, 5, &mMin, -INT_MAX, INT_MAX); mMinEntry->MakeActiveTextEntry(true); } return; } SetValueForMouse(x, y); mMouseDown = true; } bool IntSlider::MouseMoved(float x, float y) { CheckHover(x, y); if (mMouseDown) SetValueForMouse(x, y); return mMouseDown; } void IntSlider::SetValueForMouse(float x, float y) { int oldVal = *mVar; *mVar = (int)round(ofMap(x + mX, mX + 1, mX + mWidth - 1, mMin, mMax)); *mVar = ofClamp(*mVar, mMin, mMax); if (oldVal != *mVar) { CalcSliderVal(); mOwner->IntSliderUpdated(this, oldVal, NextBufferTime(false)); } } void IntSlider::SetFromMidiCC(float slider, double time, bool setViaModulator) { slider = ofClamp(slider, 0, 1); SetValue(GetValueForMidiCC(slider), time); mSliderVal = slider; mLastSetValue = *mVar; } float IntSlider::GetValueForMidiCC(float slider) const { slider = ofClamp(slider, 0, 1); return (int)round(ofMap(slider, 0, 1, mMin, mMax)); } void IntSlider::SetValue(float value, double time, bool forceUpdate /*= false*/) { int oldVal = *mVar; *mVar = (int)round(ofClamp(value, mMin, mMax)); if (oldVal != *mVar || forceUpdate) { CalcSliderVal(); gControlTactileFeedback = 1; mOwner->IntSliderUpdated(this, oldVal, time); } } float IntSlider::GetValue() const { return *mVar; } float IntSlider::GetMidiValue() const { return mSliderVal; } std::string IntSlider::GetDisplayValue(float val) const { return ofToString(val, 0); } void IntSlider::Double() { int doubl = *mVar * 2; if (doubl >= mMin && doubl <= mMax) SetValue(doubl, NextBufferTime(false)); } void IntSlider::Halve() { int half = *mVar / 2; if (half >= mMin && half <= mMax) SetValue(half, NextBufferTime(false)); } void IntSlider::Increment(float amount) { int val = *mVar + (int)amount; if (val >= mMin && val <= mMax) SetValue(val, NextBufferTime(false)); } void IntSlider::ResetToOriginal() { SetValue(mOriginalValue, NextBufferTime(false)); } bool IntSlider::CheckNeedsDraw() { if (IUIControl::CheckNeedsDraw()) return true; return *mVar != mLastDisplayedValue; } bool IntSlider::AttemptTextInput() { if (mIntEntry) mIntEntry->Delete(); mIntEntry = new TextEntry(this, "", HIDDEN_UICONTROL, HIDDEN_UICONTROL, 10, mEntryString); mIntEntry->MakeActiveTextEntry(true); mIntEntry->SetRequireEnter(true); mIntEntry->ClearInput(); return true; } void IntSlider::TextEntryComplete(TextEntry* entry) { if (entry == mIntEntry) { mIntEntry->Delete(); mIntEntry = nullptr; float evaluated = 0; bool expressionValid = EvaluateExpression(mEntryString, *mVar, evaluated); int evaluatedInt = round(evaluated); if (expressionValid && ((evaluatedInt >= mMin && evaluatedInt <= mMax) || (GetKeyModifiers() & kModifier_Shift))) SetValue(evaluatedInt, NextBufferTime(false)); } if (entry == mMaxEntry) { mMaxEntry->Delete(); mMaxEntry = nullptr; } if (entry == mMinEntry) { mMinEntry->Delete(); mMinEntry = nullptr; } } void IntSlider::TextEntryCancelled(TextEntry* entry) { if (entry == mIntEntry) { mIntEntry->Delete(); mIntEntry = nullptr; } } namespace { const int kIntSliderSaveStateRev = 1; } void IntSlider::SaveState(FileStreamOut& out) { out << kIntSliderSaveStateRev; out << (float)*mVar; out << mMin; out << mMax; } void IntSlider::LoadState(FileStreamIn& in, bool shouldSetValue) { int rev; in >> rev; LoadStateValidate(rev <= kIntSliderSaveStateRev); float var; in >> var; if (rev >= 1) { in >> mMin; in >> mMax; } else { if (var < mMin) mMin = var; if (var > mMax) mMax = var; } if (shouldSetValue) SetValueDirect(var, gTime); } ```
/content/code_sandbox/Source/Slider.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
9,210
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // Monome.cpp // modularSynth // // Created by Ryan Challinor on 2/22/14. // // #include "Monome.h" #include "Profiler.h" //static int Monome::sNextMonomeReceivePort = 13338; Monome::Monome(MidiDeviceListener* listener) : mListener(listener) { } Monome::~Monome() { OSCReceiver::disconnect(); } void Monome::UpdateDeviceList(DropdownList* list) { mListForMidiController = list; ListMonomes(); } void Monome::ListMonomes() { if (mHasMonome) return; if (mMonomeReceivePort == -1) { mMonomeReceivePort = sNextMonomeReceivePort; ++sNextMonomeReceivePort; } if (!mIsOscSetUp) { bool success = SetUpOsc(); if (!success) return; } mJustRequestedDeviceList = true; juce::OSCMessage listMsg("/serialosc/list"); listMsg.addString("localhost"); listMsg.addInt32(mMonomeReceivePort); bool written = mToSerialOsc.send(listMsg); assert(written); } bool Monome::SetUpOsc() { assert(!mIsOscSetUp); bool connected = OSCReceiver::connect(mMonomeReceivePort); if (!connected) return false; OSCReceiver::addListener(this); connected = mToSerialOsc.connect(HOST, SERIAL_OSC_PORT); if (!connected) return false; mIsOscSetUp = true; return true; } void Monome::SetLightInternal(int x, int y, float value) { if (!mHasMonome || !mLightsInitialized) return; Vec2i pos = Rotate(x, y, mGridRotation); int index = pos.x + pos.y * mMaxColumns; mLights[index].mValue = value; mLights[index].mLastUpdatedTime = NextBufferTime(false); } void Monome::SetLight(int x, int y, float value) { SetLightInternal(x, y, value); } void Monome::Poll() { int updatedLightCount = 0; for (int i = 0; i < (int)mLights.size(); ++i) { int index = (i * 13 + TheSynth->GetFrameCount() * 7) % (int)mLights.size(); if (mLights[index].mLastUpdatedTime > mLights[index].mLastSentTime) { juce::OSCMessage lightMsg("/" + mPrefix + "/grid/led/level/set"); lightMsg.addInt32(index % mMaxColumns); lightMsg.addInt32(index / mMaxColumns); lightMsg.addInt32(mLights[index].mValue * 16); bool written = mToMonome.send(lightMsg); assert(written); mLights[index].mLastSentTime = gTime; ++updatedLightCount; } static float kRateLimit = 8; if (updatedLightCount > kRateLimit) break; } } void Monome::SetLightFlicker(int x, int y, float intensity) { if (intensity == 0) { SetLight(x, y, false); return; } if (intensity == 1) { SetLight(x, y, true); return; } } std::string Monome::GetControlTooltip(MidiMessageType type, int control) { if (type == kMidiMessage_Note) return "(" + ofToString(control % mMaxColumns) + ", " + ofToString(control / mMaxColumns) + ")"; return MidiController::GetDefaultTooltip(type, control); } void Monome::SetLayoutData(ofxJSONElement& layout) { try { if (!layout["monome_rotation"].isNull()) mGridRotation = layout["monome_rotation"].asInt(); } catch (Json::LogicError& e) { TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } } void Monome::ConnectToDevice(std::string deviceDesc) { MonomeDevice* device = nullptr; for (size_t i = 0; i < mConnectedDeviceList.size(); ++i) { if (mConnectedDeviceList[i].GetDescription() == deviceDesc) device = &mConnectedDeviceList[i]; } if (device == nullptr) { TheSynth->LogEvent("couldn't find monome device " + deviceDesc, kLogEventType_Error); return; } mPrefix = device->id; mLastConnectedDeviceInfo.CopyFrom(*device); if (mListForMidiController != nullptr) { for (int i = 0; i < mListForMidiController->GetNumValues(); ++i) { if (mListForMidiController->GetLabel(i) == device->GetDescription()) mListForMidiController->SetValueDirect(i, NextBufferTime(false)); } } mToMonome.connect(HOST, device->port); mHasMonome = true; juce::OSCMessage setPortMsg("/sys/port"); setPortMsg.addInt32(mMonomeReceivePort); bool written = mToMonome.send(setPortMsg); assert(written); juce::OSCMessage setHostMsg("/sys/host"); setHostMsg.addString(HOST); written = mToMonome.send(setHostMsg); assert(written); juce::OSCMessage setPrefixMsg("/sys/prefix"); setPrefixMsg.addString(mPrefix); written = mToMonome.send(setPrefixMsg); assert(written); juce::OSCMessage sysInfoMsg("/sys/info"); written = mToMonome.send(sysInfoMsg); assert(written); juce::OSCMessage listMsg("/serialosc/notify"); listMsg.addString("localhost"); listMsg.addInt32(mMonomeReceivePort); written = mToSerialOsc.send(listMsg); assert(written); /*OSCMessage setTiltMsg("/"+mPrefix+"/tilt/set"); setTiltMsg.addInt32(0); setTiltMsg.addInt32(1); mToMonome.send(setTiltMsg);*/ for (auto& light : mLights) light.mLastSentTime = 0; } bool Monome::Reconnect() { if (mLastConnectedDeviceInfo.id != "") ConnectToDevice(mLastConnectedDeviceInfo.GetDescription()); return mHasMonome; } void Monome::oscMessageReceived(const juce::OSCMessage& msg) { juce::String label = msg.getAddressPattern().toString(); if (label == "/serialosc/device") { MonomeDevice device; device.id = msg[0].getString().toStdString(); device.product = msg[1].getString().toStdString(); device.port = msg[2].getInt32(); mConnectedDeviceList.push_back(device); if (mListForMidiController != nullptr) { if (mJustRequestedDeviceList) mListForMidiController->Clear(); mListForMidiController->AddLabel(device.GetDescription(), mListForMidiController->GetNumValues()); if (mPendingDeviceDesc != "") { ofLog() << mPendingDeviceDesc; if (mPendingDeviceDesc == device.GetDescription()) { mPendingDeviceDesc = ""; ConnectToDevice(device.GetDescription()); } } } mJustRequestedDeviceList = false; } else if (label == "/serialosc/add") { std::string id = msg[0].getString().toStdString(); if (id == mLastConnectedDeviceInfo.id) mHasMonome = true; juce::OSCMessage listMsg("/serialosc/notify"); listMsg.addString("localhost"); listMsg.addInt32(mMonomeReceivePort); bool written = mToSerialOsc.send(listMsg); assert(written); } else if (label == "/serialosc/remove") { std::string id = msg[0].getString().toStdString(); if (id == mLastConnectedDeviceInfo.id) mHasMonome = false; juce::OSCMessage listMsg("/serialosc/notify"); listMsg.addString("localhost"); listMsg.addInt32(mMonomeReceivePort); bool written = mToSerialOsc.send(listMsg); assert(written); } else if (label == "/sys/size") { if (mGridRotation % 2 == 0) mMaxColumns = msg[0].getInt32(); else mMaxColumns = msg[1].getInt32(); mLights.resize(msg[0].getInt32() * msg[1].getInt32()); mLightsInitialized = true; } else if (label == "/" + mPrefix + "/grid/key") { Vec2i pos = Rotate(msg[0].getInt32(), msg[1].getInt32(), -mGridRotation); int val = msg[2].getInt32(); MidiNote note; note.mPitch = pos.x + pos.y * mMaxColumns; note.mVelocity = val * 127.0f; note.mChannel = 0; note.mDeviceName = mPrefix.toUTF8(); mListener->OnMidiNote(note); } else if (label == "/" + mPrefix + "/tilt") { /*MidiControl updown; updown.mControl = 1; updown.mValue = ofMap(msg[1].getInt32(), 88.0f, 164.0f, 0.0f, 1.0f, true); mListener->OnMidiControl(updown); MidiControl leftright; leftright.mControl = 0; leftright.mValue = 1-ofMap(msg[2].getInt32(), 88.0f, 164.0f, 0.0f, 1.0f, true); mListener->OnMidiControl(leftright);*/ } } void Monome::SendValue(int page, int control, float value, bool forceNoteOn /*= false*/, int channel /*= -1*/) { //SetLightFlicker(control%8,control/8,value); SetLight(control % mMaxColumns, control / mMaxColumns, value); } Vec2i Monome::Rotate(int x, int y, int rotations) { if (rotations < 0) rotations += 4; Vec2i ret(x, y); for (int i = 0; i < rotations; ++i) { x = ret.y; y = mMaxColumns - 1 - ret.x; ret.x = x; ret.y = y; } return ret; } namespace { const int kSaveStateRev = 2; } void Monome::SaveState(FileStreamOut& out) { out << kSaveStateRev; std::string connectedDeviceDesc = ""; if (mLastConnectedDeviceInfo.id != "") connectedDeviceDesc = mLastConnectedDeviceInfo.GetDescription(); out << connectedDeviceDesc; } void Monome::LoadState(FileStreamIn& in) { int rev; in >> rev; LoadStateValidate(rev <= kSaveStateRev); in >> mPendingDeviceDesc; } ```
/content/code_sandbox/Source/Monome.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,613
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // BiquadFilter.h // modularSynth // // Created by Ryan Challinor on 1/2/14. // // #pragma once #include <cmath> enum FilterType { kFilterType_Off, kFilterType_Lowpass, kFilterType_Highpass, kFilterType_Bandpass, kFilterType_Notch, kFilterType_Peak, kFilterType_LowShelf, kFilterType_HighShelf, kFilterType_LowShelfNoQ, kFilterType_HighShelfNoQ, kFilterType_Allpass }; class BiquadFilter { public: BiquadFilter(); void SetSampleRate(double sampleRate) { mSampleRate = sampleRate; } void Clear(); void SetFilterType(FilterType type) { if (type != mType) { mType = type; Clear(); } } void SetFilterParams(double f, double q); void UpdateFilterCoeff(); void CopyCoeffFrom(BiquadFilter& other); bool UsesGain() { return mType == kFilterType_Peak || mType == kFilterType_HighShelf || mType == kFilterType_LowShelf; } bool UsesQ() { return true; } // return mType == kFilterType_Lowpass || mType == kFilterType_Highpass || mType == kFilterType_Bandpass || mType == kFilterType_Notch || mType == kFilterType_Peak; } float GetMagnitudeResponseAt(float f); float Filter(float sample); void Filter(float* buffer, int bufferSize); float mF{ 4000 }; float mQ{ static_cast<float>(sqrt(2.0f) / 2) }; float mDbGain{ 0 }; FilterType mType{ FilterType::kFilterType_Lowpass }; private: double mA0{ 1 }; double mA1{ 0 }; double mA2{ 0 }; double mB1{ 0 }; double mB2{ 0 }; double mZ1{ 0 }; double mZ2{ 0 }; double mSampleRate; }; inline float BiquadFilter::Filter(float in) { double out = in * mA0 + mZ1; mZ1 = in * mA1 + mZ2 - mB1 * out; mZ2 = in * mA2 - mB2 * out; return out; } ```
/content/code_sandbox/Source/BiquadFilter.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
650
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // SliderSequencer.h // Bespoke // // Created by Ryan Challinor on 3/25/14. // // #pragma once #include <iostream> #include "Transport.h" #include "Checkbox.h" #include "Slider.h" #include "DropdownList.h" #include "IDrawableModule.h" #include "INoteSource.h" #include "TextEntry.h" class SliderSequencer; class SliderLine { public: SliderLine(SliderSequencer* owner, int x, int y, int index); void Draw(); void CreateUIControls(); float mPoint{ 0 }; FloatSlider* mSlider{ nullptr }; float mVelocity{ 0 }; FloatSlider* mVelocitySlider{ nullptr }; int mPitch{ 0 }; TextEntry* mNoteSelector{ nullptr }; double mPlayTime{ 0 }; bool mPlaying{ false }; Checkbox* mPlayingCheckbox{ nullptr }; int mX{ 0 }; int mY{ 0 }; SliderSequencer* mOwner{ nullptr }; int mIndex{ 0 }; }; class SliderSequencer : public IDrawableModule, public INoteSource, public IAudioPoller, public IFloatSliderListener, public IDropdownListener, public IIntSliderListener, public ITextEntryListener { public: SliderSequencer(); ~SliderSequencer(); static IDrawableModule* Create() { return new SliderSequencer(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Init() override; void SetEnabled(bool on) override { mEnabled = on; } //IAudioPoller void OnTransportAdvanced(float amount) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; void TextEntryComplete(TextEntry* entry) override {} virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: double MeasurePos(double time); //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = 320; height = 165; } float mLastMeasurePos{ 0 }; std::vector<SliderLine*> mSliderLines; int mDivision{ 1 }; IntSlider* mDivisionSlider{ nullptr }; }; ```
/content/code_sandbox/Source/SliderSequencer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
714
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // NoteCreator.cpp // Bespoke // // Created by Ryan Challinor on 12/28/15. // // #include "NoteCreator.h" #include "SynthGlobals.h" #include "IAudioSource.h" #include "ModularSynth.h" #include "PolyphonyMgr.h" #include "UIControlMacros.h" NoteCreator::NoteCreator() { } void NoteCreator::Init() { IDrawableModule::Init(); } NoteCreator::~NoteCreator() { } void NoteCreator::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); TEXTENTRY_NUM(mPitchEntry, "pitch", 4, &mPitch, 0, 127); FLOATSLIDER(mVelocitySlider, "velocity", &mVelocity, 0, 1); FLOATSLIDER(mDurationSlider, "duration", &mDuration, 1, 1000); CHECKBOX(mNoteOnCheckbox, "on", &mNoteOn); UIBLOCK_SHIFTRIGHT(); BUTTON(mTriggerButton, "trigger"); ENDUIBLOCK(mWidth, mHeight); mPitchEntry->DrawLabel(true); } void NoteCreator::DrawModule() { if (Minimized() || IsVisible() == false) return; mPitchEntry->Draw(); mNoteOnCheckbox->Draw(); mTriggerButton->Draw(); mVelocitySlider->Draw(); mDurationSlider->Draw(); } void NoteCreator::OnPulse(double time, float velocity, int flags) { TriggerNote(time, velocity * mVelocity); } void NoteCreator::TriggerNote(double time, float velocity) { if (!IsEnabled()) return; mStartTime = time; PlayNoteOutput(mStartTime, mPitch, velocity * 127, mVoiceIndex); PlayNoteOutput(mStartTime + mDuration, mPitch, 0, mVoiceIndex); } void NoteCreator::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) mNoteOutput.Flush(time); if (checkbox == mNoteOnCheckbox) { if (mNoteOn) { if (IsEnabled()) PlayNoteOutput(time, mPitch, mVelocity * 127, mVoiceIndex); } else { if (IsEnabled()) PlayNoteOutput(time, mPitch, 0, mVoiceIndex); mNoteOutput.Flush(time); } } } void NoteCreator::ButtonClicked(ClickButton* button, double time) { if (button == mTriggerButton) { TriggerNote(time, mVelocity); } } void NoteCreator::TextEntryComplete(TextEntry* entry) { if (entry == mPitchEntry) { if (mNoteOn) { double time = NextBufferTime(false); mNoteOutput.Flush(time); PlayNoteOutput(time + .1f, mPitch, mVelocity * 127, mVoiceIndex); } } } void NoteCreator::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadInt("voice index", moduleInfo, -1, -1, kNumVoices); SetUpFromSaveData(); } void NoteCreator::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); mVoiceIndex = mModuleSaveData.GetInt("voice index"); } ```
/content/code_sandbox/Source/NoteCreator.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
834
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // NoteRouter.h // modularSynth // // Created by Ryan Challinor on 3/24/13. // // #pragma once #include <iostream> #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "INoteSource.h" #include "RadioButton.h" class NoteRouter : public NoteEffectBase, public IDrawableModule, public IRadioButtonListener { public: NoteRouter(); static IDrawableModule* Create() { return new NoteRouter(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Poll() override; void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; void SetActiveIndex(int index) { mRouteMask = 1 << index; } void SetSelectedMask(int mask); //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; //IRadioButtonListener void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; virtual void SaveLayout(ofxJSONElement& moduleInfo) override; bool IsEnabled() const override { return true; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; bool IsIndexActive(int idx) const; int mRouteMask{ 0 }; RadioButton* mRouteSelector{ nullptr }; std::vector<AdditionalNoteCable*> mDestinationCables; bool mRadioButtonMode{ false }; bool mOnlyShowActiveCables{ false }; }; ```
/content/code_sandbox/Source/NoteRouter.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
510
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // LaunchpadNoteDisplayer.cpp // modularSynth // // Created by Ryan Challinor on 4/16/13. // // #include "LaunchpadNoteDisplayer.h" #include "OpenFrameworksPort.h" #include "LaunchpadKeyboard.h" #include "ModularSynth.h" #include "FillSaveDropdown.h" LaunchpadNoteDisplayer::LaunchpadNoteDisplayer() { } void LaunchpadNoteDisplayer::DrawModule() { } void LaunchpadNoteDisplayer::DrawModuleUnclipped() { DrawConnection(mLaunchpad); } void LaunchpadNoteDisplayer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); if (mLaunchpad) mLaunchpad->DisplayNote(pitch, velocity); } void LaunchpadNoteDisplayer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadString("gridkeyboard", moduleInfo, "", FillDropdown<LaunchpadKeyboard*>); SetUpFromSaveData(); } void LaunchpadNoteDisplayer::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); mLaunchpad = dynamic_cast<LaunchpadKeyboard*>(TheSynth->FindModule(mModuleSaveData.GetString("gridkeyboard"), false)); if (mLaunchpad) mLaunchpad->SetDisplayer(this); } ```
/content/code_sandbox/Source/LaunchpadNoteDisplayer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
413
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // PitchDetector.h // modularSynth // // Created by Ryan Challinor on 3/16/14. // // #pragma once class FFT; class PitchDetector { public: PitchDetector(); ~PitchDetector(); float DetectPitch(float* buffer, int bufferSize); private: //////////////////////////////////////// //ported float mTune{ 440 }; float mPitch{ 0 }; float mConfidence{ 0 }; float mLatency{ 0 }; ::FFT* mFFT; unsigned long mfs; // Sample rate unsigned long mcbsize; // size of circular buffer unsigned long mcorrsize; // cbsize/2 + 1 unsigned long mcbiwr; float* mcbi; // circular input buffer float* mcbwindow; // hann of length N/2, zeros for the rest float* macwinv; // inverse of autocorrelation of window int mnoverlap; float* mffttime; float* mfftfreqre; float* mfftfreqim; // VARIABLES FOR LOW-RATE SECTION float maref{ 440 }; // A tuning reference (Hz) float mconf{ 0 }; // Confidence of pitch period estimate (between 0 and 1) float mvthresh; // Voiced speech threshold float mpmax; // Maximum allowable pitch period (seconds) float mpmin; // Minimum allowable pitch period (seconds) unsigned long mnmax; // Maximum period index for pitch prd est unsigned long mnmin; // Minimum period index for pitch prd est float mlrshift; // Shift prescribed by low-rate section int mptarget; // Pitch target, between 0 and 11 float msptarget; // Smoothed pitch target }; ```
/content/code_sandbox/Source/PitchDetector.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
496
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // PressureToVibrato.h // Bespoke // // Created by Ryan Challinor on 1/4/16. // // #pragma once #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "Slider.h" #include "ModulationChain.h" #include "DropdownList.h" class PressureToVibrato : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public IDropdownListener { public: PressureToVibrato(); virtual ~PressureToVibrato(); static IDrawableModule* Create() { return new PressureToVibrato(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = 138; height = 22; } NoteInterval mVibratoInterval{ NoteInterval::kInterval_16n }; DropdownList* mIntervalSelector{ nullptr }; float mVibratoAmount{ 1 }; FloatSlider* mVibratoSlider{ nullptr }; Modulations mModulation{ true }; }; ```
/content/code_sandbox/Source/PressureToVibrato.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
526
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // NoteChainNode.cpp // Bespoke // // Created by Ryan Challinor on 5/1/16. // // #include "NoteChainNode.h" #include "SynthGlobals.h" #include "IAudioSource.h" #include "ModularSynth.h" #include "PolyphonyMgr.h" #include "PatchCableSource.h" NoteChainNode::NoteChainNode() { } void NoteChainNode::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); TheTransport->AddListener(this, kInterval_8n, OffsetInfo(0, true), false); } NoteChainNode::~NoteChainNode() { TheTransport->RemoveAudioPoller(this); } void NoteChainNode::CreateUIControls() { IDrawableModule::CreateUIControls(); mPitchEntry = new TextEntry(this, "pitch", 5, 3, 3, &mPitch, 0, 127); mTriggerButton = new ClickButton(this, "trigger", 50, 3); mVelocitySlider = new FloatSlider(this, "velocity", 5, 21, 100, 15, &mVelocity, 0, 1); mDurationSlider = new FloatSlider(this, "duration", 5, 39, 100, 15, &mDuration, 0.01f, 4, 4); mNextSelector = new DropdownList(this, "next", 5, 57, (int*)(&mNextInterval)); mNextSelector->AddLabel("1n", kInterval_1n); mNextSelector->AddLabel("2n", kInterval_2n); mNextSelector->AddLabel("4n", kInterval_4n); mNextSelector->AddLabel("4nt", kInterval_4nt); mNextSelector->AddLabel("8n", kInterval_8n); mNextSelector->AddLabel("8nt", kInterval_8nt); mNextSelector->AddLabel("16n", kInterval_16n); mNextSelector->AddLabel("16nt", kInterval_16nt); mNextSelector->AddLabel("32n", kInterval_32n); mNextSelector->AddLabel("64n", kInterval_64n); mNextNodeCable = new PatchCableSource(this, kConnectionType_Pulse); mNextNodeCable->SetManualPosition(100, 10); AddPatchCableSource(mNextNodeCable); } void NoteChainNode::DrawModule() { if (Minimized() || IsVisible() == false) return; mPitchEntry->Draw(); mTriggerButton->Draw(); mVelocitySlider->Draw(); mDurationSlider->Draw(); mNextSelector->Draw(); } void NoteChainNode::OnTimeEvent(double time) { if (mQueueTrigger) { TriggerNote(time); mQueueTrigger = false; } } void NoteChainNode::OnTransportAdvanced(float amount) { if (mNoteOn && NextBufferTime(true) > mStartTime + mDurationMs) { mNoteOn = false; mNoteOutput.Flush(mStartTime + mDurationMs); } if (mWaitingToTrigger && NextBufferTime(true) > mStartTime + mNext) { mWaitingToTrigger = false; DispatchPulse(mNextNodeCable, mStartTime + mNext, 1, 0); } } void NoteChainNode::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { } void NoteChainNode::OnPulse(double time, float velocity, int flags) { TriggerNote(time); } void NoteChainNode::TriggerNote(double time) { if (mEnabled) { mNoteOn = true; mWaitingToTrigger = true; mStartTime = time; mDurationMs = mDuration / (float(TheTransport->GetTimeSigTop()) / TheTransport->GetTimeSigBottom()) * TheTransport->MsPerBar(); mNext = TheTransport->GetDuration(mNextInterval); PlayNoteOutput(time, mPitch, mVelocity * 127); } } void NoteChainNode::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) mNoteOutput.Flush(time); } void NoteChainNode::ButtonClicked(ClickButton* button, double time) { if (button == mTriggerButton) mQueueTrigger = true; } void NoteChainNode::TextEntryComplete(TextEntry* entry) { if (entry == mPitchEntry) { mNoteOn = false; mNoteOutput.Flush(NextBufferTime(false)); } } void NoteChainNode::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void NoteChainNode::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/NoteChainNode.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,180
```objective-c #pragma once #include <iostream> #include <sstream> #include <iomanip> #include <assert.h> #include <map> #include <vector> #include <list> #include <cmath> #include <mutex> class NVGcontext; extern NVGcontext* gNanoVG; extern NVGcontext* gFontBoundsNanoVG; struct ofColor { ofColor() : ofColor(255, 255, 255) {} ofColor(int _r, int _g, int _b) : r(_r) , g(_g) , b(_b) {} ofColor(int _r, int _g, int _b, int _a) : r(_r) , g(_g) , b(_b) , a(_a) {} void set(int _r, int _g, int _b, int _a = 255) { r = _r; g = _g; b = _b; a = _a; } void setBrightness(int _bright); int getBrightness() const; void setSaturation(int _sat); int getSaturation() const; void getHsb(float& h, float& s, float& b) const; void setHsb(int h, int s, int b); ofColor operator*(const ofColor& other); ofColor operator*(float f); ofColor operator+(const ofColor& other); int r{ 0 }; int g{ 0 }; int b{ 0 }; int a{ 255 }; static ofColor black, white, grey, red, green, yellow, blue, orange, purple, lime, magenta, cyan, clear; static ofColor lerp(ofColor a, ofColor b, float t) { return ofColor(int(a.r * (1 - t) + b.r * t), int(a.g * (1 - t) + b.g * t), int(a.b * (1 - t) + b.b * t), int(a.a * (1 - t) + b.a * t)); } }; struct ofVec2f { ofVec2f() {} ofVec2f(float _x, float _y) : x(_x) , y(_y) {} void set(float _x, float _y) { x = _x; y = _y; } ofVec2f operator-(const ofVec2f& other) { return ofVec2f(x - other.x, y - other.y); } ofVec2f operator+(const ofVec2f& other) { return ofVec2f(x + other.x, y + other.y); } float lengthSquared() const { return x * x + y * y; } float distanceSquared() const { return x * x + y * y; } float distanceSquared(ofVec2f other) const { return (x - other.x) * (x - other.x) + (y - other.y) * (y - other.y); } float dot(const ofVec2f& vec) const { return x * vec.x + y * vec.y; } ofVec2f operator*(float f) { return ofVec2f(x * f, y * f); } ofVec2f operator/(float f) { return ofVec2f(x / f, y / f); } ofVec2f& operator-=(const ofVec2f& other) { x -= other.x; y -= other.y; return *this; } ofVec2f& operator+=(const ofVec2f& other) { x += other.x; y += other.y; return *this; } float x{ 0 }; float y{ 0 }; }; struct ofVec3f { ofVec3f() {} ofVec3f(float _x, float _y, float _z) : x(_x) , y(_y) , z(_z) {} float length() const { return sqrt(x * x + y * y + z * z); } float x{ 0 }; float y{ 0 }; float z{ 0 }; }; struct ofRectangle { ofRectangle() {} ofRectangle(float _x, float _y, float _w, float _h) : x(_x) , y(_y) , width(_w) , height(_h) { } ofRectangle(ofVec2f p1, ofVec2f p2) { set(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y); } void set(float _x, float _y, float _w, float _h) { x = _x; y = _y; width = _w; height = _h; } bool intersects(const ofRectangle& other) const; bool contains(float x, float y) const; ofRectangle& grow(float amount) { x -= amount; y -= amount; width += amount * 2; height += amount * 2; return *this; } float getMinX() const; float getMaxX() const; float getMinY() const; float getMaxY() const; ofVec2f getCenter() const { return ofVec2f(x + width * .5f, y + height * .5f); } float x{ 0 }; float y{ 0 }; float width{ 100 }; float height{ 100 }; }; using ofMutex = std::recursive_mutex; #define CLAMP(v, a, b) (v < a ? a : (v > b ? b : v)) #define MAX(a, b) (a > b ? a : b) #define MIN(a, b) (a < b ? a : b) #define OF_KEY_RETURN juce::KeyPress::returnKey #define OF_KEY_TAB juce::KeyPress::tabKey #define OF_KEY_LEFT juce::KeyPress::leftKey #define OF_KEY_RIGHT juce::KeyPress::rightKey #define OF_KEY_ESC juce::KeyPress::escapeKey #define OF_KEY_UP juce::KeyPress::upKey #define OF_KEY_DOWN juce::KeyPress::downKey template <class T> inline std::string ofToString(const T& value) { std::ostringstream out; out << value; return out.str(); } template <class T> inline std::string ofToString(const T& value, int precision) { std::ostringstream out; out << std::fixed << std::setprecision(precision) << value; return out.str(); } #define PI 3.14159265358979323846 #define TWO_PI 6.28318530717958647693 class RetinaTrueTypeFont { public: RetinaTrueTypeFont() {} void LoadFont(std::string path); void DrawString(std::string str, float size, float x, float y); ofRectangle DrawStringWrap(std::string str, float size, float x, float y, float width); float GetStringWidth(std::string str, float size); float GetStringHeight(std::string str, float size); bool IsLoaded() { return mLoaded; } int GetFontHandle() const { return mFontHandle; } std::string GetFontPath() const { return mFontPath; } private: int mFontHandle{}; int mFontBoundsHandle{}; bool mLoaded{ false }; std::string mFontPath; }; typedef ofVec2f ofPoint; std::string ofToDataPath(const std::string& path); std::string ofToFactoryPath(const std::string& path); std::string ofToResourcePath(const std::string& path); void ofPushStyle(); void ofPopStyle(); void ofPushMatrix(); void ofPopMatrix(); void ofTranslate(float x, float y, float z = 0); void ofRotate(float radians); void ofClipWindow(float x, float y, float width, float height, bool intersectWithExisting); void ofResetClipWindow(); void ofSetColor(float r, float g, float b, float a = 255); void ofSetColor(float grey); void ofSetColor(const ofColor& color); void ofSetColor(const ofColor& color, float a); void ofSetColorGradient(const ofColor& colorA, const ofColor& colorB, ofVec2f gradientStart, ofVec2f gradientEnd); void ofFill(); void ofNoFill(); void ofCircle(float x, float y, float radius); void ofRect(float x, float y, float width, float height, float cornerRadius = 3); void ofRect(const ofRectangle& rect, float cornerRadius = 3); float ofClamp(float val, float a, float b); float ofGetLastFrameTime(); int ofToInt(const std::string& intString); float ofToFloat(const std::string& floatString); int ofHexToInt(const std::string& hexString); void ofLine(float x1, float y1, float x2, float y2); void ofLine(ofVec2f v1, ofVec2f v2); void ofSetLineWidth(float width); void ofBeginShape(); void ofEndShape(bool close = false); void ofVertex(float x, float y, float z = 0); void ofVertex(ofVec2f point); float ofMap(float val, float fromStart, float fromEnd, float toStart, float toEnd, bool clamp = false); float ofRandom(float max); float ofRandom(float x, float y); void ofSetCircleResolution(float res); unsigned long long ofGetSystemTimeNanos(); float ofGetWidth(); float ofGetHeight(); float ofGetFrameRate(); float ofLerp(float start, float stop, float amt); float ofDistSquared(float x1, float y1, float x2, float y2); std::vector<std::string> ofSplitString(std::string str, std::string splitter, bool ignoreEmpty = false, bool trim = false); bool ofIsStringInString(const std::string& haystack, const std::string& needle); void ofScale(float x, float y, float z); void ofExit(); void ofToggleFullscreen(); void ofStringReplace(std::string& str, std::string from, std::string to, bool firstOnly = false); std::string ofGetTimestampString(std::string in); void ofTriangle(float x1, float y1, float x2, float y2, float x3, float y3); ```
/content/code_sandbox/Source/OpenFrameworksPort.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,324
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== PulseSequence.h Created: 21 Oct 2018 11:26:09pm Author: Ryan Challinor ============================================================================== */ #pragma once #include <iostream> #include "IDrawableModule.h" #include "Transport.h" #include "DropdownList.h" #include "TextEntry.h" #include "ClickButton.h" #include "Slider.h" #include "IPulseReceiver.h" #include "UIGrid.h" #include "IDrivableSequencer.h" class PatchCableSource; class PulseSequence : public IDrawableModule, public ITimeListener, public IButtonListener, public IDropdownListener, public IIntSliderListener, public IFloatSliderListener, public IAudioPoller, public IPulseSource, public IPulseReceiver, public UIGridListener, public IDrivableSequencer { public: PulseSequence(); virtual ~PulseSequence(); static IDrawableModule* Create() { return new PulseSequence(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return true; } void CreateUIControls() override; void Init() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //IPulseReceiver void OnPulse(double time, float velocity, int flags) override; //IAudioPoller void OnTransportAdvanced(float amount) override; //ITimeListener void OnTimeEvent(double time) override; //UIGridListener void GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) override; //IClickable void MouseReleased() override; bool MouseMoved(float x, float y) override; bool MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) override; //IDrivableSequencer bool HasExternalPulseSource() const override { return mHasExternalPulseSource; } void ResetExternalPulseSource() override { mHasExternalPulseSource = false; } void ButtonClicked(ClickButton* button, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 2; } void SaveLayout(ofxJSONElement& moduleInfo) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; void OnClicked(float x, float y, bool right) override; void Step(double time, float velocity, int flags); static const int kMaxSteps = 32; float mVels[kMaxSteps]{}; int mLength{ 8 }; IntSlider* mLengthSlider{ nullptr }; int mStep{ 0 }; NoteInterval mInterval{ NoteInterval::kInterval_8n }; DropdownList* mIntervalSelector{ nullptr }; bool mHasExternalPulseSource{ false }; ClickButton* mAdvanceBackwardButton{ nullptr }; ClickButton* mAdvanceForwardButton{ nullptr }; static const int kIndividualStepCables = kMaxSteps; PatchCableSource* mStepCables[kIndividualStepCables]{}; UIGrid* mVelocityGrid{ nullptr }; TransportListenerInfo* mTransportListenerInfo{ nullptr }; }; ```
/content/code_sandbox/Source/PulseSequence.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
959
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== QuickSpawnMenu.cpp Created: 22 Oct 2017 7:49:17pm Author: Ryan Challinor ============================================================================== */ #include "QuickSpawnMenu.h" #include "ModularSynth.h" #include "ModuleFactory.h" #include "TitleBar.h" #include "PatchCable.h" #include "PatchCableSource.h" #include "UserPrefs.h" #include "juce_gui_basics/juce_gui_basics.h" QuickSpawnMenu* TheQuickSpawnMenu = nullptr; namespace { const int kItemSpacing = 15; const int kRightClickShiftX = 11; ofVec2f kModuleGrabOffset(-40, 10); } QuickSpawnMenu::QuickSpawnMenu() { assert(TheQuickSpawnMenu == nullptr); TheQuickSpawnMenu = this; } QuickSpawnMenu::~QuickSpawnMenu() { assert(TheQuickSpawnMenu == this); TheQuickSpawnMenu = nullptr; delete mMainContainerFollower; } void QuickSpawnMenu::Init() { IDrawableModule::Init(); SetShouldDrawOutline(false); mMainContainerFollower = new QuickSpawnFollower(); mMainContainerFollower->SetName("quickspawnfollower"); mMainContainerFollower->CreateUIControls(); mMainContainerFollower->SetUp(); mMainContainerFollower->SetShowing(false); Hide(); } void QuickSpawnFollower::SetUp() { mTempConnectionCable = new PatchCableSource(this, kConnectionType_Special); AddPatchCableSource(mTempConnectionCable); mTempConnectionCable->SetShowing(false); } void QuickSpawnMenu::ShowSpawnCategoriesPopup() { ResetAppearPos(); mMenuMode = MenuMode::ModuleCategories; mSearchString = ""; mFilterForCable = nullptr; UpdateDisplay(); } void QuickSpawnMenu::ShowSpawnCategoriesPopupForCable(PatchCable* cable) { ResetAppearPos(); mMenuMode = MenuMode::ModuleCategories; mSearchString = ""; mFilterForCable = cable; mMainContainerFollower->mTempConnectionCable->SetShowing(false); UpdateDisplay(); } void QuickSpawnMenu::SetTempConnection(IClickable* target, ConnectionType connectionType) { mMainContainerFollower->mTempConnectionCable->SetConnectionType(connectionType); mMainContainerFollower->mTempConnectionCable->SetTarget(target); mMainContainerFollower->mTempConnectionCable->SetShowing(true); } void QuickSpawnMenu::ResetAppearPos() { mAppearAtMousePos.set(TheSynth->GetMouseX(GetOwningContainer()), TheSynth->GetMouseY(GetOwningContainer())); mScrollOffset = 0; } void QuickSpawnMenu::KeyPressed(int key, bool isRepeat) { IDrawableModule::KeyPressed(key, isRepeat); if (!IsShowing()) ResetAppearPos(); if (!IsShowing() && PatchCable::sActivePatchCable != nullptr && key >= 'a' && key <= 'z') PatchCable::sActivePatchCable->ShowQuickspawnForCable(); if ((!IsShowing() || mMenuMode == MenuMode::SingleLetter) && key >= 0 && key < CHAR_MAX && ((key >= 'a' && key <= 'z') || key == ';') && !isRepeat && GetKeyModifiers() == kModifier_None) { mHeldKeys += (char)key; mMenuMode = MenuMode::SingleLetter; mFilterForCable = nullptr; UpdateDisplay(); } if (IsShowing()) { if (key == OF_KEY_DOWN || key == OF_KEY_UP || key == OF_KEY_LEFT || key == OF_KEY_RIGHT) { int oldIndex = mHighlightIndex; mHighlightIndex = ofClamp(mHighlightIndex + (key == OF_KEY_DOWN || key == OF_KEY_RIGHT ? 1 : -1), 0, (int)mElements.size() - 1); int change = mHighlightIndex - oldIndex; mScrollOffset -= change * kItemSpacing; UpdatePosition(); MoveMouseToIndex(mHighlightIndex); } if (key == OF_KEY_RETURN) { if (mHighlightIndex < 0 || mHighlightIndex >= mElements.size()) mHighlightIndex = 0; OnSelectItem(mHighlightIndex); } if (key >= 0 && key < CHAR_MAX && juce::CharacterFunctions::isPrintable((char)key) && mMenuMode != MenuMode::SingleLetter) { mSearchString += (char)key; mMenuMode = MenuMode::Search; UpdateDisplay(); MoveMouseToIndex(0); } if (mMenuMode == MenuMode::Search && key == juce::KeyPress::backspaceKey) { if (mSearchString.length() > 0) { mSearchString = mSearchString.substring(0, mSearchString.length() - 1); if (mSearchString.length() == 0) { mMenuMode = MenuMode::ModuleCategories; UpdateDisplay(); } else { UpdateDisplay(); MoveMouseToIndex(0); } } } } if (key == OF_KEY_ESC) Hide(); } void QuickSpawnMenu::KeyReleased(int key) { if (mMenuMode == MenuMode::SingleLetter && key >= 0 && key < CHAR_MAX) { mHeldKeys = mHeldKeys.removeCharacters(juce::String::charToString((char)key)); UpdateDisplay(); } } void QuickSpawnMenu::Hide() { SetShowing(false); if (mFilterForCable != nullptr) { if (mMainContainerFollower->mTempConnectionCable->IsShowing()) mFilterForCable->SetTempDrawTarget(nullptr); else mFilterForCable->GetOwner()->SetPatchCableTarget(mFilterForCable, nullptr, true); } mFilterForCable = nullptr; mMainContainerFollower->mTempConnectionCable->SetShowing(false); } void QuickSpawnMenu::UpdateDisplay() { if ((mMenuMode == MenuMode::SingleLetter && mHeldKeys.isEmpty()) || TheSynth->GetMoveModule() != nullptr) { Hide(); } else { if (mMenuMode == MenuMode::ModuleCategories) { mElements.clear(); mCategoryIndices.clear(); int categoryIndex = 0; for (auto* dropdown : TheTitleBar->GetSpawnLists()) { bool containsValidTarget = false; if (mFilterForCable == nullptr) { containsValidTarget = true; } else { const auto& spawnables = dropdown->GetElements(); for (size_t i = 0; i < spawnables.size(); ++i) { if (MatchesFilter(spawnables[i])) containsValidTarget = true; } } if (containsValidTarget) { std::string label = dropdown->GetLabel(); ofStringReplace(label, ":", ""); ModuleFactory::Spawnable dummy; dummy.mLabel = label; mElements.push_back(dummy); mCategoryIndices.push_back(categoryIndex); } ++categoryIndex; } } else if (mMenuMode == MenuMode::SingleCategory) { mElements.clear(); const auto& elements = TheTitleBar->GetSpawnLists()[mSelectedCategoryIndex]->GetElements(); for (size_t i = 0; i < elements.size(); ++i) { if (MatchesFilter(elements[i])) mElements.push_back(elements[i]); } } else if (mMenuMode == MenuMode::Search) { mElements.clear(); const auto& elements = TheSynth->GetModuleFactory()->GetSpawnableModules(mSearchString.toStdString(), true); int exactMatches = 0; for (size_t i = 0; i < elements.size(); ++i) { if (MatchesFilter(elements[i])) { if (juce::String(elements[i].mLabel).startsWith(mSearchString)) { mElements.insert(mElements.begin() + exactMatches, elements[i]); ++exactMatches; } else { mElements.push_back(elements[i]); } } } } else { mElements.clear(); const auto& elements = TheSynth->GetModuleFactory()->GetSpawnableModules(mHeldKeys.toStdString(), false); for (size_t i = 0; i < elements.size(); ++i) { if (MatchesFilter(elements[i])) mElements.push_back(elements[i]); } mScrollOffset = 0; } float width = 150; for (auto& element : mElements) { float elementWidth = GetStringWidth(element.mLabel + " " + element.mDecorator) + 10 + (mMenuMode == MenuMode::SingleLetter ? 0 : kRightClickShiftX); if (elementWidth > width) width = elementWidth; } SetDimensions(width, MAX((int)mElements.size(), 1) * kItemSpacing); UpdatePosition(); SetShowing(true); } } bool QuickSpawnMenu::MatchesFilter(const ModuleFactory::Spawnable& spawnable) const { if (mFilterForCable == nullptr) return true; bool inputMatches = false; bool outputMatches = false; ModuleFactory::ModuleInfo info; if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::Preset) info = TheSynth->GetModuleFactory()->GetModuleInfo(spawnable.mPresetModuleType); else info = TheSynth->GetModuleFactory()->GetModuleInfo(spawnable.mLabel); if (mFilterForCable->GetConnectionType() == kConnectionType_Note) { if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::Plugin) inputMatches = true; if (info.mCanReceiveNotes) inputMatches = true; } if (mFilterForCable->GetConnectionType() == kConnectionType_Audio) { if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::Plugin) inputMatches = true; if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::EffectChain) inputMatches = true; if (info.mCanReceiveAudio) inputMatches = true; } if (mFilterForCable->GetConnectionType() == kConnectionType_Pulse) { if (info.mCanReceivePulses) inputMatches = true; } if (mMainContainerFollower->mTempConnectionCable->IsShowing()) { if (mMainContainerFollower->mTempConnectionCable->GetConnectionType() == kConnectionType_Note) { if (info.mCategory == kModuleCategory_Instrument) outputMatches = true; if (info.mCategory == kModuleCategory_Note) outputMatches = true; } if (mMainContainerFollower->mTempConnectionCable->GetConnectionType() == kConnectionType_Audio) { if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::Plugin) outputMatches = true; if (spawnable.mSpawnMethod == ModuleFactory::SpawnMethod::EffectChain) outputMatches = true; if (info.mCategory == kModuleCategory_Synth) outputMatches = true; if (info.mCategory == kModuleCategory_Audio) outputMatches = true; if (info.mCategory == kModuleCategory_Processor) outputMatches = true; } if (mMainContainerFollower->mTempConnectionCable->GetConnectionType() == kConnectionType_Pulse) { if (info.mCategory == kModuleCategory_Pulse) outputMatches = true; } } else { outputMatches = true; //doesn't matter } return inputMatches && outputMatches; } void QuickSpawnMenu::UpdatePosition() { float minX = 5; float maxX = ofGetWidth() / GetOwningContainer()->GetDrawScale() - mWidth - 5; float minY = TheTitleBar->GetRect().height + 5; float maxY = ofGetHeight() / GetOwningContainer()->GetDrawScale() - mHeight - 5; if (mMenuMode == MenuMode::SingleLetter) { SetPosition(ofClamp(mAppearAtMousePos.x - mWidth / 2, minX, maxX), ofClamp(mAppearAtMousePos.y - mHeight / 2, minY, maxY) + mScrollOffset); } else { SetPosition(ofClamp(mAppearAtMousePos.x - 5, minX, maxX), mAppearAtMousePos.y - kItemSpacing / 2 + mScrollOffset); } } void QuickSpawnMenu::MouseReleased() { } bool QuickSpawnMenu::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) { const float kScrollSpeed = 5; if (isInvertedScroll) scrollY *= -1; if (!isSmoothScroll) { if (scrollY < 0) scrollY = -kItemSpacing / kScrollSpeed; if (scrollY > 0) scrollY = kItemSpacing / kScrollSpeed; } float newY = ofClamp(y - scrollY * kScrollSpeed, kItemSpacing / 2, mHeight - kItemSpacing / 2); float changeAmount = newY - y; mScrollOffset -= changeAmount; UpdatePosition(); return true; } void QuickSpawnMenu::MoveMouseToIndex(int index) { mHighlightIndex = index; TheSynth->SetMousePosition(GetOwningContainer(), mX + 5, mY + (index + .5f) * kItemSpacing); } void QuickSpawnMenu::DrawModule() { ofPushStyle(); mHighlightIndex = -1; if (TheSynth->GetMouseY(GetOwningContainer()) > GetPosition().y) mHighlightIndex = GetIndexAt(TheSynth->GetMouseX(GetOwningContainer()) - GetPosition().x, TheSynth->GetMouseY(GetOwningContainer()) - GetPosition().y); ofSetColor(50, 50, 50, 100); ofFill(); ofRect(-2, -2, mWidth + 4, mHeight + 4); for (int i = 0; i < mElements.size(); ++i) { if (mMenuMode == MenuMode::ModuleCategories) ofSetColor(IDrawableModule::GetColor(TheTitleBar->GetSpawnLists()[mCategoryIndices[i]]->GetCategory()) * (i == mHighlightIndex ? .7f : .5f), 255); else ofSetColor(IDrawableModule::GetColor(TheSynth->GetModuleFactory()->GetModuleCategory(mElements[i])) * (i == mHighlightIndex ? .7f : .5f), 255); ofRect(0, i * kItemSpacing + 1, mWidth, kItemSpacing - 1); if (i == mHighlightIndex) ofSetColor(255, 255, 0); else ofSetColor(255, 255, 255); bool showDecorator = true; if (mMenuMode == MenuMode::SingleCategory && mSelectedCategoryIndex >= 0 && mSelectedCategoryIndex < (int)TheTitleBar->GetSpawnLists().size()) showDecorator = TheTitleBar->GetSpawnLists()[mSelectedCategoryIndex]->ShouldShowDecorators(); DrawTextNormal(mElements[i].mLabel + (showDecorator ? (" " + mElements[i].mDecorator) : ""), 1 + (mMenuMode == MenuMode::SingleLetter ? 0 : kRightClickShiftX), i * kItemSpacing + 12); } if (mElements.size() == 0) { ofSetColor(255, 255, 255); DrawTextNormal("no modules found", 1, 12); } ofPopStyle(); mMainContainerFollower->UpdateLocation(); } void QuickSpawnMenu::DrawModuleUnclipped() { if (mMenuMode == MenuMode::SingleLetter) DrawTextBold(mHeldKeys.toStdString(), 3, -2, 15); if (mMenuMode == MenuMode::Search) DrawTextBold(mSearchString.toStdString(), 3, -2, 15); } bool QuickSpawnMenu::MouseMoved(float x, float y) { mLastHoverX = x; mLastHoverY = y; return false; } void QuickSpawnMenu::OnClicked(float x, float y, bool right) { if (right) { if (IsShowing()) Hide(); return; } OnSelectItem(GetIndexAt(x, y)); } void QuickSpawnMenu::OnSelectItem(int index) { if (mMenuMode == MenuMode::SingleLetter || mMenuMode == MenuMode::Search || mMenuMode == MenuMode::SingleCategory) { if (index >= 0 && index < mElements.size()) { IDrawableModule* module = TheSynth->SpawnModuleOnTheFly(mElements[index], TheSynth->GetMouseX(TheSynth->GetRootContainer()) + kModuleGrabOffset.x, TheSynth->GetMouseY(TheSynth->GetRootContainer()) + kModuleGrabOffset.y); TheSynth->SetMoveModule(module, kModuleGrabOffset.x, kModuleGrabOffset.y, true); if (mFilterForCable != nullptr) { mFilterForCable->SetTempDrawTarget(nullptr); if (mMainContainerFollower->mTempConnectionCable->IsShowing()) module->SetTarget(mMainContainerFollower->mTempConnectionCable->GetTarget()); mFilterForCable->GetOwner()->SetPatchCableTarget(mFilterForCable, module, true); mFilterForCable = nullptr; } } Hide(); } if (mMenuMode == MenuMode::ModuleCategories) { if (index >= 0 && index < mElements.size()) { mSelectedCategoryIndex = mCategoryIndices[index]; mMenuMode = MenuMode::SingleCategory; ResetAppearPos(); UpdateDisplay(); } else { Hide(); } } } std::string QuickSpawnMenu::GetHoveredModuleTypeName() { auto* element = GetElementAt(mLastHoverX, mLastHoverY); if (element) return element->mLabel; else return ""; } int QuickSpawnMenu::GetIndexAt(int x, int y) const { if (x >= 0 && x < mWidth) return y / kItemSpacing; return -1; } const ModuleFactory::Spawnable* QuickSpawnMenu::GetElementAt(int x, int y) const { int index = GetIndexAt(x, y); if (index >= 0 && index < mElements.size()) return &mElements[index]; return nullptr; } void QuickSpawnFollower::GetDimensions(float& width, float& height) { TheQuickSpawnMenu->GetDimensions(width, height); float scaleFactor = UserPrefs.ui_scale.Get() / gDrawScale; width *= scaleFactor; height *= scaleFactor; height -= 10; width -= 10; } void QuickSpawnFollower::UpdateLocation() { float x, y; TheQuickSpawnMenu->GetPosition(x, y); float scaleFactor = UserPrefs.ui_scale.Get() / gDrawScale; x *= scaleFactor; y *= scaleFactor; x -= TheSynth->GetDrawOffset().x; y -= TheSynth->GetDrawOffset().y; SetPosition(x, y); } ```
/content/code_sandbox/Source/QuickSpawnMenu.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
4,474
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // NoteRouter.cpp // modularSynth // // Created by Ryan Challinor on 3/24/13. // // #include "NoteRouter.h" #include "OpenFrameworksPort.h" #include "ModularSynth.h" #include "PatchCable.h" #include "PatchCableSource.h" NoteRouter::NoteRouter() { } void NoteRouter::CreateUIControls() { IDrawableModule::CreateUIControls(); mRouteSelector = new RadioButton(this, "route", 5, 3, &mRouteMask); GetPatchCableSource()->SetEnabled(false); } void NoteRouter::Poll() { for (int i = 0; i < (int)mDestinationCables.size(); ++i) mDestinationCables[i]->GetPatchCableSource()->SetShowing(!mOnlyShowActiveCables || IsIndexActive(i)); } void NoteRouter::DrawModule() { if (Minimized() || IsVisible() == false) return; mRouteSelector->Draw(); for (int i = 0; i < (int)mDestinationCables.size(); ++i) { ofVec2f pos = mRouteSelector->GetOptionPosition(i) - mRouteSelector->GetPosition(); mDestinationCables[i]->GetPatchCableSource()->SetManualPosition(pos.x + 10, pos.y + 4); } } void NoteRouter::SetSelectedMask(int mask) { int oldMask = mRouteMask; mRouteMask = mask; RadioButtonUpdated(mRouteSelector, oldMask, NextBufferTime(false)); } bool NoteRouter::IsIndexActive(int idx) const { if (mRadioButtonMode) return mRouteMask == idx; else return mRouteMask & (1 << idx); } void NoteRouter::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { for (int i = 0; i < (int)mDestinationCables.size(); ++i) { if (IsIndexActive(i)) { mDestinationCables[i]->PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } } } void NoteRouter::RadioButtonUpdated(RadioButton* radio, int oldVal, double time) { if (radio == mRouteSelector) { if (mRadioButtonMode) { if (oldVal < (int)mDestinationCables.size()) mDestinationCables[oldVal]->Flush(time); } else //bitmask mode { int changed = mRouteMask ^ oldVal; int removed = changed & oldVal; for (int i = 0; i <= int(log2(removed)); ++i) { if (1 & (removed >> i)) { if (i < (int)mDestinationCables.size()) mDestinationCables[i]->Flush(time); } } } } } void NoteRouter::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { INoteSource::PostRepatch(cableSource, fromUserClick); for (int i = 0; i < (int)mDestinationCables.size(); ++i) { if (cableSource == mDestinationCables[i]->GetPatchCableSource()) { IClickable* target = cableSource->GetTarget(); std::string name = target ? target->Name() : " "; mRouteSelector->SetLabel(name.c_str(), i); } } } void NoteRouter::GetModuleDimensions(float& width, float& height) { float w, h; mRouteSelector->GetDimensions(w, h); width = 20 + w; height = 8 + h; } void NoteRouter::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadInt("num_items", moduleInfo, 2, 1, 99, K(isTextField)); mModuleSaveData.LoadBool("radiobuttonmode", moduleInfo, true); mModuleSaveData.LoadBool("only_show_active_cables", moduleInfo, false); SetUpFromSaveData(); } void NoteRouter::SetUpFromSaveData() { int numItems = mModuleSaveData.GetInt("num_items"); int oldNumItems = (int)mDestinationCables.size(); if (numItems > oldNumItems) { for (int i = oldNumItems; i < numItems; ++i) { mRouteSelector->AddLabel(" ", i); auto* additionalCable = new AdditionalNoteCable(); additionalCable->SetPatchCableSource(new PatchCableSource(this, kConnectionType_Note)); AddPatchCableSource(additionalCable->GetPatchCableSource()); mDestinationCables.push_back(additionalCable); } } else if (numItems < oldNumItems) { for (int i = oldNumItems - 1; i >= numItems; --i) { mRouteSelector->RemoveLabel(i); RemovePatchCableSource(mDestinationCables[i]->GetPatchCableSource()); } mDestinationCables.resize(numItems); } mRadioButtonMode = mModuleSaveData.GetBool("radiobuttonmode"); mRouteSelector->SetMultiSelect(!mRadioButtonMode); mOnlyShowActiveCables = mModuleSaveData.GetBool("only_show_active_cables"); } void NoteRouter::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["num_items"] = (int)mDestinationCables.size(); } ```
/content/code_sandbox/Source/NoteRouter.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,299
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // GridController.cpp // Bespoke // // Created by Ryan Challinor on 2/9/15. // // #include "GridController.h" #include "ModularSynth.h" #include "PatchCableSource.h" GridControlTarget::GridControlTarget(IGridControllerListener* owner, const char* name, int x, int y) : mOwner(owner) { SetName(name); SetPosition(x, y); dynamic_cast<IDrawableModule*>(owner)->AddUIControl(this); SetParent(dynamic_cast<IClickable*>(owner)); } void GridControlTarget::Render() { ofPushStyle(); ofNoFill(); ofSetLineWidth(2); ofSetColor(200, 200, 200, gModuleDrawAlpha); ofCircle(mX + 6, mY + 8, 5); DrawGridIcon(mX + 15, mY + 2); DrawPatchCableHover(); ofPopStyle(); } //static void GridControlTarget::DrawGridIcon(float x, float y) { ofPushStyle(); ofSetLineWidth(1); float gridSize = 12; ofRect(x, y, gridSize, gridSize, 0); ofRect(x + gridSize / 3, y, gridSize / 3, 12, 0); ofRect(x, y + gridSize / 3, 12, gridSize / 3, 0); ofPopStyle(); } bool GridControlTarget::CanBeTargetedBy(PatchCableSource* source) const { return source->GetConnectionType() == kConnectionType_Grid; } bool GridControlTarget::MouseMoved(float x, float y) { CheckHover(x, y); return false; } namespace { const int kSaveStateRev = 1; } void GridControlTarget::SaveState(FileStreamOut& out) { out << kSaveStateRev; } void GridControlTarget::LoadState(FileStreamIn& in, bool shouldSetValue) { int rev; in >> rev; LoadStateValidate(rev <= kSaveStateRev); } //---------------- GridControllerMidi::GridControllerMidi() { } void GridControllerMidi::OnControllerPageSelected() { mOwner->OnControllerPageSelected(); for (int i = 0; i < mCols; ++i) { for (int j = 0; j < mRows; ++j) { SetLightDirect(i, j, mLights[i][j], K(force)); } } } void GridControllerMidi::OnInput(int control, float velocity) { int x = 0; int y = 0; bool found = false; for (x = 0; x < mCols; ++x) { for (y = 0; y < mRows; ++y) { if (mControls[x][y] == control) { found = true; break; } } if (found) break; } if (found) { mInput[x][y] = velocity; if (mOwner) mOwner->OnGridButton(x, y, velocity, this); } } bool GridControllerMidi::HasInput() const { for (int i = 0; i < mCols; ++i) { for (int j = 0; j < mRows; ++j) { if (mInput[i][j] > 0) { return true; } } } return false; } void GridControllerMidi::SetLight(int x, int y, GridColor color, bool force) { if (x >= mCols || y >= mRows) return; int colorIdx = (int)color; int rawColor = 0; if (mColors.size()) { if (colorIdx >= mColors.size()) //we don't have this many colors { while (colorIdx >= mColors.size()) colorIdx -= 2; //move back by two to retain bright/dimness if (colorIdx <= 0) colorIdx = 1; //never set a non-off light to "off" } rawColor = mColors[colorIdx]; } else { rawColor = colorIdx > 0 ? 127 : 0; } SetLightDirect(x, y, rawColor, force); } void GridControllerMidi::SetLightDirect(int x, int y, int color, bool force) { if (mLights[x][y] != color || force) { if (mMidiController) { if (mMessageType == kMidiMessage_Note) mMidiController->SendNote(mControllerPage, mControls[x][y], color); else if (mMessageType == kMidiMessage_Control) mMidiController->SendCC(mControllerPage, mControls[x][y], color); } mLights[x][y] = color; } } void GridControllerMidi::ResetLights() { for (int i = 0; i < mCols; ++i) { for (int j = 0; j < mRows; ++j) { SetLight(i, j, kGridColorOff); } } } void GridControllerMidi::SetUp(GridLayout* layout, int page, MidiController* controller) { mRows = layout->mRows; mCols = layout->mCols; for (unsigned int row = 0; row < mRows; ++row) { for (unsigned int col = 0; col < mCols; ++col) { int index = col + row * mCols; mControls[col][row] = layout->mControls[index]; } } mColors = layout->mColors; mMessageType = layout->mType; mMidiController = controller; mControllerPage = page; OnControllerPageSelected(); } void GridControllerMidi::UnhookController() { mMidiController = nullptr; } ```
/content/code_sandbox/Source/GridController.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,422
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // NoteEffectBase.h // Bespoke // // Created by Ryan Challinor on 6/17/15. // // #pragma once #include "INoteReceiver.h" #include "INoteSource.h" class NoteEffectBase : public INoteReceiver, public INoteSource { public: void PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) override { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void SendCC(int control, int value, int voiceIdx = -1) override { SendCCOutput(control, value, voiceIdx); } }; ```
/content/code_sandbox/Source/NoteEffectBase.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
239
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // PreviousNote.cpp // Bespoke // // Created by Ryan Challinor on 1/4/16. // // #include "PreviousNote.h" #include "SynthGlobals.h" PreviousNote::PreviousNote() { } void PreviousNote::DrawModule() { if (Minimized() || IsVisible() == false) return; } void PreviousNote::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (!mEnabled) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); return; } if (velocity > 0) { if (mPitch != -1) { PlayNoteOutput(time, mPitch, mVelocity, voiceIdx, modulation); } mPitch = pitch; mVelocity = velocity; } else { mNoteOutput.Flush(time); } } void PreviousNote::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void PreviousNote::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/PreviousNote.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
353
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== PulseRouter.h Created: 31/03/2024 Author: Ryan Challinor / ArkyonVeil ============================================================================== */ #pragma once #include <iostream> #include "IDrawableModule.h" #include "INoteSource.h" #include "RadioButton.h" class PulseRouter : public IPulseReceiver, public IPulseSource, public IDrawableModule, public IRadioButtonListener { public: PulseRouter(); static IDrawableModule* Create() { return new PulseRouter(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return true; } void CreateUIControls() override; void Poll() override; void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; void SetActiveIndex(int index) { mRouteMask = 1 << index; } void SetSelectedMask(int mask); //INoteReceiver void OnPulse(double time, float velocity, int flags) override; //IRadioButtonListener void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; virtual void SaveLayout(ofxJSONElement& moduleInfo) override; bool IsEnabled() const override { return true; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; bool IsIndexActive(int idx) const; int mRouteMask{ 0 }; RadioButton* mRouteSelector{ nullptr }; std::vector<PatchCableSource*> mDestinationCables; bool mRadioButtonMode{ false }; bool mOnlyShowActiveCables{ false }; }; ```
/content/code_sandbox/Source/PulseRouter.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
501
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== SpectralDisplay.cpp Created: 14 Nov 2019 10:39:24am Author: Ryan Challinor ============================================================================== */ #include "SpectralDisplay.h" #include "ModularSynth.h" #include "Profiler.h" namespace { const int kNumFFTBins = 1024; const int kBinIgnore = 2; }; SpectralDisplay::SpectralDisplay() : IAudioProcessor(gBufferSize) , mFFT(kNumFFTBins) , mFFTData(kNumFFTBins, kNumFFTBins / 2 + 1) , mRollingInputBuffer(kNumFFTBins) { // Generate a window with a single raised cosine from N/4 to 3N/4 mWindower = new float[kNumFFTBins]; for (int i = 0; i < kNumFFTBins; ++i) mWindower[i] = -.5f * cos(FTWO_PI * i / kNumFFTBins) + .5f; mSmoother = new float[kNumFFTBins / 2 + 1 - kBinIgnore]; for (int i = 0; i < kNumFFTBins / 2 + 1 - kBinIgnore; ++i) mSmoother[i] = 0; } void SpectralDisplay::CreateUIControls() { IDrawableModule::CreateUIControls(); } SpectralDisplay::~SpectralDisplay() { delete[] mWindower; delete[] mSmoother; } void SpectralDisplay::Process(double time) { PROFILER(SpectralDisplay); SyncBuffers(); if (mEnabled) { ComputeSliders(0); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { if (ch == 0) BufferCopy(gWorkBuffer, GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize()); else Add(gWorkBuffer, GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize()); } mRollingInputBuffer.WriteChunk(gWorkBuffer, GetBuffer()->BufferSize(), 0); //copy rolling input buffer into working buffer and window it mRollingInputBuffer.ReadChunk(mFFTData.mTimeDomain, kNumFFTBins, 0, 0); Mult(mFFTData.mTimeDomain, mWindower, kNumFFTBins); mFFT.Forward(mFFTData.mTimeDomain, mFFTData.mRealValues, mFFTData.mImaginaryValues); } IAudioReceiver* target = GetTarget(); if (target) { ChannelBuffer* out = target->GetBuffer(); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { Add(out->GetChannel(ch), GetBuffer()->GetChannel(ch), out->BufferSize()); GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize(), ch); } } GetBuffer()->Reset(); } void SpectralDisplay::DrawModule() { if (Minimized() || IsVisible() == false || !mEnabled) return; ofPushStyle(); ofPushMatrix(); float w, h; GetDimensions(w, h); ofSetColor(255, 255, 255); ofSetLineWidth(1); //raw int end = kNumFFTBins / 2 + 1; ofBeginShape(); for (int i = kBinIgnore; i < end; i++) { float x = sqrtf(float(i - kBinIgnore) / (end - kBinIgnore - 1)) * w; float samp = sqrtf(fabsf(mFFTData.mRealValues[i]) / end) * 3; float y = ofClamp(samp, 0, 1) * h; ofVertex(x, h - y); mSmoother[i - kBinIgnore] = ofLerp(mSmoother[i - kBinIgnore], samp, .1f); } ofEndShape(false); ofSetColor(245, 58, 135); ofSetLineWidth(3); //smoothed ofBeginShape(); for (int i = kBinIgnore; i < end; i++) { float x = sqrtf(float(i - kBinIgnore) / (end - kBinIgnore - 1)) * w; float y = ofClamp(mSmoother[i - kBinIgnore], 0, 1) * h; ofVertex(x, h - y); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); } void SpectralDisplay::Resize(float w, float h) { mWidth = w; mHeight = h; mModuleSaveData.SetInt("width", w); mModuleSaveData.SetInt("height", h); } void SpectralDisplay::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadInt("width", moduleInfo, 600, 50, 2000, K(isTextField)); mModuleSaveData.LoadInt("height", moduleInfo, 100, 50, 2000, K(isTextField)); SetUpFromSaveData(); } void SpectralDisplay::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["width"] = mWidth; moduleInfo["height"] = mHeight; } void SpectralDisplay::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); mWidth = mModuleSaveData.GetInt("width"); mHeight = mModuleSaveData.GetInt("height"); } ```
/content/code_sandbox/Source/SpectralDisplay.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,346
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== RadioSequencer.h Created: 10 Jun 2017 4:53:13pm Author: Ryan Challinor ============================================================================== */ #pragma once #include <iostream> #include "IDrawableModule.h" #include "UIGrid.h" #include "Checkbox.h" #include "Transport.h" #include "DropdownList.h" #include "GridController.h" #include "Slider.h" #include "IPulseReceiver.h" #include "INoteReceiver.h" #include "IDrivableSequencer.h" class PatchCableSource; class RadioSequencer : public IDrawableModule, public ITimeListener, public IDropdownListener, public UIGridListener, public IGridControllerListener, public IIntSliderListener, public IPulseReceiver, public INoteReceiver, public IDrivableSequencer { public: RadioSequencer(); ~RadioSequencer(); static IDrawableModule* Create() { return new RadioSequencer(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return true; } void CreateUIControls() override; //IGridListener void GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) override; //IDrawableModule void Init() override; void Poll() override; bool IsResizable() const override { return true; } void Resize(float w, float h) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //ITimeListener void OnTimeEvent(double time) override; //IPulseReceiver void OnPulse(double time, float velocity, int flags) override; //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; void SendCC(int control, int value, int voiceIdx = -1) override {} //IGridControllerListener void OnControllerPageSelected() override; void OnGridButton(int x, int y, float velocity, IGridController* grid) override; //IDrivableSequencer bool HasExternalPulseSource() const override { return mHasExternalPulseSource; } void ResetExternalPulseSource() override { mHasExternalPulseSource = false; } void CheckboxUpdated(Checkbox* checkbox, double time) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SaveLayout(ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 2; } bool LoadOldControl(FileStreamIn& in, std::string& oldName) override; //IPatchable void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; bool IsEnabled() const override { return mEnabled; } private: void Step(double time, int pulseFlags); void SetGridSize(float w, float h); void SyncControlCablesToGrid(); void UpdateGridLights(); //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override; void OnClicked(float x, float y, bool right) override; bool MouseMoved(float x, float y) override; void MouseReleased() override; UIGrid* mGrid{ nullptr }; NoteInterval mInterval{ kInterval_1n }; DropdownList* mIntervalSelector{ nullptr }; int mLength{ 4 }; IntSlider* mLengthSlider{ nullptr }; std::string mOldLengthStr; std::vector<PatchCableSource*> mControlCables; GridControlTarget* mGridControlTarget{ nullptr }; bool mHasExternalPulseSource{ false }; int mStep{ 0 }; int mLoadRev{ -1 }; bool mDisableAllWhenDisabled{ true }; TransportListenerInfo* mTransportListenerInfo{ nullptr }; }; ```
/content/code_sandbox/Source/RadioSequencer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,050
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // DebugAudioSource.cpp // Bespoke // // Created by Ryan Challinor on 7/1/14. // // #include "DebugAudioSource.h" #include "IAudioReceiver.h" #include "ModularSynth.h" #include "Profiler.h" DebugAudioSource::DebugAudioSource() { } DebugAudioSource::~DebugAudioSource() { } void DebugAudioSource::Process(double time) { PROFILER(DebugAudioSource); IAudioReceiver* target = GetTarget(); if (!mEnabled || target == nullptr) return; int bufferSize = target->GetBuffer()->BufferSize(); float* out = target->GetBuffer()->GetChannel(0); assert(bufferSize == gBufferSize); for (int i = 0; i < bufferSize; ++i) { float sample = 1; out[i] += sample; GetVizBuffer()->Write(sample, 0); } } void DebugAudioSource::DrawModule() { if (Minimized() || IsVisible() == false) return; } void DebugAudioSource::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void DebugAudioSource::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); } ```
/content/code_sandbox/Source/DebugAudioSource.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
386
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // EQEffect.h // Bespoke // // Created by Ryan Challinor on 12/26/14. // // #pragma once #include "IAudioEffect.h" #include "DropdownList.h" #include "Checkbox.h" #include "Slider.h" #include "BiquadFilter.h" #include "RadioButton.h" #include "UIGrid.h" #include "ClickButton.h" #define NUM_EQ_FILTERS 8 class EQEffect : public IAudioEffect, public IDropdownListener, public IIntSliderListener, public IRadioButtonListener, public IButtonListener, public UIGridListener { public: EQEffect(); ~EQEffect(); static IAudioEffect* Create() { return new EQEffect(); } void CreateUIControls() override; void Init() override; //IAudioEffect void ProcessAudio(double time, ChannelBuffer* buffer) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } float GetEffectAmount() override; std::string GetType() override { return "basiceq"; } void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; void RadioButtonUpdated(RadioButton* list, int oldVal, double time) override; void ButtonClicked(ClickButton* button, double time) override; void GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) override; bool IsEnabled() const override { return mEnabled; } void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 0; } private: //IDrawableModule void GetModuleDimensions(float& width, float& height) override; void DrawModule() override; void OnClicked(float x, float y, bool right) override; bool MouseMoved(float x, float y) override; void MouseReleased() override; struct FilterBank { BiquadFilter mBiquad[NUM_EQ_FILTERS]{}; }; FilterBank mBanks[ChannelBuffer::kMaxNumChannels]{}; int mNumFilters{ NUM_EQ_FILTERS }; UIGrid* mMultiSlider{ nullptr }; ClickButton* mEvenButton{ nullptr }; }; ```
/content/code_sandbox/Source/EQEffect.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
622
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // FourOnTheFloor.h // modularSynth // // Created by Ryan Challinor on 6/23/13. // // #pragma once #include <iostream> #include "IDrawableModule.h" #include "INoteSource.h" #include "Transport.h" #include "Checkbox.h" class FourOnTheFloor : public IDrawableModule, public INoteSource, public ITimeListener { public: FourOnTheFloor(); ~FourOnTheFloor(); static IDrawableModule* Create() { return new FourOnTheFloor(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Init() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //ITimeListener void OnTimeEvent(double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = 120; height = 22; } bool mTwoOnTheFloor{ false }; Checkbox* mTwoOnTheFloorCheckbox{ nullptr }; }; ```
/content/code_sandbox/Source/FourOnTheFloor.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
422
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== EnvelopeEditor.h Created: 9 Nov 2017 5:20:48pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "RadioButton.h" #include "Slider.h" #include "ClickButton.h" #include "DropdownList.h" #include "ADSR.h" #include "ADSRDisplay.h" class EnvelopeControl { public: EnvelopeControl(ofVec2f position, ofVec2f dimensions); void SetADSR(::ADSR* adsr) { mAdsr = adsr; } void OnClicked(float x, float y, bool right); void MouseMoved(float x, float y); void MouseReleased(); void Draw(); void SetViewLength(float length) { mViewLength = length; } ofVec2f GetPosition() const { return mPosition; } ofVec2f GetDimensions() const { return mDimensions; } void SetPosition(ofVec2f pos) { mPosition = pos; } void SetDimensions(ofVec2f dim) { mDimensions = dim; } void SetFixedLengthMode(bool fixed) { mFixedLengthMode = fixed; } private: void AddVertex(float x, float y); float GetPreSustainTime(); float GetReleaseTime(); float GetTimeForX(float x); float GetValueForY(float y); float GetXForTime(float time); float GetYForValue(float value); ofVec2f mPosition; ofVec2f mDimensions; ::ADSR* mAdsr{ nullptr }; ::ADSR mClickAdsr; bool mClick{ false }; ofVec2f mClickStart; float mViewLength{ 2000 }; int mHighlightPoint{ -1 }; int mHighlightCurve{ -1 }; double mLastClickTime{ 0 }; bool mFixedLengthMode{ false }; }; class EnvelopeEditor : public IDrawableModule, public IRadioButtonListener, public IFloatSliderListener, public IButtonListener, public IDropdownListener, public IIntSliderListener { public: EnvelopeEditor(); static IDrawableModule* Create() { return new EnvelopeEditor(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void Delete() { delete this; } void DrawModule() override; void SetEnabled(bool enabled) override {} //don't use this one bool IsEnabled() const override { return true; } bool HasTitleBar() const override { return mPinned; } bool IsSaveable() override { return mPinned; } void CreateUIControls() override; void MouseReleased() override; bool MouseMoved(float x, float y) override; bool IsResizable() const override { return true; } void Resize(float w, float h) override; bool IsPinned() const { return mPinned; } void SetADSRDisplay(ADSRDisplay* adsrDisplay); bool HasSpecialDelete() const override { return true; } void DoSpecialDelete() override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override {} void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override {} void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void ButtonClicked(ClickButton* button, double time) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override {} void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } void SaveLayout(ofxJSONElement& moduleInfo) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; protected: ~EnvelopeEditor(); private: void OnClicked(float x, float y, bool right) override; void Pin(); struct StageControls { FloatSlider* mTargetSlider{ nullptr }; FloatSlider* mTimeSlider{ nullptr }; FloatSlider* mCurveSlider{ nullptr }; Checkbox* mSustainCheckbox{ nullptr }; bool mIsSustainStage{ false }; }; EnvelopeControl mEnvelopeControl; float mWidth{ 320 }; float mHeight{ 210 }; ADSRDisplay* mADSRDisplay{ nullptr }; ClickButton* mPinButton{ nullptr }; bool mPinned{ false }; FloatSlider* mADSRViewLengthSlider{ nullptr }; FloatSlider* mMaxSustainSlider{ nullptr }; Checkbox* mFreeReleaseLevelCheckbox{ nullptr }; PatchCableSource* mTargetCable{ nullptr }; std::array<StageControls, 10> mStageControls{}; }; ```
/content/code_sandbox/Source/EnvelopeEditor.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,168
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== IAudioProcessor.h Created: 15 Oct 2017 10:24:40am Author: Ryan Challinor ============================================================================== */ #pragma once #include "IAudioReceiver.h" #include "IAudioSource.h" class IAudioProcessor : public IAudioReceiver, public IAudioSource { public: IAudioProcessor(int bufferSize) : IAudioReceiver(bufferSize) {} protected: void SyncBuffers(int overrideNumOutputChannels = -1); }; ```
/content/code_sandbox/Source/IAudioProcessor.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
203
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== MultitapDelay.h Created: 25 Nov 2018 11:16:38am Author: Ryan Challinor ============================================================================== */ #pragma once #include "IAudioProcessor.h" #include "EnvOscillator.h" #include "IDrawableModule.h" #include "Slider.h" #include "DropdownList.h" #include "ClickButton.h" #include "INoteReceiver.h" #include "Granulator.h" #include "ADSR.h" class Sample; class MultitapDelay : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public IDropdownListener, public IButtonListener, public INoteReceiver { public: MultitapDelay(); ~MultitapDelay(); static IDrawableModule* Create() { return new MultitapDelay(); } static bool AcceptsAudio() { return true; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; void SendCC(int control, int value, int voiceIdx = -1) override {} //IAudioSource void Process(double time) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //IClickable void MouseReleased() override; bool MouseMoved(float x, float y) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; //IFloatSliderListener void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; //IFloatSliderListener void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; //IDropdownListener void DropdownClicked(DropdownList* list) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; //IButtonListener void ButtonClicked(ClickButton* button, double time) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 0; } bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; void OnClicked(float x, float y, bool right) override; struct DelayTap { DelayTap(); void Process(float* sampleOut, int offset, int ch); void Draw(float w, float h); float mDelayMs{ 100 }; float mGain{ 0 }; float mFeedback{ 0 }; float mPan{ 0 }; MultitapDelay* mOwner{ nullptr }; FloatSlider* mDelayMsSlider{ nullptr }; FloatSlider* mGainSlider{ nullptr }; FloatSlider* mFeedbackSlider{ nullptr }; FloatSlider* mPanSlider{ nullptr }; ChannelBuffer mTapBuffer; }; struct DelayMPETap { void Process(float* sampleOut, int offset, int ch); void Draw(float w, float h); float mPitch{ 0 }; ModulationChain* mPitchBend{ nullptr }; ModulationChain* mPressure{ nullptr }; ModulationChain* mModWheel{ nullptr }; ::ADSR mADSR{ 100, 0, 1, 100 }; MultitapDelay* mOwner{ nullptr }; }; int mNumTaps{ 4 }; std::vector<DelayTap> mTaps; static const int kNumMPETaps = 16; DelayMPETap mMPETaps[kNumMPETaps]; ChannelBuffer mWriteBuffer; FloatSlider* mDryAmountSlider{ nullptr }; float mDryAmount{ 1 }; FloatSlider* mDisplayLengthSlider{ nullptr }; float mDisplayLength{ 10 }; RollingBuffer mDelayBuffer; }; ```
/content/code_sandbox/Source/MultitapDelay.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,026
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // EventCanvas.cpp // Bespoke // // Created by Ryan Challinor on 12/28/15. // // #include "EventCanvas.h" #include "SynthGlobals.h" #include "DrumPlayer.h" #include "ModularSynth.h" #include "CanvasControls.h" #include "Scale.h" #include "CanvasElement.h" #include "Profiler.h" #include "PatchCableSource.h" #include "CanvasScrollbar.h" EventCanvas::EventCanvas() { mRowColors.push_back(ofColor::red); mRowColors.push_back(ofColor::green); mRowColors.push_back(ofColor::blue); mRowColors.push_back(ofColor::orange); mRowColors.push_back(ofColor::purple); mRowColors.push_back(ofColor::yellow); for (auto& color : mRowColors) { color.setBrightness(color.getBrightness() * .8f); color.setSaturation(color.getSaturation() * .7f); } mRowConnections.resize(kMaxEventRows); } void EventCanvas::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } void EventCanvas::CreateUIControls() { IDrawableModule::CreateUIControls(); mQuantizeButton = new ClickButton(this, "quantize", 160, 5); mNumMeasuresEntry = new TextEntry(this, "measures", 5, 5, 3, &mNumMeasures, 1, 999); mIntervalSelector = new DropdownList(this, "interval", 110, 5, (int*)(&mInterval)); mRecordCheckbox = new Checkbox(this, "record", 220, 5, &mRecord); mNumMeasuresEntry->DrawLabel(true); mIntervalSelector->AddLabel("4", kInterval_4); mIntervalSelector->AddLabel("1n", kInterval_1n); mIntervalSelector->AddLabel("4n", kInterval_4n); mIntervalSelector->AddLabel("4nt", kInterval_4nt); mIntervalSelector->AddLabel("8n", kInterval_8n); mIntervalSelector->AddLabel("8nt", kInterval_8nt); mIntervalSelector->AddLabel("16n", kInterval_16n); mIntervalSelector->AddLabel("16nt", kInterval_16nt); mIntervalSelector->AddLabel("32n", kInterval_32n); mCanvas = new Canvas(this, 5, 45, 390, 100, L(length, 1), L(rows, 8), L(cols, 16), &(EventCanvasElement::Create)); AddUIControl(mCanvas); mCanvasControls = new CanvasControls(); mCanvasControls->SetCanvas(mCanvas); mCanvasControls->CreateUIControls(); mCanvasControls->AllowDragModeSelection(false); AddChild(mCanvasControls); UpdateNumColumns(); mCanvas->SetListener(this); mCanvas->SetDragMode(Canvas::kDragHorizontal); mCanvas->SetNumVisibleRows(8); mCanvasScrollbarHorizontal = new CanvasScrollbar(mCanvas, "scrollh", CanvasScrollbar::Style::kHorizontal); AddUIControl(mCanvasScrollbarHorizontal); SyncControlCablesToCanvas(); } EventCanvas::~EventCanvas() { mCanvas->SetListener(nullptr); TheTransport->RemoveAudioPoller(this); } void EventCanvas::OnTransportAdvanced(float amount) { PROFILER(EventCanvas); if (mCanvas == nullptr) return; //look ahead two buffers so that we set things slightly early, so we'll do things like catch the downbeat right after enabling a sequencer, etc. double lookaheadMsAmount = gBufferSizeMs * 2; double lookaheadTime = gTime + lookaheadMsAmount; double lookaheadPos = DoubleWrap(((TheTransport->GetMeasure(lookaheadTime) % mNumMeasures) + TheTransport->GetMeasurePos(lookaheadTime)) / mNumMeasures, 1); mCanvas->SetCursorPos(lookaheadPos); mPosition = lookaheadPos; double bufferOffsetAmount = gBufferSizeMs / TheTransport->MsPerBar() / mNumMeasures; mPreviousPosition = std::min(mPreviousPosition, lookaheadPos - bufferOffsetAmount); if (!mEnabled) return; for (auto* canvasElement : mCanvas->GetElements()) { float elementStart = canvasElement->GetStart(); bool startPassed = (lookaheadPos >= elementStart && mPreviousPosition < elementStart); float elementEnd = canvasElement->GetEnd(); if (elementEnd > mCanvas->GetLength()) elementEnd = FloatWrap(elementEnd, mCanvas->GetLength()); bool endPassed = (lookaheadPos >= elementEnd && mPreviousPosition < elementEnd); if (startPassed || endPassed) { EventCanvasElement* element = static_cast<EventCanvasElement*>(canvasElement); if (lookaheadPos > elementEnd) { if (startPassed) element->Trigger(GetTriggerTime(lookaheadTime, lookaheadPos, elementStart)); if (endPassed) element->TriggerEnd(GetTriggerTime(lookaheadTime, lookaheadPos, elementEnd)); } else { if (endPassed) element->TriggerEnd(GetTriggerTime(lookaheadTime, lookaheadPos, elementEnd)); if (startPassed) element->Trigger(GetTriggerTime(lookaheadTime, lookaheadPos, elementStart)); } IUIControl* control = mRowConnections[element->mRow].mUIControl; if (control) mRowConnections[element->mRow].mLastValue = control->GetValue(); } } for (int i = 0; i < mControlCables.size(); ++i) { if (mRowConnections[i].mUIControl) { float value = mRowConnections[i].mUIControl->GetValue(); if (mRecord && mRowConnections[i].mLastValue != value) { float colPos = lookaheadPos * mCanvas->GetNumCols(); int col = int(colPos + .5f); EventCanvasElement* element = new EventCanvasElement(mCanvas, col, i, colPos - col); element->SetUIControl(mRowConnections[i].mUIControl); element->SetValue(value); mCanvas->AddElement(element); } mRowConnections[i].mLastValue = value; } } mPreviousPosition = lookaheadPos; } double EventCanvas::GetTriggerTime(double lookaheadTime, double lookaheadPos, float eventPos) { double cursorAdvanceSinceEvent = lookaheadPos - eventPos; if (cursorAdvanceSinceEvent < 0) cursorAdvanceSinceEvent += 1; double time = lookaheadTime - cursorAdvanceSinceEvent * TheTransport->MsPerBar() * mNumMeasures; if (time < gTime) time = gTime; return time; } void EventCanvas::UpdateNumColumns() { if (TheTransport->GetDuration(mInterval) < TheTransport->GetDuration(kInterval_1n)) { mCanvas->RescaleNumCols(TheTransport->CountInStandardMeasure(mInterval) * mNumMeasures); mCanvas->SetMajorColumnInterval(TheTransport->CountInStandardMeasure(mInterval) / 4); } else { mCanvas->RescaleNumCols(TheTransport->GetDuration(kInterval_1n) / TheTransport->GetDuration(mInterval) * mNumMeasures); mCanvas->SetMajorColumnInterval(-1); } } IUIControl* EventCanvas::GetUIControlForRow(int row) { return mRowConnections[row].mUIControl; } ofColor EventCanvas::GetRowColor(int row) const { return mRowColors[row % mRowColors.size()]; } void EventCanvas::CanvasUpdated(Canvas* canvas) { if (canvas == mCanvas) { } } void EventCanvas::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { for (int i = 0; i < mControlCables.size(); ++i) { mRowConnections[i].mUIControl = dynamic_cast<IUIControl*>(mControlCables[i]->GetTarget()); if (mRowConnections[i].mUIControl) mRowConnections[i].mLastValue = mRowConnections[i].mUIControl->GetValue(); } for (auto canvasElement : mCanvas->GetElements()) { EventCanvasElement* element = static_cast<EventCanvasElement*>(canvasElement); int row = element->mRow; element->SetUIControl(GetUIControlForRow(row)); } } void EventCanvas::DrawModule() { if (Minimized() || IsVisible() == false) return; ofPushStyle(); ofFill(); for (int i = 0; i < mCanvas->GetNumVisibleRows(); ++i) { ofColor color = GetRowColor(i + mCanvas->GetRowOffset()); color.a = 50; ofSetColor(color); float boxHeight = (float(mCanvas->GetHeight()) / mCanvas->GetNumVisibleRows()); float y = mCanvas->GetPosition(true).y + i * boxHeight; ofRect(mCanvas->GetPosition(true).x, y, mCanvas->GetWidth(), boxHeight); } ofPopStyle(); ofPushStyle(); ofSetColor(128, 128, 128); mCanvas->Draw(); ofPopStyle(); mCanvasScrollbarHorizontal->Draw(); mCanvasControls->Draw(); mQuantizeButton->Draw(); mNumMeasuresEntry->Draw(); mIntervalSelector->Draw(); mRecordCheckbox->Draw(); ofRectangle canvasRect = mCanvas->GetRect(true); for (int i = 0; i < mControlCables.size(); ++i) { if (mCanvas->IsRowVisible(i)) { mControlCables[i]->SetManualPosition(GetRect().width, canvasRect.y + (canvasRect.height / mCanvas->GetNumVisibleRows()) * (i - mCanvas->GetRowOffset() + .5f)); mControlCables[i]->SetEnabled(true); } else { mControlCables[i]->SetEnabled(false); } } } void EventCanvas::SyncControlCablesToCanvas() { if (mCanvas->GetNumRows() == mControlCables.size()) return; //nothing to do if (mCanvas->GetNumRows() > mControlCables.size()) { int oldSize = (int)mControlCables.size(); mControlCables.resize(mCanvas->GetNumRows()); for (int i = oldSize; i < mControlCables.size(); ++i) { mControlCables[i] = new PatchCableSource(this, kConnectionType_UIControl); mControlCables[i]->SetOverrideCableDir(ofVec2f(1, 0), PatchCableSource::Side::kRight); mControlCables[i]->SetColor(GetRowColor(i)); AddPatchCableSource(mControlCables[i]); } } else { for (int i = mCanvas->GetNumRows(); i < mControlCables.size(); ++i) RemovePatchCableSource(mControlCables[i]); mControlCables.resize(mCanvas->GetNumRows()); } } namespace { const float extraW = 10; const float extraH = 150; } void EventCanvas::Resize(float w, float h) { w = MAX(w - extraW, 390); h = MAX(h - extraH, 100); mCanvas->SetDimensions(w, h); } void EventCanvas::GetModuleDimensions(float& width, float& height) { width = mCanvas->GetWidth() + extraW; height = mCanvas->GetHeight() + extraH; } void EventCanvas::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) { mPreviousPosition = mPosition + .001f; } } void EventCanvas::ButtonClicked(ClickButton* button, double time) { if (button == mQuantizeButton) { bool anyHighlighted = false; for (auto* element : mCanvas->GetElements()) { if (element->GetHighlighted()) { anyHighlighted = true; break; } } for (auto* element : mCanvas->GetElements()) { if (anyHighlighted == false || element->GetHighlighted()) { element->mCol = int(element->mCol + element->mOffset + .5f) % mCanvas->GetNumCols(); element->mOffset = 0; } } } } void EventCanvas::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void EventCanvas::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void EventCanvas::TextEntryComplete(TextEntry* entry) { if (entry == mNumMeasuresEntry) { mCanvas->SetNumCols(TheTransport->CountInStandardMeasure(mInterval) * mNumMeasures); } } void EventCanvas::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mIntervalSelector) { UpdateNumColumns(); } } void EventCanvas::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadFloat("canvaswidth", moduleInfo, 390, 390, 99999, K(isTextField)); mModuleSaveData.LoadFloat("canvasheight", moduleInfo, 100, 40, 99999, K(isTextField)); mModuleSaveData.LoadInt("num_rows", moduleInfo, 8, 1, 999, K(isTextField)); SetUpFromSaveData(); } void EventCanvas::SetUpFromSaveData() { mCanvas->SetDimensions(mModuleSaveData.GetFloat("canvaswidth"), mModuleSaveData.GetFloat("canvasheight")); assert(mModuleSaveData.GetInt("num_rows") <= kMaxEventRows); mCanvas->SetNumRows(mModuleSaveData.GetInt("num_rows")); SyncControlCablesToCanvas(); } void EventCanvas::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["canvaswidth"] = mCanvas->GetWidth(); moduleInfo["canvasheight"] = mCanvas->GetHeight(); } void EventCanvas::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); out << (int)mControlCables.size(); for (auto cable : mControlCables) { std::string path = ""; if (cable->GetTarget()) path = cable->GetTarget()->Path(); out << path; } mCanvas->SaveState(out); } void EventCanvas::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); int size; in >> size; mControlCables.resize(size); for (auto cable : mControlCables) { std::string path; in >> path; cable->SetTarget(TheSynth->FindUIControl(path)); } mCanvas->LoadState(in); } std::vector<IUIControl*> EventCanvas::ControlsToIgnoreInSaveState() const { std::vector<IUIControl*> ignore; ignore.push_back(mCanvas); return ignore; } ```
/content/code_sandbox/Source/EventCanvas.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
3,505
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== Push2Control.h Created: 24 Feb 2020 8:57:57pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "MidiDevice.h" #include "MidiController.h" #include "TitleBar.h" #include "DropdownList.h" class NVGcontext; class NVGLUframebuffer; class IUIControl; class IPush2GridController; class Snapshots; class ControlRecorder; class Push2Control : public IDrawableModule, public MidiDeviceListener, public IDropdownListener { public: Push2Control(); virtual ~Push2Control(); static IDrawableModule* Create() { return new Push2Control(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Poll() override; void Exit() override; void KeyPressed(int key, bool isRepeat) override; void SetLed(MidiMessageType type, int index, int color, int flashColor = -1); void SetDisplayModule(IDrawableModule* module, bool addToHistory = true); IDrawableModule* GetDisplayModule() const { return mDisplayModule; } void OnMidiNote(MidiNote& note) override; void OnMidiControl(MidiControl& control) override; void OnMidiPitchBend(MidiPitchBend& pitchBend) override; MidiDevice* GetDevice() { return &mDevice; } void DropdownUpdated(DropdownList* list, int oldVal, double time) override {} void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; void SaveLayout(ofxJSONElement& moduleInfo) override; int GetModuleSaveStateRev() const override { return 1; } int GetGridControllerOption1Control() const; int GetGridControllerOption2Control() const; static bool sDrawingPush2Display; static NVGcontext* sVG; static NVGLUframebuffer* sFB; static void CreateStaticFramebuffer(); //windows was having trouble creating a nanovg context and fbo on the fly static IUIControl* sBindToUIControl; bool IsEnabled() const override { return true; } private: //IDrawableModule void DrawModule() override; void DrawModuleUnclipped() override; void PostRender() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight + (mShowManualGrid ? 98 : 0); } void OnClicked(float x, float y, bool right) override; bool Initialize(); void DrawToFramebuffer(NVGcontext* vg, NVGLUframebuffer* fb, float t, float pxRatio); void RenderPush2Display(); void SetModuleGridLights(); void DrawDisplayModuleControls(); void DrawLowerModuleSelector(); void DrawRoutingDisplay(); void DrawControls(std::vector<IUIControl*> controls, bool sliders, float yPos); void UpdateControlList(); void AddFavoriteControl(IUIControl* control); void RemoveFavoriteControl(IUIControl* control); void BookmarkModuleToSlot(int slotIndex, IDrawableModule* module); void SwitchToBookmarkedModule(int slotIndex); int GetPadColorForType(ModuleCategory type, bool enabled) const; bool GetGridIndex(int gridX, int gridY, int& gridIndex) const { gridIndex = gridX + gridY * 8; return gridX >= 0 && gridX < 8 && gridY >= 0 && gridY < 8; } bool IsIgnorableModule(IDrawableModule* module); std::vector<IDrawableModule*> SortModules(std::vector<IDrawableModule*> modules); void AddModuleChain(IDrawableModule* module, std::vector<IDrawableModule*>& modules, std::vector<IDrawableModule*>& output, int depth); void DrawDisplayModuleRect(ofRectangle rect, float thickness); std::string GetModuleTypeToSpawn(); ModuleCategory GetModuleTypeForSpawnList(IUIControl* control); ofColor GetSpawnGridColor(int index, ModuleCategory moduleType) const; int GetSpawnGridPadColor(int index, ModuleCategory moduleType) const; int GetNumDisplayPixels() const; bool AllowRepatch() const; void UpdateRoutingModules(); void SetGridControlInterface(IPush2GridController* controller, IDrawableModule* module); unsigned char* mPixels{ nullptr }; const int kPixelRatio = 1; const float kColumnSpacing = 121; int mFontHandle{ 0 }; int mFontHandleBold{ 0 }; float mWidth{ 100 }; float mHeight{ 20 }; IDrawableModule* mDisplayModule{ nullptr }; Snapshots* mDisplayModuleSnapshots{ nullptr }; ControlRecorder* mCurrentControlRecorder{ nullptr }; std::vector<IUIControl*> mSliderControls; std::vector<IUIControl*> mButtonControls; std::vector<IUIControl*> mDisplayedControls; bool mDisplayModuleIsShowingOverrideControls{ false }; int mModuleViewOffset{ 0 }; float mModuleViewOffsetSmoothed{ 0 }; std::vector<IDrawableModule*> mModules; float mModuleListOffset{ 0 }; float mModuleListOffsetSmoothed{ 0 }; std::array<IDrawableModule*, 8 * 8> mModuleGrid; std::array<PatchCableSource*, 8 * 8> mModuleGridManualCables; ofRectangle mModuleGridRect; enum class ModuleGridLayoutStyle { Automatic, Manual }; ModuleGridLayoutStyle mModuleGridLayoutStyle{ ModuleGridLayoutStyle::Automatic }; DropdownList* mModuleGridLayoutStyleDropdown{ nullptr }; bool mShowManualGrid{ false }; Checkbox* mShowManualGridCheckbox{ nullptr }; std::vector<IUIControl*> mFavoriteControls; std::vector<IUIControl*> mSpawnModuleControls; bool mNewButtonHeld{ false }; bool mDeleteButtonHeld{ false }; bool mLFOButtonHeld{ false }; bool mAutomateButtonHeld{ false }; bool mAddModuleBookmarkButtonHeld{ false }; std::array<bool, 128> mNoteHeldState; IDrawableModule* mHeldModule{ nullptr }; double mModuleHeldTime{ -1 }; bool mRepatchedHeldModule{ false }; std::vector<IDrawableModule*> mModuleHistory; int mModuleHistoryPosition{ -1 }; std::vector<IDrawableModule*> mBookmarkSlots; bool mInMidiControllerBindMode{ false }; bool mShiftHeld{ false }; bool mAddTrackHeld{ false }; int mHeldKnobIndex{ -1 }; double mLastResetTime{ -1 }; int mHeldModulePatchCableIndex{ 0 }; std::string mTextPopup; double mTextPopupTime{ -1 }; struct Routing { Routing(IDrawableModule* module, ofColor connectionColor) { mModule = module; mConnectionColor = connectionColor; } IDrawableModule* mModule; ofColor mConnectionColor; }; std::vector<Routing> mRoutingInputModules; std::vector<Routing> mRoutingOutputModules; enum class ScreenDisplayMode { kNormal, kAddModule, kMap, kRouting }; ScreenDisplayMode mScreenDisplayMode{ ScreenDisplayMode::kNormal }; IPush2GridController* mGridControlInterface{ nullptr }; IDrawableModule* mGridControlModule{ nullptr }; bool mDisplayModuleCanControlGrid{ false }; int mLedState[128 * 2]{}; //bottom 128 are notes, top 128 are CCs MidiDevice mDevice; SpawnListManager mSpawnLists; int mPendingSpawnPitch{ -1 }; int mSelectedGridSpawnListIndex{ -1 }; std::string mPushBridgeInitErrMsg; }; //path_to_url class IPush2GridController { public: virtual ~IPush2GridController() {} virtual void OnPush2Connect() {} virtual bool OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue) = 0; virtual void UpdatePush2Leds(Push2Control* push2) = 0; }; ```
/content/code_sandbox/Source/Push2Control.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,029
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // PatchCableSource.cpp // Bespoke // // Created by Ryan Challinor on 12/13/15. // // #include "PatchCableSource.h" #include "ModularSynth.h" #include "TitleBar.h" #include "ADSRDisplay.h" #include "INoteReceiver.h" #include "GridController.h" #include "IPulseReceiver.h" #include "AudioSend.h" #include "juce_gui_basics/juce_gui_basics.h" namespace { const int kPatchCableSourceRadius = 5; const int kPatchCableSourceClickRadius = 7; const int kPatchCableSpacing = 8; } bool PatchCableSource::sAllowInsert = true; bool PatchCableSource::sIsLoadingModulePreset = false; PatchCableSource::PatchCableSource(IDrawableModule* owner, ConnectionType type) : mOwner(owner) , mType(type) { mAllowMultipleTargets = (mType == kConnectionType_Note || mType == kConnectionType_Pulse || mType == kConnectionType_Audio || mType == kConnectionType_Modulator || mType == kConnectionType_ValueSetter); SetConnectionType(type); } PatchCableSource::~PatchCableSource() { for (auto cable : mPatchCables) delete cable; } void PatchCableSource::SetConnectionType(ConnectionType type) { mType = type; if (mType == kConnectionType_Note) mColor = IDrawableModule::GetColor(kModuleCategory_Note); else if (mType == kConnectionType_Audio) mColor = IDrawableModule::GetColor(kModuleCategory_Audio); else if (mType == kConnectionType_Modulator) mColor = IDrawableModule::GetColor(kModuleCategory_Modulator); else if (mType == kConnectionType_ValueSetter) { mColor = IDrawableModule::GetColor(kModuleCategory_Modulator); mColor.setSaturation(mColor.getSaturation() * .6f); mColor.setBrightness(mColor.getBrightness() * .7f); } else if (mType == kConnectionType_Pulse) mColor = IDrawableModule::GetColor(kModuleCategory_Pulse); else mColor = IDrawableModule::GetColor(kModuleCategory_Other); mColor.setBrightness(mColor.getBrightness() * .8f); } PatchCable* PatchCableSource::AddPatchCable(IClickable* target) { for (auto cable : mPatchCables) { if (cable != nullptr && cable->GetTarget() == target) return nullptr; } PatchCable* cable = new PatchCable(this); mPatchCables.push_back(cable); if (target) SetPatchCableTarget(cable, target, false); return cable; } void PatchCableSource::SetPatchCableTarget(PatchCable* cable, IClickable* target, bool fromUserClick) { IClickable* oldTarget = cable->GetTarget(); mOwner->PreRepatch(this); if (cable->GetTarget()) { mAudioReceiver = nullptr; RemoveFromVector(dynamic_cast<INoteReceiver*>(cable->GetTarget()), mNoteReceivers); RemoveFromVector(dynamic_cast<IPulseReceiver*>(cable->GetTarget()), mPulseReceivers); } cable->SetCableTarget(target); INoteReceiver* noteReceiver = dynamic_cast<INoteReceiver*>(target); if (noteReceiver) mNoteReceivers.push_back(noteReceiver); IPulseReceiver* pulseReceiver = dynamic_cast<IPulseReceiver*>(target); if (pulseReceiver) mPulseReceivers.push_back(pulseReceiver); IAudioReceiver* audioReceiver = dynamic_cast<IAudioReceiver*>(target); if (audioReceiver) { mAudioReceiver = audioReceiver; TheSynth->ArrangeAudioSourceDependencies(); } mOwner->PostRepatch(this, fromUserClick); //insert if (GetKeyModifiers() == kModifier_Shift && fromUserClick) { if (sAllowInsert) //avoid cascade on the next set { sAllowInsert = false; IDrawableModule* targetModule = dynamic_cast<IDrawableModule*>(target); if (targetModule && targetModule->GetPatchCableSource()) { targetModule->GetPatchCableSource()->FindValidTargets(); if (targetModule->GetPatchCableSource()->IsValidTarget(oldTarget)) targetModule->SetTarget(oldTarget); } sAllowInsert = true; } } } void PatchCableSource::Clear() { auto cablesToRemove = mPatchCables; //make copy of list for (auto cable : cablesToRemove) RemovePatchCable(cable); mPatchCables.clear(); } void PatchCableSource::UpdatePosition(bool parentMinimized) { if (mOwner != nullptr && (mAutomaticPositioning || parentMinimized || mOwner->Minimized())) { float x, y, w, h; mOwner->GetPosition(x, y); mOwner->GetDimensions(w, h); if (parentMinimized) { mOwner->GetParent()->GetPosition(x, y); mOwner->GetParent()->GetDimensions(w, h); } if (mManualSide == Side::kNone || parentMinimized) { ofVec2f centerOfMass; int count = 0; for (auto cable : mPatchCables) { if (cable != nullptr) { if (cable->IsDragging()) { centerOfMass.x += TheSynth->GetMouseX(mOwner->GetOwningContainer()); centerOfMass.y += TheSynth->GetMouseY(mOwner->GetOwningContainer()); ++count; } else if (cable->GetTarget()) { float targetX, targetY, targetW, targetH; cable->GetTarget()->GetPosition(targetX, targetY); cable->GetTarget()->GetDimensions(targetW, targetH); centerOfMass.x += targetX + targetW / 2; centerOfMass.y += targetY + targetH / 2; ++count; } } } centerOfMass.x /= count; centerOfMass.y /= count; if (count > 0) { if (centerOfMass.y > y + h) mSide = Side::kBottom; else if (centerOfMass.x < x + w / 2) mSide = Side::kLeft; else mSide = Side::kRight; } else { mSide = Side::kBottom; } } else { mSide = mManualSide; } if (mSide == Side::kBottom) { mX = x + w / 2; mY = y + h + 3; } else if (mSide == Side::kLeft) { mX = x - 3; mY = y + h / 2; } else if (mSide == Side::kRight) { mX = x + w + 3; mY = y + h / 2; } } else if (mOwner != nullptr) { float x, y; mOwner->GetPosition(x, y); mX = mManualPositionX + x; mY = mManualPositionY + y; mSide = mManualSide; } } void PatchCableSource::DrawSource() { mDrawPass = DrawPass::kSource; Draw(); } void PatchCableSource::DrawCables(bool parentMinimized) { mDrawPass = DrawPass::kCables; mParentMinimized = parentMinimized; Draw(); } void PatchCableSource::Render() { if (!Enabled() || mOwner->IsDeleted()) return; ofPushStyle(); float cableX = mX; float cableY = mY; if (mOwner->GetOwningContainer() != nullptr) { cableX -= mOwner->GetOwningContainer()->GetOwnerPosition().x; cableY -= mOwner->GetOwningContainer()->GetOwnerPosition().y; } for (int i = 0; i < (int)mPatchCables.size() || i == 0; ++i) { if (i < (int)mPatchCables.size() && mPatchCables[i] != nullptr) { mPatchCables[i]->SetSourceIndex(i); if (mParentMinimized) { IDrawableModule* owningModule = mPatchCables[i]->GetOwningModule(); IClickable* target = mPatchCables[i]->GetTarget(); if (owningModule != nullptr && target != nullptr) { ModuleContainer* owningModuleContainer = owningModule->GetOwningContainer(); ModuleContainer* targetContainer = target->GetModuleParent()->GetOwningContainer(); if (owningModuleContainer == targetContainer) continue; //this is an internally-patched cable in a minimized module } } } if (mDrawPass == DrawPass::kCables && (mPatchCableDrawMode != kPatchCableDrawMode_CablesOnHoverOnly || mHoverIndex != -1)) { if (i < (int)mPatchCables.size() && mPatchCables[i] != nullptr) mPatchCables[i]->Draw(); } if (mDrawPass == DrawPass::kSource && (mPatchCableDrawMode != kPatchCableDrawMode_SourceOnHoverOnly || mHoverIndex != -1)) { ofSetLineWidth(0); ofColor color = GetColor(); float radius = kPatchCableSourceRadius; IDrawableModule* moveModule = TheSynth->GetMoveModule(); if (GetKeyModifiers() == kModifier_Shift && moveModule != nullptr) { if (mLastSeenAutopatchableModule != moveModule) { FindValidTargets(); mLastSeenAutopatchableModule = moveModule; } if ((IsValidTarget(moveModule) && GetTarget() != moveModule) || (GetOwner() == moveModule && GetTarget() == nullptr)) { //highlight autopatchable cable sources float lerp = ofMap(sin(gTime / 600 * PI * 2), -1, 1, 0, 1); color = ofColor::lerp(color, ofColor::white, lerp * .7f); radius = ofLerp(radius, kPatchCableSourceClickRadius, lerp); } } ofSetColor(color); ofFill(); ofCircle(cableX, cableY, radius); if (mHoverIndex == i && PatchCable::sActivePatchCable == nullptr && !TheSynth->IsGroupSelecting()) { ofSetColor(ofColor::white); ofFill(); ofCircle(cableX, cableY, kPatchCableSourceRadius - 2); if (InAddCableMode()) { ofSetColor(0, 0, 0); ofSetLineWidth(2); ofLine(cableX, cableY - (kPatchCableSourceRadius - 1), cableX, cableY + (kPatchCableSourceRadius - 1)); ofLine(cableX - (kPatchCableSourceRadius - 1), cableY, cableX + (kPatchCableSourceRadius - 1), cableY); } } if (mType == kConnectionType_Grid) { ofPushStyle(); ofNoFill(); ofSetColor(IDrawableModule::GetColor(kModuleCategory_Other)); GridControlTarget::DrawGridIcon(cableX + 7, cableY - 6); ofPopStyle(); } } if (mHoverIndex != -1 && mDefaultPatchBehavior != kDefaultPatchBehavior_Add) { if (mSide == Side::kBottom) cableY += kPatchCableSpacing; else if (mSide == Side::kLeft) cableX -= kPatchCableSpacing; else if (mSide == Side::kRight || mSide == Side::kNone) cableX += kPatchCableSpacing; } } ofPopStyle(); } ofColor PatchCableSource::GetColor() const { if (mIsPartOfCircularDependency) { float pulse = ofMap(sin(gTime / 500 * PI * 2), -1, 1, .5f, 1); return ofColor(255 * pulse, 255 * pulse, 0); } return mColor; } ofVec2f PatchCableSource::GetCableStart(int index) const { float cableX = mX; float cableY = mY; if (mHoverIndex != -1 && mDefaultPatchBehavior != kDefaultPatchBehavior_Add) { if (mSide == Side::kBottom) cableY += kPatchCableSpacing * index; else if (mSide == Side::kLeft) cableX -= kPatchCableSpacing * index; else if (mSide == Side::kRight || mSide == Side::kNone) cableX += kPatchCableSpacing * index; } return ofVec2f(cableX, cableY); } ofVec2f PatchCableSource::GetCableStartDir(int index, ofVec2f dest) const { if (mHasOverrideCableDir) { return mOverrideCableDir; } else { enum class Direction { kUp, kDown, kLeft, kRight, kNone }; Direction dir{ Direction::kNone }; switch (mSide) { case Side::kBottom: dir = Direction::kDown; break; case Side::kLeft: dir = Direction::kLeft; break; case Side::kRight: dir = Direction::kRight; break; case Side::kNone: dir = Direction::kNone; break; } if (mHoverIndex != -1 && mPatchCables.size() > 0 && index < mPatchCables.size() - 1) //not the top of the cable stack { if (mSide == Side::kBottom) { if (dest.x < mX) dir = Direction::kLeft; else dir = Direction::kRight; } else if (mSide == Side::kLeft || mSide == Side::kRight) { if (dest.y < mY) dir = Direction::kUp; else dir = Direction::kDown; } } ofVec2f ret(0, 0); switch (dir) { case Direction::kDown: ret = ofVec2f(0, 1); break; case Direction::kRight: ret = ofVec2f(1, 0); break; case Direction::kLeft: ret = ofVec2f(-1, 0); break; case Direction::kUp: ret = ofVec2f(0, -1); break; case Direction::kNone: ret = ofVec2f(0, 0); break; } if (mHoverIndex == -1 && mPatchCables.size() > 1) ret = ret * .5f; //soften if there are multiple cables return ret; } } bool PatchCableSource::MouseMoved(float x, float y) { if (!Enabled()) return false; if (!mClickable) return false; x = TheSynth->GetMouseX(mOwner->GetOwningContainer()); y = TheSynth->GetMouseY(mOwner->GetOwningContainer()); mHoverIndex = GetHoverIndex(x, y); if (mHoverIndex != -1 && gHoveredUIControl != nullptr) { if (gHoveredUIControl->IsMouseDown()) mHoverIndex = -1; //if we're dragging a control, don't show cables bubbling out else gHoveredUIControl = nullptr; //if we're hovering over a patch cable, get rid of ui control hover } for (size_t i = 0; i < mPatchCables.size(); ++i) { if (mPatchCables[i] != nullptr) { mPatchCables[i]->SetHoveringOnSource(i == mHoverIndex); mPatchCables[i]->NotifyMouseMoved(x, y); } } return false; } void PatchCableSource::MouseReleased() { mValidTargets.clear(); std::vector<PatchCable*> cables = mPatchCables; //copy, since list might get modified here for (auto cable : cables) { if (cable->IsDragging()) { FindValidTargets(); cable->MouseReleased(); } } } bool PatchCableSource::TestClick(float x, float y, bool right, bool testOnly /* = false */) { if (!Enabled()) return false; if (!mClickable) return false; if (right) return false; if (mHoverIndex != -1) { if (!testOnly) { if (mPatchCables.empty() || InAddCableMode()) { if (mPatchCables.empty() || mType == kConnectionType_Note || mType == kConnectionType_Pulse || mType == kConnectionType_UIControl || mType == kConnectionType_Special || mType == kConnectionType_ValueSetter || mType == kConnectionType_Modulator) { PatchCable* newCable = AddPatchCable(nullptr); if (newCable) newCable->Grab(); } else if (mType == kConnectionType_Audio) { ofVec2f spawnOffset(-20, 10); ModuleFactory::Spawnable spawnable; spawnable.mLabel = "send"; AudioSend* send = dynamic_cast<AudioSend*>(TheSynth->SpawnModuleOnTheFly(spawnable, x + spawnOffset.x, y + spawnOffset.y)); send->SetTarget(GetTarget()); SetTarget(send); send->SetSend(1, false); TheSynth->SetMoveModule(send, spawnOffset.x, spawnOffset.y, false); } } else { if (mPatchCables[mHoverIndex] != nullptr) mPatchCables[mHoverIndex]->Grab(); } } return true; } //for (auto cable : mPatchCables) //{ // if (cable->TestClick(x, y, right, testOnly)) // return true; //} return false; } bool PatchCableSource::TestHover(float x, float y) const { if (!Enabled()) return false; if (!mClickable) return false; return GetHoverIndex(x, y) != -1; } int PatchCableSource::GetHoverIndex(float x, float y) const { float cableX = mX; float cableY = mY; for (int i = 0; i < mPatchCables.size() || i == 0; ++i) { if (ofDistSquared(x, y, cableX, cableY) < kPatchCableSourceClickRadius * kPatchCableSourceClickRadius) return i; if (mDefaultPatchBehavior == kDefaultPatchBehavior_Add) break; if (mSide == Side::kBottom) cableY += kPatchCableSpacing; else if (mSide == Side::kLeft) cableX -= kPatchCableSpacing; else if (mSide == Side::kRight || mSide == Side::kNone) cableX += kPatchCableSpacing; } return -1; } bool PatchCableSource::Enabled() const { return mEnabled; } void PatchCableSource::OnClicked(float x, float y, bool right) { } bool PatchCableSource::InAddCableMode() const { return (GetKeyModifiers() == kModifier_Shift && mAllowMultipleTargets) || mDefaultPatchBehavior == kDefaultPatchBehavior_Add; } bool PatchCableSource::IsValidTarget(IClickable* target) const { if (target == nullptr) return false; return VectorContains(target, mValidTargets); } void PatchCableSource::FindValidTargets() { mValidTargets.clear(); std::vector<IDrawableModule*> allModules; TheSynth->GetAllModules(allModules); for (auto module : allModules) { if (module == mOwner) continue; if ((mType == kConnectionType_Pulse || mType == kConnectionType_Modulator || mType == kConnectionType_ValueSetter || mType == kConnectionType_UIControl || mType == kConnectionType_Grid) && module != TheTitleBar) { for (auto uicontrol : module->GetUIControls()) { if (uicontrol->IsShowing() && (uicontrol->GetShouldSaveState() || dynamic_cast<ClickButton*>(uicontrol) != nullptr) && uicontrol->CanBeTargetedBy(this)) mValidTargets.push_back(uicontrol); } for (auto uigrid : module->GetUIGrids()) { if (uigrid->IsShowing() && uigrid->CanBeTargetedBy(this)) mValidTargets.push_back(uigrid); } } if (module == mOwner->GetParent()) continue; if (mTypeFilter.empty() == false && !VectorContains(module->GetTypeName(), mTypeFilter)) continue; if (mType == kConnectionType_Audio && module->CanReceiveAudio()) mValidTargets.push_back(module); if (mType == kConnectionType_Note && module->CanReceiveNotes()) mValidTargets.push_back(module); if (mType == kConnectionType_Pulse && module->CanReceivePulses()) mValidTargets.push_back(module); if (mType == kConnectionType_Special) { mValidTargets.push_back(module); } } } void PatchCableSource::CableGrabbed() { FindValidTargets(); mOwner->OnCableGrabbed(this); } void PatchCableSource::KeyPressed(int key, bool isRepeat) { if (key == juce::KeyPress::backspaceKey || key == juce::KeyPress::deleteKey) { for (auto cable : mPatchCables) { if (cable != nullptr && cable == PatchCable::sActivePatchCable) { RemovePatchCable(cable, true); break; } } } } void PatchCableSource::RemovePatchCable(PatchCable* cable, bool fromUserAction) { mOwner->PreRepatch(this); bool hadAudioReceiver = (mAudioReceiver != nullptr); mAudioReceiver = nullptr; if (cable != nullptr) { RemoveFromVector(dynamic_cast<INoteReceiver*>(cable->GetTarget()), mNoteReceivers); RemoveFromVector(dynamic_cast<IPulseReceiver*>(cable->GetTarget()), mPulseReceivers); } RemoveFromVector(cable, mPatchCables); mOwner->PostRepatch(this, fromUserAction); delete cable; if (hadAudioReceiver) TheSynth->ArrangeAudioSourceDependencies(); } void PatchCableSource::ClearPatchCables() { while (mPatchCables.empty() == false) RemovePatchCable(mPatchCables[0]); } void PatchCableSource::SetTarget(IClickable* target) { if (target != nullptr) { if (mPatchCables.empty()) AddPatchCable(target); else if (mPatchCables[0] != nullptr && mPatchCables[0]->GetTarget() != target) SetPatchCableTarget(mPatchCables[0], target, false); } else { mAudioReceiver = nullptr; mNoteReceivers.clear(); mPulseReceivers.clear(); } } IClickable* PatchCableSource::GetTarget() const { if (mPatchCables.empty() || mPatchCables[0] == nullptr) return nullptr; else return mPatchCables[0]->GetTarget(); } void PatchCableSource::SaveState(FileStreamOut& out) { out << (int)mPatchCables.size(); for (int i = 0; i < mPatchCables.size(); ++i) { std::string path = ""; IClickable* target = mPatchCables[i]->GetTarget(); if (target) path = target->Path(); out << path; } } void PatchCableSource::LoadState(FileStreamIn& in) { bool doDummyLoad = false; if (sIsLoadingModulePreset) doDummyLoad = true; if (!doDummyLoad) ClearPatchCables(); int size; in >> size; for (int i = 0; i < size; ++i) { std::string path; in >> path; if (!doDummyLoad) { IClickable* target = TheSynth->FindModule(path, false); if (target == nullptr) { try { target = TheSynth->FindUIControl(path); } catch (UnknownUIControlException& e) { } } if (TheSynth->IsDuplicatingModule() && mType == kConnectionType_Modulator) target = nullptr; //TODO(Ryan) make it so that when you're duplicating a group, modulators preserve connections to the new copies of controls within that group mPatchCables.push_back(new PatchCable(this)); assert(i == (int)mPatchCables.size() - 1); SetPatchCableTarget(mPatchCables[i], target, false); } } if (!doDummyLoad) mOwner->PostRepatch(this, false); } void NoteHistory::AddEvent(double time, bool on, int data) { if (on) mLastOnEventTime = time; mHistoryPos = (mHistoryPos + 1) % kHistorySize; mHistory[mHistoryPos].mTime = time; mHistory[mHistoryPos].mOn = on; mHistory[mHistoryPos].mData = data; } bool NoteHistory::CurrentlyOn() { return mHistory[mHistoryPos].mOn; } const NoteHistoryEvent& NoteHistory::GetHistoryEvent(int ago) const { assert(ago < kHistorySize); int index = (mHistoryPos + kHistorySize - ago) % kHistorySize; return mHistory[index]; } ```
/content/code_sandbox/Source/PatchCableSource.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
6,084
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // Chorder.cpp // modularSynth // // Created by Ryan Challinor on 12/2/12. // // #include "Chorder.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" #include "PolyphonyMgr.h" #include "ChordDatabase.h" #include <cstring> Chorder::Chorder() { std::memset(mHeldCount, 0, TOTAL_NUM_NOTES * sizeof(int)); std::memset(mInputNotes, 0, TOTAL_NUM_NOTES * sizeof(bool)); TheScale->AddListener(this); } Chorder::~Chorder() { TheScale->RemoveListener(this); } void Chorder::CreateUIControls() { IDrawableModule::CreateUIControls(); mChordGrid = new UIGrid("uigrid", 2, 2, 130, 50, mDiatonic ? TheScale->NumTonesInScale() : TheScale->GetPitchesPerOctave(), 3, this); mChordGrid->SetVal(0, 1, 1); mChordGrid->SetListener(this); mDiatonicCheckbox = new Checkbox(this, "diatonic", mChordGrid, kAnchor_Below, &mDiatonic); mChordDropdown = new DropdownList(this, "chord", mDiatonicCheckbox, kAnchor_Right, &mChordIndex, 40); mInversionDropdown = new DropdownList(this, "inversion", mChordDropdown, kAnchor_Right, &mInversion, 30); for (auto name : TheScale->GetChordDatabase().GetChordNames()) mChordDropdown->AddLabel(name, mChordDropdown->GetNumValues()); mInversionDropdown->AddLabel("0", 0); mInversionDropdown->AddLabel("1", 1); mInversionDropdown->AddLabel("2", 2); mInversionDropdown->AddLabel("3", 3); } void Chorder::DrawModule() { if (Minimized() || IsVisible() == false) return; ofPushStyle(); ofFill(); for (int i = 0; i < mChordGrid->GetCols(); ++i) { bool addColor = false; if (i == 0) { ofSetColor(0, 255, 0, 80); addColor = true; } else if ((mDiatonic && i == 4 && TheScale->NumTonesInScale() == 7) || (!mDiatonic && i == 7 && TheScale->GetPitchesPerOctave() == 12)) { ofSetColor(200, 150, 0, 80); addColor = true; } if (addColor) { ofRectangle rect = mChordGrid->GetRect(true); rect.width /= mChordGrid->GetCols(); rect.x += i * rect.width; ofRect(rect); } } ofPopStyle(); mChordGrid->Draw(); mDiatonicCheckbox->Draw(); mChordDropdown->Draw(); mInversionDropdown->Draw(); } void Chorder::GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) { if (!mDiatonic) return; //TODO(Ryan) int tone = col + (mChordGrid->GetRows() / 2 - row) * mChordGrid->GetCols(); if (value > 0 && oldValue == 0) { AddTone(tone, value * value); } else if (value == 0 && oldValue > 0) { RemoveTone(tone); } } void Chorder::AddTone(int tone, float velocity) { mChordGrid->SetVal((tone + mChordGrid->GetCols() * 10) % mChordGrid->GetCols(), mChordGrid->GetRows() - 1 - (tone + (mChordGrid->GetRows() / 2 * mChordGrid->GetCols())) / mChordGrid->GetCols(), sqrtf(velocity), !K(notifyListeners)); for (int i = 0; i < TOTAL_NUM_NOTES; ++i) { if (mInputNotes[i]) { int chordtone = tone + TheScale->GetToneFromPitch(i); int outPitch = TheScale->MakeDiatonic(TheScale->GetPitchFromTone(chordtone)); PlayChorderNote(NextBufferTime(false), outPitch, mVelocity * velocity, -1, ModulationParameters()); } } } void Chorder::RemoveTone(int tone) { mChordGrid->SetVal((tone + mChordGrid->GetCols() * 10) % mChordGrid->GetCols(), mChordGrid->GetRows() - 1 - (tone + (mChordGrid->GetRows() / 2 * mChordGrid->GetCols())) / mChordGrid->GetCols(), 0, !K(notifyListeners)); for (int i = 0; i < TOTAL_NUM_NOTES; ++i) { if (mInputNotes[i]) { int chordtone = tone + TheScale->GetToneFromPitch(i); int outPitch = TheScale->MakeDiatonic(TheScale->GetPitchFromTone(chordtone)); PlayChorderNote(NextBufferTime(false), outPitch, 0, -1, ModulationParameters()); } } } void Chorder::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); if (right) return; mChordGrid->TestClick(x, y, right); } void Chorder::MouseReleased() { IDrawableModule::MouseReleased(); mChordGrid->MouseReleased(); } bool Chorder::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); mChordGrid->NotifyMouseMoved(x, y); return false; } void Chorder::OnScaleChanged() { mChordGrid->SetGrid(mDiatonic ? TheScale->NumTonesInScale() : TheScale->GetPitchesPerOctave(), 3); } void Chorder::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) { mNoteOutput.Flush(time); std::memset(mHeldCount, 0, TOTAL_NUM_NOTES * sizeof(int)); std::memset(mInputNotes, 0, TOTAL_NUM_NOTES * sizeof(bool)); } if (checkbox == mDiatonicCheckbox) { mChordDropdown->SetShowing(!mDiatonic); mInversionDropdown->SetShowing(!mDiatonic); mChordGrid->SetGrid(mDiatonic ? TheScale->NumTonesInScale() : TheScale->GetPitchesPerOctave(), 3); } } void Chorder::DropdownUpdated(DropdownList* dropdown, int oldVal, double time) { if (dropdown == mChordDropdown || dropdown == mInversionDropdown) { std::vector<int> chord = TheScale->GetChordDatabase().GetChord(mChordDropdown->GetLabel(mChordIndex), mInversion); mChordGrid->Clear(); for (int val : chord) { int row = 2 - ((val + TheScale->GetPitchesPerOctave()) / TheScale->GetPitchesPerOctave()); int col = (val + TheScale->GetPitchesPerOctave()) % TheScale->GetPitchesPerOctave(); mChordGrid->SetVal(col, row, 1); } } } void Chorder::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (!mEnabled) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); return; } bool noteOn = velocity > 0; if (mInputNotes[pitch] == noteOn) return; mInputNotes[pitch] = noteOn; if (velocity > 0) mVelocity = velocity; int idx = 0; // iterate rows from bottom to top to go from lowest to highest note // for compatibility with arpeggiator and strummer for (int row = mChordGrid->GetRows() - 1; row >= 0; --row) { for (int col = 0; col < mChordGrid->GetCols(); ++col) { float val = mChordGrid->GetVal(col, row); if (val > 0) { int gridPosition = col + (mChordGrid->GetRows() / 2 - row) * mChordGrid->GetCols(); int voice = (voiceIdx == -1) ? -1 : (voiceIdx + idx) % 16; int outPitch; if (!mDiatonic) { outPitch = pitch + gridPosition; } else if (gridPosition % TheScale->NumTonesInScale() == 0) //if this is the pressed note or an octave of it { //play the pressed note (might not be in scale, so play it directly) int octave = gridPosition / TheScale->NumTonesInScale(); outPitch = pitch + TheScale->GetPitchesPerOctave() * octave; } else { int tone = gridPosition + TheScale->GetToneFromPitch(pitch); outPitch = TheScale->MakeDiatonic(TheScale->GetPitchFromTone(tone)); } PlayChorderNote(time, outPitch, velocity * val * val, voice, modulation); ++idx; } } } CheckLeftovers(); } void Chorder::PlayChorderNote(double time, int pitch, int velocity, int voice /*=-1*/, ModulationParameters modulation) { assert(velocity >= 0); if (pitch < 0 || pitch >= TOTAL_NUM_NOTES) return; bool wasOn = mHeldCount[pitch] > 0; if (velocity > 0) ++mHeldCount[pitch]; if (velocity == 0 && mHeldCount[pitch] > 0) --mHeldCount[pitch]; if (mHeldCount[pitch] > 0 && !wasOn) PlayNoteOutput(time, pitch, velocity, voice, modulation); if (mHeldCount[pitch] == 0 && wasOn) PlayNoteOutput(time, pitch, 0, voice, modulation); //ofLog() << ofToString(pitch) + " " + ofToString(velocity) + ": " + ofToString(mHeldCount[pitch]) + " " + ofToString(voice); } void Chorder::CheckLeftovers() { bool anyHeldNotes = false; for (int i = 0; i < TOTAL_NUM_NOTES; ++i) { if (mInputNotes[i]) { anyHeldNotes = true; break; } } if (!anyHeldNotes) { for (int i = 0; i < TOTAL_NUM_NOTES; ++i) { if (mHeldCount[i] > 0) { ofLog() << "Somehow there are still notes in the count! Clearing"; PlayNoteOutput(gTime, i, 0, -1); mHeldCount[i] = 0; } } } } void Chorder::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadBool("multislider_mode", moduleInfo, true); SetUpFromSaveData(); } void Chorder::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); bool multisliderMode = mModuleSaveData.GetBool("multislider_mode"); mChordGrid->SetGridMode(multisliderMode ? UIGrid::kMultisliderBipolar : UIGrid::kNormal); mChordGrid->SetRestrictDragToRow(multisliderMode); mChordGrid->SetRequireShiftForMultislider(true); } void Chorder::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); mChordGrid->SaveState(out); } void Chorder::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); mChordGrid->LoadState(in); } ```
/content/code_sandbox/Source/Chorder.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,965
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== NotePanAlternator.cpp Created: 25 Mar 2018 9:27:26pm Author: Ryan Challinor ============================================================================== */ #include "NotePanAlternator.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" NotePanAlternator::NotePanAlternator() { } void NotePanAlternator::CreateUIControls() { IDrawableModule::CreateUIControls(); mPanOneSlider = new FloatSlider(this, "one", 4, 2, 100, 15, &mPanOne, -1, 1); mPanTwoSlider = new FloatSlider(this, "two", mPanOneSlider, kAnchor_Below, 100, 15, &mPanTwo, -1, 1); } void NotePanAlternator::DrawModule() { if (Minimized() || IsVisible() == false) return; mPanOneSlider->Draw(); mPanTwoSlider->Draw(); ofPushStyle(); ofSetColor(0, 255, 0, 50); ofFill(); ofVec2f activePos = mFlip ? mPanTwoSlider->GetPosition(true) : mPanOneSlider->GetPosition(true); ofRect(activePos.x, activePos.y, 100, 15); ofPopStyle(); } void NotePanAlternator::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled && velocity > 0) { modulation.pan = mFlip ? mPanTwo : mPanOne; mFlip = !mFlip; } PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void NotePanAlternator::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void NotePanAlternator::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/NotePanAlternator.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
538
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // VSTScanner.cpp // Bespoke // // Created by Ryan Challinor on 10/16/21. // // #include "VSTScanner.h" #include "VSTPlugin.h" #include "ModularSynth.h" #include "juce_gui_basics/juce_gui_basics.h" extern juce::ApplicationProperties& getAppProperties(); CustomPluginScanner::CustomPluginScanner() { if (auto* file = getAppProperties().getUserSettings()) file->addChangeListener(this); changeListenerCallback(nullptr); } CustomPluginScanner::~CustomPluginScanner() { if (auto* file = getAppProperties().getUserSettings()) file->removeChangeListener(this); } bool CustomPluginScanner::findPluginTypesFor(juce::AudioPluginFormat& format, juce::OwnedArray<juce::PluginDescription>& result, const juce::String& fileOrIdentifier) { if (!scanWithExternalProcess) { superprocess = nullptr; format.findAllTypesForFile(result, fileOrIdentifier); return true; } if (superprocess == nullptr) { superprocess = std::make_unique<Superprocess>(*this); std::unique_lock<std::mutex> lock(mutex); connectionLost = false; } juce::MemoryBlock block; juce::MemoryOutputStream stream{ block, true }; stream.writeString(format.getName()); stream.writeString(fileOrIdentifier); if (superprocess->sendMessageToWorker(block)) { std::unique_lock<std::mutex> lock(mutex); gotResponse = false; pluginDescription = nullptr; for (;;) { if (condvar.wait_for(lock, std::chrono::milliseconds(50), [this] { return gotResponse || shouldExit(); })) { break; } } if (shouldExit()) { superprocess = nullptr; return true; } if (connectionLost) { superprocess = nullptr; return false; } if (pluginDescription != nullptr) { for (const auto* item : pluginDescription->getChildIterator()) { auto desc = std::make_unique<juce::PluginDescription>(); if (desc->loadFromXml(*item)) result.add(std::move(desc)); } } return true; } superprocess = nullptr; return false; } void CustomPluginScanner::changeListenerCallback(juce::ChangeBroadcaster*) { if (auto* file = getAppProperties().getUserSettings()) scanWithExternalProcess = (file->getIntValue(kScanModeKey) == 0); } CustomPluginScanner::Superprocess::Superprocess(CustomPluginScanner& o) : owner(o) { launchWorkerProcess(juce::File::getSpecialLocation(juce::File::currentExecutableFile), kScanProcessUID, 0, 0); } void CustomPluginScanner::Superprocess::handleMessageFromWorker(const juce::MemoryBlock& mb) { auto xml = parseXML(mb.toString()); const std::lock_guard<std::mutex> lock(owner.mutex); owner.pluginDescription = std::move(xml); owner.gotResponse = true; owner.condvar.notify_one(); } void CustomPluginScanner::Superprocess::handleConnectionLost() { const std::lock_guard<std::mutex> lock(owner.mutex); owner.pluginDescription = nullptr; owner.gotResponse = true; owner.connectionLost = true; owner.condvar.notify_one(); } ///////////////////////////////////////////////////////////////////////////////////////////////// CustomPluginListComponent::CustomPluginListComponent(juce::AudioPluginFormatManager& manager, juce::KnownPluginList& listToRepresent, const juce::File& pedal, juce::PropertiesFile* props, bool async) : juce::PluginListComponent(manager, listToRepresent, pedal, props, async) { addAndMakeVisible(validationModeLabel); addAndMakeVisible(validationModeBox); validationModeLabel.attachToComponent(&validationModeBox, true); validationModeLabel.setJustificationType(juce::Justification::right); validationModeLabel.setSize(100, 30); auto unusedId = 1; for (const auto mode : { "Avoid crashes", "Within process" }) validationModeBox.addItem(mode, unusedId++); validationModeBox.setSelectedItemIndex(getAppProperties().getUserSettings()->getIntValue(kScanModeKey)); validationModeBox.onChange = [this] { getAppProperties().getUserSettings()->setValue(kScanModeKey, validationModeBox.getSelectedItemIndex()); }; OnResize(); } void CustomPluginListComponent::OnResize() { const auto& buttonBounds = getOptionsButton().getBounds(); validationModeBox.setBounds(buttonBounds.withWidth(130).withRightX(getWidth() - buttonBounds.getX())); //validationModeBox.setBounds(juce::Rectangle(5,5,130,40)); } ///////////////////////////////////////////////////////////////////////////////////////////////// PluginListWindow::PluginListWindow(juce::AudioPluginFormatManager& pluginFormatManager, WindowCloseListener* listener) : juce::DocumentWindow("Plugin Manager", juce::LookAndFeel::getDefaultLookAndFeel().findColour(juce::ResizableWindow::backgroundColourId), juce::DocumentWindow::closeButton) , mListener(listener) { auto deadMansPedalFile(juce::File(ofToDataPath("vst/deadmanspedal.txt"))); TheSynth->GetKnownPluginList().setCustomScanner(std::make_unique<CustomPluginScanner>()); mComponent = new CustomPluginListComponent(pluginFormatManager, TheSynth->GetKnownPluginList(), deadMansPedalFile, getAppProperties().getUserSettings(), true); setContentOwned(mComponent, true); setResizable(true, false); setResizeLimits(300, 400, 1500, 1500); setSize(600, 600); //setAlwaysOnTop(true); if (const auto* dpy = juce::Desktop::getInstance().getDisplays().getDisplayForRect(TheSynth->GetMainComponent()->getScreenBounds())) { const auto& mainMon = dpy->userArea; setTopLeftPosition(mainMon.getX() + mainMon.getWidth() / 4, mainMon.getY() + mainMon.getHeight() / 4); } restoreWindowStateFromString(getAppProperties().getUserSettings()->getValue("listWindowPos")); setVisible(true); } PluginListWindow::~PluginListWindow() { getAppProperties().getUserSettings()->setValue("listWindowPos", getWindowStateAsString()); clearContentComponent(); } void PluginListWindow::resized() { juce::DocumentWindow::resized(); mComponent->OnResize(); } void PluginListWindow::closeButtonPressed() { mListener->OnWindowClosed(); } ///////////////////////////////////////////////////////////////////////////////////////////////// PluginScannerSubprocess::PluginScannerSubprocess() { formatManager.addDefaultFormats(); } void PluginScannerSubprocess::handleMessageFromCoordinator(const juce::MemoryBlock& mb) { { const std::lock_guard<std::mutex> lock(mutex); pendingBlocks.emplace(mb); } triggerAsyncUpdate(); } void PluginScannerSubprocess::handleConnectionLost() { juce::JUCEApplicationBase::quit(); } // It's important to run the plugin scan on the main thread! void PluginScannerSubprocess::handleAsyncUpdate() { for (;;) { const auto block = [&]() -> juce::MemoryBlock { const std::lock_guard<std::mutex> lock(mutex); if (pendingBlocks.empty()) return {}; auto out = std::move(pendingBlocks.front()); pendingBlocks.pop(); return out; }(); if (block.isEmpty()) return; juce::MemoryInputStream stream{ block, false }; const auto formatName = stream.readString(); const auto identifier = stream.readString(); juce::OwnedArray<juce::PluginDescription> results; for (auto* format : formatManager.getFormats()) if (format->getName() == formatName) format->findAllTypesForFile(results, identifier); juce::XmlElement xml("LIST"); for (const auto& desc : results) xml.addChildElement(desc->createXml().release()); const auto str = xml.toString(); sendMessageToCoordinator({ str.toRawUTF8(), str.getNumBytesAsUTF8() }); } } ```
/content/code_sandbox/Source/VSTScanner.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,849
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== NoteEcho.h Created: 29 March 2022 Author: Ryan Challinor ============================================================================== */ #pragma once #include <iostream> #include "IDrawableModule.h" #include "INoteSource.h" #include "Slider.h" class NoteEcho : public INoteReceiver, public INoteSource, public IDrawableModule, public IFloatSliderListener { public: NoteEcho(); static IDrawableModule* Create() { return new NoteEcho(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) override; void SendCC(int control, int value, int voiceIdx = -1) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; virtual void SaveLayout(ofxJSONElement& moduleInfo) override; bool IsEnabled() const override { return true; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } void SendNoteToIndex(int index, double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation); static const int kMaxDestinations = 5; std::array<float, kMaxDestinations> mDelay; std::array<FloatSlider*, kMaxDestinations> mDelaySlider{}; std::array<AdditionalNoteCable*, kMaxDestinations> mDestinationCables{}; float mWidth{ 200 }; float mHeight{ 20 }; }; ```
/content/code_sandbox/Source/NoteEcho.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
516
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // PatchCable.cpp // Bespoke // // Created by Ryan Challinor on 12/12/15. // // #include "PatchCable.h" #include "IDrawableModule.h" #include "INoteSource.h" #include "IAudioReceiver.h" #include "IAudioSource.h" #include "GridController.h" #include "ModularSynth.h" #include "SynthGlobals.h" #include "PatchCableSource.h" #include "MathUtils.h" #include "IPulseReceiver.h" #include "RadioButton.h" #include "MidiController.h" #include "IModulator.h" #include "UserPrefs.h" #include "QuickSpawnMenu.h" PatchCable* PatchCable::sActivePatchCable = nullptr; PatchCable::PatchCable(PatchCableSource* owner) { mOwner = owner; TheSynth->RegisterPatchCable(this); } PatchCable::~PatchCable() { if (sActivePatchCable == this) sActivePatchCable = nullptr; TheSynth->UnregisterPatchCable(this); } void PatchCable::SetCableTarget(IClickable* target) { mTarget = target; mTargetRadioButton = dynamic_cast<RadioButton*>(target); mAudioReceiverTarget = dynamic_cast<IAudioReceiver*>(target); } void PatchCable::Render() { PatchCablePos cable = GetPatchCablePos(); mX = cable.start.x; mY = cable.start.y; ofVec2f cableFadeOut = cable.start * .47 + cable.end * .53f; ofVec2f cableFadeIn = cable.start * .53f + cable.end * .47f; float cableQuality = gDrawScale * UserPrefs.cable_quality.Get(); float lineWidth = 1; float plugWidth = 4; float lineAlpha = .4f; bool fatCable = false; if (TheSynth->GetLastClickedModule() == GetOwningModule() || TheSynth->GetLastClickedModule() == mTarget) fatCable = true; if (TheSynth->ShouldAccentuateActiveModules()) //only draw if we're making noise { if (GetConnectionType() == kConnectionType_Note || GetConnectionType() == kConnectionType_Grid || GetConnectionType() == kConnectionType_Pulse || GetConnectionType() == kConnectionType_Modulator || GetConnectionType() == kConnectionType_ValueSetter || GetConnectionType() == kConnectionType_UIControl) { bool hasNote = false; const NoteHistoryEvent& event = mOwner->GetHistory().GetHistoryEvent(0); float elapsed = float(gTime - event.mTime) / NOTE_HISTORY_LENGTH; if (event.mOn || elapsed <= 1) hasNote = true; if (!hasNote) return; } else if (GetConnectionType() == kConnectionType_Audio) { IAudioSource* audioSource = dynamic_cast<IAudioSource*>(GetOwningModule()); if (audioSource) { RollingBuffer* vizBuff = mOwner->GetOverrideVizBuffer(); if (vizBuff == nullptr) vizBuff = audioSource->GetVizBuffer(); assert(vizBuff); int numSamples = vizBuff->Size(); bool allZero = true; for (int ch = 0; ch < vizBuff->NumChannels(); ++ch) { for (int i = 0; i < numSamples && allZero; ++i) { if (vizBuff->GetSample(i, ch) != 0) allZero = false; } } if (allZero) return; } else { return; } } else { return; } fatCable = true; } if (fatCable) { lineWidth = 1; plugWidth = 5; lineAlpha = 1; } if (mHovered || mDragging) plugWidth = 6; ofPushMatrix(); ofPushStyle(); ofNoFill(); ConnectionType type = mOwner->GetConnectionType(); ofColor lineColor = mOwner->GetColor(); if (mHoveringOnSource && sActivePatchCable == nullptr && !TheSynth->IsGroupSelecting()) lineColor = ofColor::lerp(lineColor, ofColor::white, .5f); lineColor.a *= ModularSynth::sCableAlpha; ofColor lineColorAlphaed = lineColor; lineColorAlphaed.a *= lineAlpha; float wThis, hThis, xThis, yThis; GetDimensions(wThis, hThis); GetPosition(xThis, yThis); //bool isInsideSelf = cable.end.x >= xThis && cable.end.x <= (xThis + wThis) && cable.end.y >= yThis && cable.end.y <= (yThis + hThis); //if (!isInsideSelf) { IAudioSource* audioSource = nullptr; float wireLength = sqrtf((cable.plug - cable.start).lengthSquared()); float bezierStrength = wireLength * .15f; ofVec2f endDirection = MathUtils::Normal(cable.plug - cable.end); ofVec2f bezierControl1 = cable.start + cable.startDirection * bezierStrength; ofVec2f bezierControl2 = cable.plug + endDirection * bezierStrength; if (type == kConnectionType_Note || type == kConnectionType_Grid || type == kConnectionType_Pulse || type == kConnectionType_Modulator || type == kConnectionType_ValueSetter || type == kConnectionType_UIControl) { ofSetLineWidth(lineWidth); float cableStepSize = ofClamp(wireLength / (60 * cableQuality), 1, 1000); for (int half = 0; half < 2; ++half) { if (!UserPrefs.fade_cable_middle.Get() || wireLength < 100) ofSetColor(lineColorAlphaed); else if (half == 0) ofSetColorGradient(lineColorAlphaed, ofColor::clear, cable.start, cableFadeOut); else ofSetColorGradient(ofColor::clear, lineColorAlphaed, cableFadeIn, cable.end); ofBeginShape(); ofVertex(cable.start.x, cable.start.y); for (float i = 1; i < wireLength - 1; i += cableStepSize) { ofVec2f pos = MathUtils::Bezier(i / wireLength, cable.start, bezierControl1, bezierControl2, cable.plug); ofVertex(pos.x, pos.y); } ofVertex(cable.plug.x, cable.plug.y); ofEndShape(); if (!UserPrefs.fade_cable_middle.Get() || wireLength < 100) break; } IModulator* modulator = mOwner->GetModulatorOwner(); if (modulator != nullptr) { float range = abs(modulator->GetMax() - modulator->GetMin()); if (range > .00001f) { float delta = ofClamp(modulator->GetRecentChange() / range, -1, 1); ofColor color = ofColor::lerp(ofColor::blue, ofColor::red, delta * .5f + .5f); color.a = abs(1 - ((1 - delta) * (1 - delta))) * 150 * UserPrefs.cable_alpha.Get(); ofSetColor(color); ofSetLineWidth(3); for (int half = 0; half < 2; ++half) { if (!UserPrefs.fade_cable_middle.Get() || wireLength < 100) ofSetColor(color); else if (half == 0) ofSetColorGradient(color, ofColor::clear, cable.start, cableFadeOut); else ofSetColorGradient(ofColor::clear, color, cableFadeIn, cable.end); ofBeginShape(); ofVertex(cable.start.x, cable.start.y); for (float i = 1; i < wireLength - 1; i += cableStepSize) { ofVec2f pos = MathUtils::Bezier(i / wireLength, cable.start, bezierControl1, bezierControl2, cable.plug); ofVertex(pos.x, pos.y); } ofVertex(cable.plug.x, cable.plug.y); ofEndShape(); if (!UserPrefs.fade_cable_middle.Get() || wireLength < 100) break; } //change plug color if (delta > 0) lineColor = ofColor::lerp(lineColor, ofColor::red, delta); else lineColor = ofColor::lerp(lineColor, ofColor::blue, -delta); } } else { float lastElapsed = 0; for (int i = 0; i < NoteHistory::kHistorySize; ++i) { const NoteHistoryEvent& event = mOwner->GetHistory().GetHistoryEvent(i); float elapsed = float(gTime - event.mTime) / NOTE_HISTORY_LENGTH; float clampedElapsed = MIN(elapsed, 1); if (event.mOn) { ofSetLineWidth(lineWidth * (2 + ofClamp(1 - elapsed * .7f, 0, 1) * 3 + cos((gTime - event.mTime) * PI * 8 / TheTransport->MsPerBar()) * .3f)); for (int half = 0; half < 2; ++half) { if (!UserPrefs.fade_cable_middle.Get() || wireLength < 100) ofSetColor(lineColor); else if (half == 0) ofSetColorGradient(lineColor, ofColor::clear, cable.start, cableFadeOut); else ofSetColorGradient(ofColor::clear, lineColor, cableFadeIn, cable.end); ofBeginShape(); ofVec2f pos; for (int j = lastElapsed * wireLength; j < clampedElapsed * wireLength; ++j) { pos = MathUtils::Bezier(ofClamp(j / wireLength, 0, 1), cable.start, bezierControl1, bezierControl2, cable.plug); ofVertex(pos.x, pos.y); } ofEndShape(); if (type == kConnectionType_Pulse && (event.mData & kPulseFlag_Reset)) { ofPushStyle(); pos = MathUtils::Bezier(ofClamp(clampedElapsed, 0, 1), cable.start, bezierControl1, bezierControl2, cable.plug); ofSetLineWidth(1); ofFill(); ofSetColor(ofColor::black); ofCircle(pos.x, pos.y, 3); ofPopStyle(); } if (!UserPrefs.fade_cable_middle.Get() || wireLength < 100) break; } /*if (clampedElapsed < 1) { ofPushStyle(); ofFill(); ofSetLineWidth(1); ofCircle(pos.x, pos.y, 4); ofPopStyle(); }*/ } lastElapsed = clampedElapsed; if (clampedElapsed >= 1) break; } } ofSetLineWidth(plugWidth); ofSetColor(lineColor); ofLine(cable.plug.x, cable.plug.y, cable.end.x, cable.end.y); } else if (type == kConnectionType_Audio && (audioSource = dynamic_cast<IAudioSource*>(mOwner->GetOwner())) != nullptr) { ofSetLineWidth(lineWidth); RollingBuffer* vizBuff = mOwner->GetOverrideVizBuffer(); if (vizBuff == nullptr) vizBuff = audioSource->GetVizBuffer(); assert(vizBuff); int numSamples = vizBuff->Size(); float dx = (cable.plug.x - cable.start.x) / wireLength; float dy = (cable.plug.y - cable.start.y) / wireLength; float cableStepSize = ofClamp(wireLength / (100 * cableQuality), 1, 7); for (int ch = 0; ch < vizBuff->NumChannels(); ++ch) { ofColor drawColor; if (ch == 0) drawColor.set(lineColorAlphaed.r, lineColorAlphaed.g, lineColorAlphaed.b, lineColorAlphaed.a); else drawColor.set(lineColorAlphaed.g, lineColorAlphaed.r, lineColorAlphaed.b, lineColorAlphaed.a); ofVec2f offset((ch - (vizBuff->NumChannels() - 1) * .5f) * 2 * dy, (ch - (vizBuff->NumChannels() - 1) * .5f) * 2 * -dx); for (int half = 0; half < 2; ++half) { if (!UserPrefs.fade_cable_middle.Get() || wireLength < 100) ofSetColor(drawColor); else if (half == 0) ofSetColorGradient(drawColor, ofColor::clear, cable.start, cableFadeOut); else ofSetColorGradient(ofColor::clear, drawColor, cableFadeIn, cable.end); ofBeginShape(); ofVertex(cable.start.x + offset.x, cable.start.y + offset.y); for (float i = 1; i < wireLength - 1; i += cableStepSize) { ofVec2f pos = MathUtils::Bezier(i / wireLength, cable.start, bezierControl1, bezierControl2, cable.plug); float sample = vizBuff->GetSample((i / wireLength * numSamples), ch); if (std::isnan(sample)) { ofSetColor(ofColor(255, 0, 0)); sample = 0; } else { sample = sqrtf(fabsf(sample)) * (sample < 0 ? -1 : 1); sample = ofClamp(sample, -1.0f, 1.0f); } ofVec2f sampleOffsetDir = MathUtils::BezierPerpendicular(i / wireLength, cable.start, bezierControl1, bezierControl2, cable.plug); pos += sampleOffsetDir * 10 * sample; ofVertex(pos.x + offset.x, pos.y + offset.y); } ofVertex(cable.plug.x + offset.x, cable.plug.y + offset.y); ofEndShape(); if (!UserPrefs.fade_cable_middle.Get() || wireLength < 100) break; } } ofSetLineWidth(plugWidth); ofSetColor(lineColor); ofLine(cable.plug.x, cable.plug.y, cable.end.x, cable.end.y); bool warn = false; if (!TheSynth->IsAudioPaused()) { if (vizBuff->NumChannels() > 1 && mAudioReceiverTarget && mAudioReceiverTarget->GetInputMode() == IAudioReceiver::kInputMode_Mono) { warn = true; //warn that the multichannel audio is being crunched to mono if (mHovered) TheSynth->SetNextDrawTooltip("warning: multichannel audio is being squashed to mono"); } if (vizBuff->NumChannels() == 1 && mAudioReceiverTarget && mAudioReceiverTarget->GetBuffer()->RecentNumActiveChannels() > 1) { warn = true; //warn that the target expects multichannel audio but we're not filling all of the channels if (mHovered) TheSynth->SetNextDrawTooltip("warning: target expects multichannel audio, but is only getting mono"); } } if (warn) { ofFill(); ofSetColor(255, 255, 0); ofCircle(cable.plug.x, cable.plug.y, 6); ofSetColor(0, 0, 0); DrawTextBold("!", cable.plug.x - 2, cable.plug.y + 5, 15); } } else { ofSetLineWidth(lineWidth); float cableStepSize = ofClamp(wireLength / (60 * cableQuality), 1, 1000); for (int half = 0; half < 2; ++half) { if (!UserPrefs.fade_cable_middle.Get() || wireLength < 100) ofSetColor(lineColorAlphaed); else if (half == 0) ofSetColorGradient(lineColorAlphaed, ofColor::clear, cable.start, cableFadeOut); else ofSetColorGradient(ofColor::clear, lineColorAlphaed, cableFadeIn, cable.end); ofBeginShape(); ofVertex(cable.start.x, cable.start.y); for (float i = 1; i < wireLength - 1; i += cableStepSize) { ofVec2f pos = MathUtils::Bezier(i / wireLength, cable.start, bezierControl1, bezierControl2, cable.plug); ofVertex(pos.x, pos.y); } ofVertex(cable.plug.x, cable.plug.y); ofEndShape(); if (!UserPrefs.fade_cable_middle.Get() || wireLength < 100) break; } ofSetLineWidth(plugWidth); ofSetColor(lineColor); ofLine(cable.plug.x, cable.plug.y, cable.end.x, cable.end.y); } } ofPopStyle(); ofPopMatrix(); } bool PatchCable::MouseMoved(float x, float y) { x = TheSynth->GetMouseX(GetOwningModule()->GetOwningContainer()); y = TheSynth->GetMouseY(GetOwningModule()->GetOwningContainer()); PatchCablePos cable = GetPatchCablePos(); mHovered = DistSqToLine(ofVec2f(x, y), cable.plug, cable.end) < 25 && gHoveredUIControl == nullptr; return false; } void PatchCable::MouseReleased() { if (mDragging) { ofVec2f mousePos(TheSynth->GetRawMouseX(), TheSynth->GetRawMouseY()); if ((mousePos - mGrabPos).distanceSquared() > 3) { IClickable* target = GetDropTarget(); if (target) mOwner->SetPatchCableTarget(this, target, true); Release(); if (target == nullptr) { if ((CableDropBehavior)UserPrefs.cable_drop_behavior.GetIndex() == CableDropBehavior::ShowQuickspawn) { if (GetConnectionType() == kConnectionType_Note || GetConnectionType() == kConnectionType_Audio || GetConnectionType() == kConnectionType_Pulse) ShowQuickspawnForCable(); } if ((CableDropBehavior)UserPrefs.cable_drop_behavior.GetIndex() == CableDropBehavior::DoNothing) { //do nothing } if ((CableDropBehavior)UserPrefs.cable_drop_behavior.GetIndex() == CableDropBehavior::DisconnectCable) { mOwner->RemovePatchCable(this, true); return; } if (mTarget == nullptr) Destroy(true); } } } } void PatchCable::ShowQuickspawnForCable() { Release(); TheSynth->GetQuickSpawn()->ShowSpawnCategoriesPopupForCable(this); if (mTarget == nullptr) //if we're currently connected to nothing { mOwner->SetPatchCableTarget(this, TheSynth->GetQuickSpawn()->GetMainContainerFollower(), true); } else //if we're inserting { SetTempDrawTarget(TheSynth->GetQuickSpawn()->GetMainContainerFollower()); TheSynth->GetQuickSpawn()->SetTempConnection(mTarget, GetConnectionType()); } TheSynth->GetQuickSpawn()->GetMainContainerFollower()->UpdateLocation(); } IClickable* PatchCable::GetDropTarget() { if (mDragging) { PatchCablePos cable = GetPatchCablePos(); IClickable* potentialTarget = TheSynth->GetRootContainer()->GetModuleAt(cable.end.x, cable.end.y); if (potentialTarget && (GetConnectionType() == kConnectionType_Pulse || GetConnectionType() == kConnectionType_Modulator || GetConnectionType() == kConnectionType_ValueSetter || GetConnectionType() == kConnectionType_Grid || GetConnectionType() == kConnectionType_UIControl)) { IClickable* potentialUIControl = nullptr; const auto& uicontrols = (static_cast<IDrawableModule*>(potentialTarget))->GetUIControls(); for (auto uicontrol : uicontrols) { if (uicontrol->IsShowing() == false || !IsValidTarget(uicontrol)) continue; ofRectangle rect = uicontrol->GetRect(); if (rect.contains(cable.end.x, cable.end.y)) { potentialUIControl = uicontrol; break; } } const auto& grids = (static_cast<IDrawableModule*>(potentialTarget))->GetUIGrids(); for (auto grid : grids) { if (grid->IsShowing() == false || !IsValidTarget(grid)) continue; ofRectangle rect = grid->GetRect(); if (rect.contains(cable.end.x, cable.end.y)) { potentialUIControl = grid; break; } } if (potentialUIControl != nullptr) potentialTarget = potentialUIControl; } if (mOwner->IsValidTarget(potentialTarget)) return potentialTarget; } return nullptr; } bool PatchCable::TestClick(float x, float y, bool right, bool testOnly /* = false */) { if (mHovered && !right) { if (!testOnly) Grab(); return true; } return false; } void PatchCable::OnClicked(float x, float y, bool right) { } PatchCablePos PatchCable::GetPatchCablePos() { ofVec2f start = mOwner->GetCableStart(mSourceIndex); float wThat, hThat, xThat, yThat; int yThatAdjust = 0; IClickable* target = mTarget; if (mTempDrawTarget != nullptr) target = mTempDrawTarget; IDrawableModule* targetModule = dynamic_cast<IDrawableModule*>(target); if (targetModule != nullptr && targetModule->IsDeleted()) { targetModule = nullptr; target = nullptr; } if (targetModule && targetModule->HasTitleBar() && !mDragging) yThatAdjust = IDrawableModule::TitleBarHeight(); if (mDragging) { int mouseX = TheSynth->GetMouseX(GetOwningModule()->GetOwningContainer()); int mouseY = TheSynth->GetMouseY(GetOwningModule()->GetOwningContainer()); wThat = 0; hThat = 0; xThat = mouseX; yThat = mouseY; } else if (target) { target->GetDimensions(wThat, hThat); target->GetPosition(xThat, yThat); IDrawableModule* targetModuleParent = dynamic_cast<IDrawableModule*>(target->GetParent()); IDrawableModule* targetModuleGrandparent = dynamic_cast<IDrawableModule*>(targetModuleParent ? targetModuleParent->GetParent() : nullptr); ModuleContainer* targetModuleParentContainer = targetModuleParent ? targetModuleParent->GetOwningContainer() : nullptr; IDrawableModule* targetModuleParentContainerModule = targetModuleParentContainer ? targetModuleParentContainer->GetOwner() : nullptr; if (targetModuleParentContainerModule && targetModuleParentContainerModule->Minimized()) targetModuleParent = targetModuleParentContainerModule; if (targetModuleParent && (targetModuleParent->Minimized() || target->IsShowing() == false)) { targetModuleParent->GetPosition(xThat, yThat); targetModuleParent->GetDimensions(wThat, hThat); if (targetModuleParent->HasTitleBar() && !mDragging) yThatAdjust = IDrawableModule::TitleBarHeight(); } if (targetModuleGrandparent && (targetModuleGrandparent->Minimized() || target->IsShowing() == false)) { targetModuleGrandparent->GetPosition(xThat, yThat); targetModuleGrandparent->GetDimensions(wThat, hThat); if (targetModuleGrandparent->HasTitleBar() && !mDragging) yThatAdjust = IDrawableModule::TitleBarHeight(); } } else { wThat = 0; hThat = 0; xThat = start.x; yThat = start.y; } ofVec2f startDirection = mOwner->GetCableStartDir(mSourceIndex, ofVec2f(xThat, yThat)); ofVec2f endDirection; ofVec2f end = FindClosestSide(xThat, yThat - yThatAdjust, wThat, hThat + yThatAdjust, start, startDirection, endDirection); //update direction to match found side startDirection = mOwner->GetCableStartDir(mSourceIndex, end); if (mTargetRadioButton && mUIControlConnection && !mDragging && target != nullptr) { target->GetDimensions(wThat, hThat); target->GetPosition(xThat, yThat); end = mTargetRadioButton->GetOptionPosition(mUIControlConnection->mValue); } float plugDirDistanceToStart = endDirection.dot(start - end); float plugLength = ofClamp(plugDirDistanceToStart - 20, 5, 14); ofVec2f plug = end + endDirection * plugLength; PatchCablePos cable; cable.start = start + startDirection * 4; cable.startDirection = startDirection; cable.end = end; cable.plug = plug; return cable; } ofVec2f PatchCable::FindClosestSide(float x, float y, float w, float h, ofVec2f start, ofVec2f startDirection, ofVec2f& endDirection) { ofVec2f dirs[4]; dirs[0].set(-1, 0); dirs[1].set(1, 0); dirs[2].set(0, -1); dirs[3].set(0, 1); ofVec2f sides[4]; sides[0].set(x, y + h / 2); //left sides[1].set(x + w, y + h / 2); //right sides[2].set(x + w / 2, y); //top sides[3].set(x + w / 2, y + h); //bottom float best = -FLT_MAX; int bestIndex = 0; for (int i = 0; i < 4; ++i) { if (i == 3) //skip bottom continue; float score = MathUtils::Normal(start - sides[i]).dot(dirs[i]); if (score > best) { best = score; bestIndex = i; } } if (w == 0 && h == 0) endDirection = MathUtils::Normal(start - ofVec2f(x, y)); else endDirection = dirs[bestIndex]; return sides[bestIndex]; } void PatchCable::Grab() { if (!mDragging) { mDragging = true; sActivePatchCable = this; gHoveredUIControl = nullptr; mGrabPos.set(TheSynth->GetRawMouseX(), TheSynth->GetRawMouseY()); mOwner->CableGrabbed(); } } void PatchCable::Release() { if (mDragging) { mDragging = false; mHovered = false; if (sActivePatchCable == this) sActivePatchCable = nullptr; } } IDrawableModule* PatchCable::GetOwningModule() const { return mOwner->GetOwner(); } bool PatchCable::IsValidTarget(IClickable* target) const { return mOwner->IsValidTarget(target); } void PatchCable::Destroy(bool fromUserClick) { mOwner->RemovePatchCable(this, fromUserClick); } ConnectionType PatchCable::GetConnectionType() const { return mOwner->GetConnectionType(); } ```
/content/code_sandbox/Source/PatchCable.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
6,370
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== Waveshaper.h Created: 1 Dec 2019 10:01:56pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IAudioProcessor.h" #include "IDrawableModule.h" #include "Slider.h" #include "ClickButton.h" #include "TextEntry.h" #include "exprtk/exprtk.hpp" class Waveshaper : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public ITextEntryListener { public: Waveshaper(); virtual ~Waveshaper(); static IDrawableModule* Create() { return new Waveshaper(); } static bool AcceptsAudio() { return true; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; //IAudioSource void Process(double time) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //IFloatSliderListener void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} //ITextEntryListener void TextEntryComplete(TextEntry* entry) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override; float mRescale{ 1 }; FloatSlider* mRescaleSlider{ nullptr }; float mA{ 0 }; FloatSlider* mASlider{ nullptr }; float mB{ 0 }; FloatSlider* mBSlider{ nullptr }; float mC{ 0 }; FloatSlider* mCSlider{ nullptr }; float mD{ 0 }; FloatSlider* mDSlider{ nullptr }; float mE{ 0 }; FloatSlider* mESlider{ nullptr }; std::string mEntryString{ "x" }; TextEntry* mTextEntry{ nullptr }; exprtk::symbol_table<float> mSymbolTable; exprtk::expression<float> mExpression; exprtk::symbol_table<float> mSymbolTableDraw; exprtk::expression<float> mExpressionDraw; float mExpressionInput{ 0 }; float mHistPre1{ 0 }; float mHistPre2{ 0 }; float mHistPost1{ 0 }; float mHistPost2{ 0 }; float mExpressionInputDraw{ 0 }; float mT{ 0 }; bool mExpressionValid{ false }; float mSmoothMax{ 0 }; float mSmoothMin{ 0 }; struct BiquadState { float mHistPre1{ 0 }; float mHistPre2{ 0 }; float mHistPost1{ 0 }; float mHistPost2{ 0 }; }; BiquadState mBiquadState[ChannelBuffer::kMaxNumChannels]; }; ```
/content/code_sandbox/Source/Waveshaper.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
774
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // SwitchAndRamp.cpp // Bespoke // // Created by Ryan Challinor on 03/27/22. // // #include "SwitchAndRamp.h" SwitchAndRamp::SwitchAndRamp() { mSwitching.fill(false); mLastOutput.fill(0); mOffset.fill(0); } void SwitchAndRamp::StartSwitch() { mSwitching.fill(true); } float SwitchAndRamp::Process(int channel, float input, float rampSpeed) { if (mSwitching[channel]) { mOffset[channel] = mLastOutput[channel] - input; mSwitching[channel] = false; } if (mOffset[channel] > rampSpeed) mOffset[channel] -= rampSpeed; else if (mOffset[channel] < -rampSpeed) mOffset[channel] += rampSpeed; else mOffset[channel] = 0; float ret = input + mOffset[channel]; mLastOutput[channel] = ret; return ret; } ```
/content/code_sandbox/Source/SwitchAndRamp.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
319
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== Push2Control.cpp Created: 24 Feb 2020 8:57:57pm Author: Ryan Challinor ============================================================================== */ #include "juce_opengl/juce_opengl.h" using namespace juce::gl; #include "Push2Control.h" #include <cctype> #include "SynthGlobals.h" #include "nanovg/nanovg.h" #define NANOVG_GLES2_IMPLEMENTATION #include "nanovg/nanovg_gl.h" #include "nanovg/nanovg_gl_utils.h" #include "OpenFrameworksPort.h" #include "UIControlMacros.h" #include "TitleBar.h" #include "ModuleSaveDataPanel.h" #include "QuickSpawnMenu.h" #include "PatchCableSource.h" #include "DropdownList.h" #include "FloatSliderLFOControl.h" #include "UserPrefsEditor.h" #include "Snapshots.h" #include "ADSRDisplay.h" #include "Looper.h" #include "NoteLooper.h" #include "ControlRecorder.h" #include "push2/JuceToPush2DisplayBridge.h" #include "push2/Push2-Bitmap.h" bool Push2Control::sDrawingPush2Display = false; NVGcontext* Push2Control::sVG = nullptr; NVGLUframebuffer* Push2Control::sFB = nullptr; IUIControl* Push2Control::sBindToUIControl = nullptr; namespace { ableton::Push2DisplayBridge ThePushBridge; // The bridge allowing to use juce::graphics for push } //path_to_url #include "leathers/push" #include "leathers/unused-variable" namespace { const int kTapTempoButton = 3; const int kMetronomeButton = 9; const int kBelowScreenButtonRow = 20; const int kMasterButton = 28; const int kStopClipButton = 29; const int kSetupButton = 30; const int kLayoutButton = 31; const int kConvertButton = 35; const int kQuantizeButtonSection = 36; const int kLeftButton = 44; const int kRightButton = 45; const int kUpButton = 46; const int kDownButton = 47; const int kSelectButton = 48; const int kShiftButton = 49; const int kNoteButton = 50; const int kSessionButton = 51; const int kAddDeviceButton = 52; const int kAddTrackButton = 53; const int kOctaveDownButton = 54; const int kOctaveUpButton = 55; const int kRepeatButton = 56; const int kAccentButton = 57; const int kScaleButton = 58; const int kUserButton = 59; const int kMuteButton = 60; const int kSoloButton = 61; const int kPageLeftButton = 62; const int kPageRightButton = 63; const int kCornerKnob = 79; const int kPlayButton = 85; const int kCircleButton = 86; const int kNewButton = 87; const int kDuplicateButton = 88; const int kAutomateButton = 89; const int kFixedLengthButton = 90; const int kAboveScreenButtonRow = 102; const int kDeviceButton = 110; const int kBrowseButton = 111; const int kMixButton = 112; const int kClipButton = 113; const int kQuantizeButton = 116; const int kDoubleLoopButton = 117; const int kDeleteButton = 118; const int kUndoButton = 119; const int kNumQuantizeButtons = 8; } #include "leathers/pop" Push2Control::Push2Control() : mSpawnLists(this) , mDevice(this) { Initialize(); for (int i = 0; i < 128 * 2; ++i) mLedState[i] = -1; for (int i = 0; i < (int)mModuleGrid.size(); ++i) mModuleGrid[i] = nullptr; for (int i = 0; i < 128; ++i) mNoteHeldState[i] = 0; for (int i = 0; i < kNumQuantizeButtons; ++i) mBookmarkSlots.push_back(nullptr); } Push2Control::~Push2Control() { } void Push2Control::Exit() { for (int i = 0; i < 128; ++i) { SetLed(kMidiMessage_Note, i, 0); SetLed(kMidiMessage_Control, i, 0); } if (mPixels != nullptr) { memset(mPixels, 0, sizeof(unsigned char) * GetNumDisplayPixels()); ThePushBridge.Flip(mPixels); } mDevice.DisconnectInput(); mDevice.DisconnectOutput(); } void Push2Control::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); DROPDOWN(mModuleGridLayoutStyleDropdown, "grid style", (int*)(&mModuleGridLayoutStyle), 100); CHECKBOX(mShowManualGridCheckbox, "show manual grid", &mShowManualGrid); ENDUIBLOCK(mWidth, mHeight); mModuleGridLayoutStyleDropdown->AddLabel("auto layout", (int)ModuleGridLayoutStyle::Automatic); mModuleGridLayoutStyleDropdown->AddLabel("manual layout", (int)ModuleGridLayoutStyle::Manual); mSpawnLists.SetModuleFactory(TheSynth->GetModuleFactory()); mSpawnLists.mNoteModules.GetList()->SetMaxPerColumn(9999); for (int i = 0; i < mSpawnLists.GetDropdowns().size(); ++i) { mSpawnLists.GetDropdowns()[i]->GetList()->SetWidth(100); mSpawnLists.GetDropdowns()[i]->GetList()->SetPosition(-999, -999); } mSpawnModuleControls.push_back(mSpawnLists.mInstrumentModules.GetList()); mSpawnModuleControls.push_back(mSpawnLists.mNoteModules.GetList()); mSpawnModuleControls.push_back(mSpawnLists.mSynthModules.GetList()); mSpawnModuleControls.push_back(mSpawnLists.mAudioModules.GetList()); mSpawnModuleControls.push_back(mSpawnLists.mModulatorModules.GetList()); mSpawnModuleControls.push_back(mSpawnLists.mPulseModules.GetList()); mSpawnModuleControls.push_back(mSpawnLists.mPlugins.GetList()); mSpawnModuleControls.push_back(mSpawnLists.mOtherModules.GetList()); mSpawnModuleControls.push_back(mSpawnLists.mPrefabs.GetList()); for (size_t i = 0; i < mModuleGridManualCables.size(); ++i) { mModuleGridManualCables[i] = new PatchCableSource(this, kConnectionType_Special); ofColor color = IDrawableModule::GetColor(kModuleCategory_Other); color.a *= .3f; mModuleGridManualCables[i]->SetColor(color); mModuleGridManualCables[i]->SetManualPosition((i % 8) * 12 + 8, (i / 8) * 12 + mHeight + 6); AddPatchCableSource(mModuleGridManualCables[i]); } } void Push2Control::DrawModule() { if (Minimized() || IsVisible() == false) return; if (!ThePushBridge.IsInitialized()) { ofSetColor(255, 0, 0, gModuleDrawAlpha); DrawTextNormal(mPushBridgeInitErrMsg, 3, 15); mModuleGridLayoutStyleDropdown->SetShowing(false); mShowManualGridCheckbox->SetShowing(false); for (auto& cable : mModuleGridManualCables) cable->SetShowing(false); } else { mModuleGridLayoutStyleDropdown->SetShowing(true); mShowManualGridCheckbox->SetShowing(true); for (auto& cable : mModuleGridManualCables) cable->SetShowing(mShowManualGrid); } mModuleGridLayoutStyleDropdown->Draw(); mShowManualGridCheckbox->Draw(); } void Push2Control::DrawModuleUnclipped() { if (mDisplayModule != nullptr && !mDisplayModule->IsDeleted() && !sDrawingPush2Display && mDisplayModule->GetOwningContainer() != nullptr && mDisplayModule->IsShowing()) { ofPushMatrix(); ofPushStyle(); ofVec2f pos = GetPosition(); ofTranslate(-pos.x, -pos.y); DrawDisplayModuleRect(mDisplayModule->GetRect(), 3); ofPopMatrix(); ofPopStyle(); } } void Push2Control::DrawDisplayModuleRect(ofRectangle rect, float thickness) { if (mDisplayModule->HasTitleBar()) { rect.y -= IDrawableModule::TitleBarHeight(); rect.height += IDrawableModule::TitleBarHeight(); } ofSetColor(255, 255, 255, ofMap(sin(gTime / 1000 * PI * 2), -1, 1, 60, 100)); ofSetLineWidth(thickness); ofNoFill(); ofRect(rect.x - 3, rect.y - 3, rect.width + 6, rect.height + 6); } void Push2Control::PostRender() { if (ThePushBridge.IsInitialized()) RenderPush2Display(); } void Push2Control::KeyPressed(int key, bool isRepeat) { if (key == OF_KEY_DOWN || key == OF_KEY_UP || key == OF_KEY_LEFT || key == OF_KEY_RIGHT) { for (int i = 0; i < (int)mModuleGridManualCables.size(); ++i) { if (mModuleGridManualCables[i]->IsHovered()) { int x = i % 8; int y = i / 8; int newX = x; int newY = y; if (key == OF_KEY_RIGHT) newX = ofClamp(x + 1, 0, 7); if (key == OF_KEY_LEFT) newX = ofClamp(x - 1, 0, 7); if (key == OF_KEY_UP) newY = ofClamp(y - 1, 0, 7); if (key == OF_KEY_DOWN) newY = ofClamp(y + 1, 0, 7); IClickable* target = mModuleGridManualCables[x + y * 8]->GetTarget(); mModuleGridManualCables[x + y * 8]->ClearPatchCables(); mModuleGridManualCables[newX + newY * 8]->SetTarget(target); } } } } void Push2Control::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); if (!ThePushBridge.IsInitialized()) { Initialize(); } } void Push2Control::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void Push2Control::SetUpFromSaveData() { } void Push2Control::SaveLayout(ofxJSONElement& moduleInfo) { } void Push2Control::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); out << (int)mBookmarkSlots.size(); for (size_t i = 0; i < mBookmarkSlots.size(); ++i) { if (mBookmarkSlots[i] != nullptr) out << mBookmarkSlots[i]->Path(); else out << std::string(""); } out << (int)mFavoriteControls.size(); for (size_t i = 0; i < mFavoriteControls.size(); ++i) { if (mFavoriteControls[i] != nullptr) out << mFavoriteControls[i]->Path(); else out << std::string(""); } } void Push2Control::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (!ModuleContainer::DoesModuleHaveMoreSaveData(in)) return; //this was saved before we added versioning, bail out LoadStateValidate(rev >= GetModuleSaveStateRev()); int numBookmarks; in >> numBookmarks; mBookmarkSlots.resize(numBookmarks); for (int i = 0; i < numBookmarks; ++i) { std::string path; in >> path; if (path != "") mBookmarkSlots[i] = TheSynth->FindModule(path); else mBookmarkSlots[i] = nullptr; } int numFaves; in >> numFaves; mFavoriteControls.resize(numFaves); for (int i = 0; i < numFaves; ++i) { std::string path; in >> path; if (path != "") mFavoriteControls[i] = TheSynth->FindUIControl(path); else mFavoriteControls[i] = nullptr; } } //static void Push2Control::CreateStaticFramebuffer() { sVG = nvgCreateGLES2(NVG_ANTIALIAS | NVG_STENCIL_STROKES); assert(sVG); const auto width = ableton::Push2DisplayBitmap::kWidth; const auto height = ableton::Push2DisplayBitmap::kHeight; const int pixelRatio = 1; sFB = nvgluCreateFramebuffer(sVG, width * pixelRatio, height * pixelRatio, 0); assert(sFB); } bool Push2Control::Initialize() { if (!ThePushBridge.IsInitialized()) { if (auto result = ThePushBridge.Init(); result.Failed()) { mPushBridgeInitErrMsg = result.GetDescription(); ofLog() << mPushBridgeInitErrMsg; return false; } ofLog() << "push 2 connected"; } mPixels = new unsigned char[GetNumDisplayPixels()]; mFontHandle = nvgCreateFont(sVG, ofToResourcePath("frabk.ttf").c_str(), ofToResourcePath("frabk.ttf").c_str()); mFontHandleBold = nvgCreateFont(sVG, ofToResourcePath("frabk_m.ttf").c_str(), ofToResourcePath("frabk_m.ttf").c_str()); const std::vector<std::string>& devices = mDevice.GetPortList(false); for (int i = 0; i < devices.size(); ++i) { #if JUCE_WINDOWS if (strcmp(devices[i].c_str(), "Ableton Push 2") == 0) #else if (strcmp(devices[i].c_str(), "Ableton Push 2 Live Port") == 0) #endif { mDevice.ConnectOutput(i); mDevice.ConnectInput(devices[i].c_str()); std::string touchStripConfig = { 0x00, 0x21, 0x1D, 0x01, 0x01, 0x17, 0x03 }; mDevice.SendSysEx(touchStripConfig); break; } } return true; } int Push2Control::GetNumDisplayPixels() const { return 3 * (ableton::Push2DisplayBitmap::kWidth * kPixelRatio) * (ableton::Push2DisplayBitmap::kHeight * kPixelRatio); } void Push2Control::DrawToFramebuffer(NVGcontext* vg, NVGLUframebuffer* fb, float t, float pxRatio) { int winWidth, winHeight; int fboWidth, fboHeight; if (fb == NULL) return; nvgImageSize(vg, fb->image, &fboWidth, &fboHeight); winWidth = (int)(fboWidth / pxRatio); winHeight = (int)(fboHeight / pxRatio); nvgluBindFramebuffer(fb); glViewport(0, 0, fboWidth, fboHeight); glClearColor(0, 0, 0, 0); glClear(juce::gl::GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); nvgBeginFrame(vg, winWidth, winHeight, pxRatio); nvgLineCap(vg, NVG_ROUND); nvgLineJoin(vg, NVG_ROUND); static float sSpacing = -.3f; nvgTextLetterSpacing(vg, sSpacing); mModules.clear(); std::vector<IDrawableModule*> modules; TheSynth->GetAllModules(modules); for (int i = 0; i < modules.size(); ++i) { if (!IsIgnorableModule(modules[i])) mModules.push_back(modules[i]); } mModules = SortModules(mModules); SetModuleGridLights(); mModuleViewOffsetSmoothed = ofLerp(mModuleViewOffsetSmoothed, mModuleViewOffset, .3f); mModuleListOffsetSmoothed = ofLerp(mModuleListOffsetSmoothed, round(mModuleListOffset), .3f); if (mScreenDisplayMode == ScreenDisplayMode::kNormal || mScreenDisplayMode == ScreenDisplayMode::kMap) { DrawLowerModuleSelector(); DrawDisplayModuleControls(); std::string stateInfo = ""; if (gTime - mTextPopupTime < 1000) stateInfo = mTextPopup; else if (AllowRepatch() && mHeldModule != nullptr) stateInfo = "repatch mode: tap destination for " + std::string(mHeldModule->Name()); else if (mNewButtonHeld) stateInfo = "tap control to add favorite..."; else if (mDeleteButtonHeld) stateInfo = "tap control to remove favorite..."; else if (mLFOButtonHeld) stateInfo = "tap a control to add/edit LFO..."; else if (mAutomateButtonHeld && mCurrentControlRecorder == nullptr) stateInfo = "move a control to record automation..."; else if (mAutomateButtonHeld && mCurrentControlRecorder != nullptr) stateInfo = "recording automation, length = " + ofToString(mCurrentControlRecorder->GetLength(), 2); else if (mAddModuleBookmarkButtonHeld && mDisplayModule != nullptr) stateInfo = "tap a button in the column below this button to bookmark the \"" + std::string(mDisplayModule->Name()) + "\" module..."; else if (mInMidiControllerBindMode) stateInfo = "MIDI bind mode: hold a knob or button, then move/press a MIDI control to bind to that module control"; else if (mAddTrackHeld && mDisplayModule != nullptr && mDisplayModuleSnapshots == nullptr) stateInfo = "press one of the 4 buttons to the right of this screen to create a snapshot"; else if (mAddTrackHeld && mDisplayModule != nullptr && mDisplayModuleSnapshots != nullptr) stateInfo = "press one of the 4 buttons to the right of this screen to store a snapshot"; if (stateInfo != "") { ofPushStyle(); ofFill(); ofColor bgColor(175, 255, 221); bgColor = bgColor * ofMap(sin(gTime / 300 * PI * 2), -1, 1, .7f, 1); ofSetColor(bgColor); ofRect(1, 120, ableton::Push2DisplayBitmap::kWidth - 2, ableton::Push2DisplayBitmap::kHeight - 120); ofNoFill(); ofSetColor(255, 0, 0); ofRect(1, 1, ableton::Push2DisplayBitmap::kWidth - 2, ableton::Push2DisplayBitmap::kHeight - 2); ofSetColor(0, 0, 0); DrawTextBold(stateInfo, 10, 147, 18); ofPopStyle(); } } else if (mScreenDisplayMode == ScreenDisplayMode::kAddModule) { ofPushMatrix(); ofPushStyle(); if (mSelectedGridSpawnListIndex == -1) { ofSetColor(255, 255, 255); std::string text = "choose a module, then tap a grid square"; std::string moduleTypeToSpawn = GetModuleTypeToSpawn(); if (moduleTypeToSpawn != "") { ofSetColor(IDrawableModule::GetColor(TheSynth->GetModuleFactory()->GetModuleCategory(moduleTypeToSpawn))); text = "\ntap grid to spawn " + moduleTypeToSpawn; } DrawTextBold(text, 5, 80, 18); ofSetColor(IDrawableModule::GetColor(kModuleCategory_Other)); ofNoFill(); ofTranslate(-kColumnSpacing * mModuleViewOffsetSmoothed, 0); nvgFontSize(sVG, 12); DrawControls(mButtonControls, false, 60); DrawControls(mSliderControls, true, 20); } else if (mSelectedGridSpawnListIndex < (int)mSpawnLists.GetDropdowns().size()) { auto* list = mSpawnLists.GetDropdowns()[mSelectedGridSpawnListIndex]->GetList(); int boxWidth = 120; int boxHeight = 18; ofFill(); ofSetColor(IDrawableModule::GetColor(GetModuleTypeForSpawnList(list))); ofRect(mSelectedGridSpawnListIndex * boxWidth, -5, boxWidth, 12); for (int i = mModuleViewOffset * 8; i < list->GetNumValues(); ++i) { int x = (i % 8) * boxWidth; int y = (i / 8) * boxHeight + 10 - mModuleViewOffsetSmoothed * boxHeight; ofPushMatrix(); ofClipWindow(x, y, boxWidth, boxHeight, false); ofSetColor(GetSpawnGridColor(i, GetModuleTypeForSpawnList(list))); ofRect(x, y, boxWidth, boxHeight); ofSetColor(255, 255, 255); DrawTextBold(list->GetLabel(i), x + 4, y + 12); ofPopMatrix(); } } ofPopMatrix(); ofPopStyle(); for (int i = 0; i < 8; ++i) { if (mSelectedGridSpawnListIndex != -1 && i != mSelectedGridSpawnListIndex) SetLed(kMidiMessage_Control, i + kAboveScreenButtonRow, 0); else if (i < (int)mSpawnModuleControls.size()) SetLed(kMidiMessage_Control, i + kAboveScreenButtonRow, GetPadColorForType(GetModuleTypeForSpawnList(mSpawnModuleControls[i]), true)); else SetLed(kMidiMessage_Control, i + kAboveScreenButtonRow, 0); SetLed(kMidiMessage_Control, i + kBelowScreenButtonRow, 0); } } else if (mScreenDisplayMode == ScreenDisplayMode::kRouting) { DrawRoutingDisplay(); } if (mScreenDisplayMode == ScreenDisplayMode::kMap) { ofPushStyle(); ofPushMatrix(); ofPushStyle(); ofFill(); ofSetColor(0, 0, 0, 150); ofRect(0, 0, ableton::Push2DisplayBitmap::kWidth * kPixelRatio, ableton::Push2DisplayBitmap::kHeight * kPixelRatio); ofPopStyle(); float screenScale = .2f; ofScale(screenScale * gDrawScale, screenScale * gDrawScale, screenScale * gDrawScale); ofTranslate(TheSynth->GetDrawOffset().x, TheSynth->GetDrawOffset().y); ofTranslate(1500 / gDrawScale, -100 / gDrawScale); //center on display TheSynth->GetRootContainer()->DrawContents(); if (mDisplayModule != nullptr && !mDisplayModule->IsDeleted() && mDisplayModule->GetOwningContainer() != nullptr && mDisplayModule->IsShowing()) DrawDisplayModuleRect(mDisplayModule->GetRect(), 6); ofPopMatrix(); ofPopStyle(); /*for (int i = 0; i < 8; ++i) { SetLed(kMidiMessage_Control, i + kAboveScreenButtonRow, 0); SetLed(kMidiMessage_Control, i + kBelowScreenButtonRow, 0); }*/ } bool isHoveringOverNewModule = (gHoveredModule != mDisplayModule && gHoveredModule != nullptr); SetLed(kMidiMessage_Control, kPlayButton, TheSynth->IsAudioPaused() ? 127 : 120); if (mDisplayModule != nullptr) SetLed(kMidiMessage_Control, kCircleButton, mDisplayModule->IsEnabled() ? 126 : 127); else SetLed(kMidiMessage_Control, kCircleButton, 0); SetLed(kMidiMessage_Control, kTapTempoButton, isHoveringOverNewModule ? 127 : 0, isHoveringOverNewModule ? 32 : 0); SetLed(kMidiMessage_Control, kMetronomeButton, mDisplayModule == this ? 127 : 8); SetLed(kMidiMessage_Control, kConvertButton, mDisplayModule != nullptr ? 127 : 0); SetLed(kMidiMessage_Control, kDoubleLoopButton, mDisplayModule != nullptr && (mDisplayModule->GetTypeName() == "looper" || mDisplayModule->GetTypeName() == "notelooper") ? 127 : 0); SetLed(kMidiMessage_Control, kNewButton, 127, mNewButtonHeld ? 0 : -1); SetLed(kMidiMessage_Control, kDeleteButton, 127, mDeleteButtonHeld ? 0 : -1); SetLed(kMidiMessage_Control, kFixedLengthButton, 127, mLFOButtonHeld ? 0 : -1); SetLed(kMidiMessage_Control, kAutomateButton, GetPadColorForType(kModuleCategory_Modulator, true), mAutomateButtonHeld ? 0 : -1); SetLed(kMidiMessage_Control, kMasterButton, 127, mAddModuleBookmarkButtonHeld ? 0 : -1); SetLed(kMidiMessage_Control, kAddDeviceButton, 127, mScreenDisplayMode == ScreenDisplayMode::kAddModule ? 0 : -1); SetLed(kMidiMessage_Control, kAddTrackButton, mDisplayModule != nullptr ? 127 : 0, mAddTrackHeld ? 0 : -1); SetLed(kMidiMessage_Control, kUserButton, 127, mScreenDisplayMode == ScreenDisplayMode::kMap ? 0 : -1); if (mDisplayModuleSnapshots != nullptr) { SetLed(kMidiMessage_Control, kDeviceButton, mDisplayModuleSnapshots->HasSnapshot(0) ? 127 : 8, mDisplayModuleSnapshots->GetCurrentSnapshot() == 0 ? 0 : -1); SetLed(kMidiMessage_Control, kMixButton, mDisplayModuleSnapshots->HasSnapshot(1) ? 127 : 8, mDisplayModuleSnapshots->GetCurrentSnapshot() == 1 ? 0 : -1); SetLed(kMidiMessage_Control, kBrowseButton, mDisplayModuleSnapshots->HasSnapshot(2) ? 127 : 8, mDisplayModuleSnapshots->GetCurrentSnapshot() == 2 ? 0 : -1); SetLed(kMidiMessage_Control, kClipButton, mDisplayModuleSnapshots->HasSnapshot(3) ? 127 : 8, mDisplayModuleSnapshots->GetCurrentSnapshot() == 3 ? 0 : -1); } else { SetLed(kMidiMessage_Control, kDeviceButton, 0, mAddTrackHeld && mDisplayModule != nullptr ? 8 : -1); SetLed(kMidiMessage_Control, kMixButton, 0, mAddTrackHeld && mDisplayModule != nullptr ? 8 : -1); SetLed(kMidiMessage_Control, kBrowseButton, 0, mAddTrackHeld && mDisplayModule != nullptr ? 8 : -1); SetLed(kMidiMessage_Control, kClipButton, 0, mAddTrackHeld && mDisplayModule != nullptr ? 8 : -1); } SetLed(kMidiMessage_Control, kUpButton, mShiftHeld ? 0 : 127, 127); SetLed(kMidiMessage_Control, kDownButton, mShiftHeld ? 0 : 127, 127); SetLed(kMidiMessage_Control, kLeftButton, mShiftHeld ? 0 : 127, 127); SetLed(kMidiMessage_Control, kRightButton, mShiftHeld ? 0 : 127, 127); if (mHeldKnobIndex == -1) { SetLed(kMidiMessage_Control, kPageLeftButton, mModuleHistoryPosition > 0 ? 127 : 0); SetLed(kMidiMessage_Control, kPageRightButton, mModuleHistoryPosition < mModuleHistory.size() - 1 ? 127 : 0); SetLed(kMidiMessage_Control, kOctaveUpButton, 127); SetLed(kMidiMessage_Control, kOctaveDownButton, 127); SetLed(kMidiMessage_Control, kSelectButton, mDisplayModule != nullptr ? 127 : 0); } else { SetLed(kMidiMessage_Control, kPageLeftButton, 0, 127); SetLed(kMidiMessage_Control, kPageRightButton, 0, 127); SetLed(kMidiMessage_Control, kOctaveUpButton, 0, 127); SetLed(kMidiMessage_Control, kOctaveDownButton, 0, 127); SetLed(kMidiMessage_Control, kSelectButton, 0, 127); } SetLed(kMidiMessage_Control, kSetupButton, mInMidiControllerBindMode ? 127 : 32, mInMidiControllerBindMode ? 0 : 32); if (mGridControlModule != nullptr) { SetLed(kMidiMessage_Control, kNoteButton, 127, 10); SetLed(kMidiMessage_Control, kSessionButton, 10); SetLed(kMidiMessage_Control, kScaleButton, mDisplayModule == mGridControlModule ? 127 : 10); } else { SetLed(kMidiMessage_Control, kNoteButton, mDisplayModuleCanControlGrid ? 10 : 0); SetLed(kMidiMessage_Control, kSessionButton, 127); SetLed(kMidiMessage_Control, kScaleButton, 0); } if (mDisplayModule != nullptr) SetLed(kMidiMessage_Control, kLayoutButton, mScreenDisplayMode == ScreenDisplayMode::kRouting ? 127 : 10, mScreenDisplayMode == ScreenDisplayMode::kRouting ? 0 : -1); else SetLed(kMidiMessage_Control, kLayoutButton, 0); for (int i = 0; i < kNumQuantizeButtons; ++i) { int color = 0; if (mBookmarkSlots[i] != nullptr && !mBookmarkSlots[i]->IsDeleted()) color = GetPadColorForType(mBookmarkSlots[i]->GetModuleCategory(), mBookmarkSlots[i]->IsEnabled()); SetLed(kMidiMessage_Control, kQuantizeButtonSection + i, color, mDisplayModule == mBookmarkSlots[i] ? 0 : -1); } SetLed(kMidiMessage_Control, kShiftButton, 127, mShiftHeld ? 0 : -1); //test led colors //SetLed(kMidiMessage_Note, 92, (int)mModuleListOffset); //ofLog() << (int)mModuleListOffset; nvgEndFrame(vg); glFinish(); glReadBuffer(juce::gl::GL_COLOR_ATTACHMENT0); glReadPixels(0, 0, winWidth, winHeight, juce::gl::GL_RGB, GL_UNSIGNED_BYTE, mPixels); nvgluBindFramebuffer(NULL); } ofColor Push2Control::GetSpawnGridColor(int index, ModuleCategory moduleType) const { bool bright = false; if ((index / 4) % 4 == 0 || (index / 4) % 4 == 3) bright = true; ofColor color = IDrawableModule::GetColor(moduleType); if (bright) color = color * .8f; else color = color * .4f; return color; } int Push2Control::GetSpawnGridPadColor(int index, ModuleCategory moduleType) const { bool bright = false; if ((index / 4) % 4 == 0 || (index / 4) % 4 == 3) bright = true; return GetPadColorForType(moduleType, bright); } void Push2Control::SetModuleGridLights() { float minX = 0; float minY = 0; float maxX = ofGetWidth(); float maxY = ofGetHeight(); for (int i = 0; i < mModules.size(); ++i) { ofVec2f pos = mModules[i]->GetPosition(); if (pos.x > maxX) maxX = pos.x; if (pos.y > maxY) maxY = pos.y; if (pos.x < minX) minX = pos.x; if (pos.y < minY) minY = pos.y; } maxX += 1; maxY += 1; mModuleGridRect.set(minX, minY, maxX - minX, maxY - minY); if (mModuleGridLayoutStyle == ModuleGridLayoutStyle::Automatic || mScreenDisplayMode == ScreenDisplayMode::kAddModule) { for (int i = 0; i < (int)mModuleGrid.size(); ++i) mModuleGrid[i] = nullptr; for (int i = 0; i < mModules.size(); ++i) { ofVec2f pos = mModules[i]->GetPosition(); int gridX = (pos.x - minX) / (maxX - minX) * 8; int gridY = (pos.y - minY) / (maxY - minY) * 8; while (gridX < 8 && gridY < 8) { int index = gridX + gridY * 8; if (mModuleGrid[index] == nullptr) { mModuleGrid[index] = mModules[i]; break; } else { //IDrawableModule* otherModule = mModuleGrid[index]; int peekGridIndex; if (GetGridIndex(gridX + 1, gridY, peekGridIndex) && mModuleGrid[peekGridIndex] == nullptr) ++gridX; else if (GetGridIndex(gridX, gridY + 1, peekGridIndex) && mModuleGrid[peekGridIndex] == nullptr) ++gridY; else ++gridX; } } } } else if (mModuleGridLayoutStyle == ModuleGridLayoutStyle::Manual) { for (int i = 0; i < (int)mModuleGrid.size(); ++i) mModuleGrid[i] = static_cast<IDrawableModule*>(mModuleGridManualCables[i]->GetTarget()); } if (mScreenDisplayMode == ScreenDisplayMode::kAddModule && mSelectedGridSpawnListIndex != -1 && mSelectedGridSpawnListIndex < (int)mSpawnLists.GetDropdowns().size()) { auto* list = mSpawnLists.GetDropdowns()[mSelectedGridSpawnListIndex]->GetList(); for (int i = 0; i < 8 * 8; ++i) { int gridX = i % 8; int gridY = i / 8; int gridIndex = gridX + (7 - gridY) * 8 + 36; int moduleIndex = i + mModuleViewOffset * 8; if (moduleIndex < list->GetNumValues()) SetLed(kMidiMessage_Note, gridIndex, GetSpawnGridPadColor(moduleIndex, GetModuleTypeForSpawnList(list))); else SetLed(kMidiMessage_Note, gridIndex, 0); } } else if (mGridControlInterface != nullptr) { mGridControlInterface->UpdatePush2Leds(this); } else { for (int i = 0; i < (int)mModuleGrid.size(); ++i) { int gridX = i % 8; int gridY = i / 8; int gridIndex = gridX + (7 - gridY) * 8; int padNumber = 36 + i; if (mModuleGrid[gridIndex] != nullptr) SetLed(kMidiMessage_Note, padNumber, GetPadColorForType(mModuleGrid[gridIndex]->GetModuleCategory(), mModuleGrid[gridIndex]->IsEnabled()), mModuleGrid[gridIndex] == mDisplayModule ? 0 : -1); else SetLed(kMidiMessage_Note, padNumber, 0); } //all touchstrip LEDs off std::string touchStripLights = { 0x00, 0x21, 0x1D, 0x01, 0x01, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; GetDevice()->SendSysEx(touchStripLights); } } void Push2Control::DrawDisplayModuleControls() { if (mDisplayModule != nullptr && mDisplayModule->IsDeleted()) { SetDisplayModule(nullptr, false); return; } ofSetColor(255, 255, 255); if (mDisplayModule != nullptr) { ofPushMatrix(); ofPushStyle(); //nvgFontSize(mVG, 16); //nvgText(mVG, 10, 10, mDisplayModule->Name(), nullptr); float x; float y; mDisplayModule->GetPosition(x, y, true); mDisplayModule->SetPosition(5 - kColumnSpacing * mModuleViewOffsetSmoothed, 15); float titleBarHeight; float highlight; mDisplayModule->DrawFrame(kColumnSpacing * MAX(1, MAX(mSliderControls.size(), mButtonControls.size())) - 14, 80, false, titleBarHeight, highlight); mDisplayModule->SetPosition(x, y); ofSetColor(IDrawableModule::GetColor(mDisplayModule->GetModuleCategory())); ofNoFill(); nvgFontSize(sVG, 16); bool screenDrawingHandled = mDisplayModule->DrawToPush2Screen(); if (!screenDrawingHandled) { DrawControls(mButtonControls, false, 60); DrawControls(mSliderControls, true, 20); } int topRowLedColors[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; for (int i = 0; i < mButtonControls.size(); ++i) { if (i - mModuleViewOffset >= 0 && i - mModuleViewOffset < 8) topRowLedColors[i - mModuleViewOffset] = GetPadColorForType(mButtonControls[i]->GetModuleParent()->GetModuleCategory(), true); } for (int i = 0; i < 8; ++i) SetLed(kMidiMessage_Control, i + kAboveScreenButtonRow, topRowLedColors[i]); ofPopMatrix(); ofPopStyle(); ofPushStyle(); ofSetLineWidth(.5f); int length = MAX(mButtonControls.size(), mSliderControls.size()); if (length > 8) { ofRectangle bar(ableton::Push2DisplayBitmap::kWidth * kPixelRatio - 100, 3, 80, 10); ofNoFill(); ofSetColor(100, 100, 100); ofRect(bar); ofFill(); ofSetColor(255, 255, 255); bar.x += bar.width * mModuleViewOffsetSmoothed / length; bar.width *= 8.0f / length; ofRect(bar); } ofPopStyle(); } else { for (int i = 0; i < 8; ++i) SetLed(kMidiMessage_Control, i + kAboveScreenButtonRow, 0); } } void Push2Control::DrawLowerModuleSelector() { int bottomRowLedColors[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; for (int i = 0; i < mModules.size(); ++i) { if (i - mModuleListOffset < -1 || i - mModuleListOffset > 8) continue; ofPushMatrix(); ofPushStyle(); ofClipWindow(kColumnSpacing * (i - mModuleListOffsetSmoothed), 0, kColumnSpacing, ableton::Push2DisplayBitmap::kHeight * kPixelRatio, true); float x; float y; mModules[i]->GetPosition(x, y, true); mModules[i]->SetPosition(3 + kColumnSpacing * (i - mModuleListOffsetSmoothed), 120); float titleBarHeight; float highlight; mModules[i]->DrawFrame(kColumnSpacing - 14, 80, true, titleBarHeight, highlight); if (mModules[i] == mDisplayModule) DrawDisplayModuleRect(ofRectangle(0, 0, kColumnSpacing - 14, 80), 3); mModules[i]->SetPosition(x, y); if (i - round(mModuleListOffset) >= 0 && i - round(mModuleListOffset) < 8) bottomRowLedColors[i - (int)round(mModuleListOffset)] = GetPadColorForType(mModules[i]->GetModuleCategory(), true); ofPopMatrix(); ofPopStyle(); } for (int i = 0; i < 8; ++i) SetLed(kMidiMessage_Control, i + kBelowScreenButtonRow, bottomRowLedColors[i]); } void Push2Control::DrawRoutingDisplay() { int topRowLedColors[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; int bottomRowLedColors[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; for (int i = 0; i < mRoutingInputModules.size(); ++i) { ofPushMatrix(); ofPushStyle(); ofSetColor(mRoutingInputModules[i].mConnectionColor); ofLine(kColumnSpacing * (i + .5f), 37, kColumnSpacing * .5f, 60); ofClipWindow(kColumnSpacing * i, 0, kColumnSpacing, ableton::Push2DisplayBitmap::kHeight * kPixelRatio, true); float x; float y; mRoutingInputModules[i].mModule->GetPosition(x, y, true); mRoutingInputModules[i].mModule->SetPosition(3 + kColumnSpacing * i, 12); float titleBarHeight; float highlight; mRoutingInputModules[i].mModule->DrawFrame(kColumnSpacing - 14, 25, true, titleBarHeight, highlight); mRoutingInputModules[i].mModule->SetPosition(x, y); if (i >= 0 && i < 8) topRowLedColors[i] = GetPadColorForType(mRoutingInputModules[i].mModule->GetModuleCategory(), true); ofPopMatrix(); ofPopStyle(); } for (int i = 0; i < mRoutingOutputModules.size(); ++i) { ofPushMatrix(); ofPushStyle(); ofSetColor(mRoutingOutputModules[i].mConnectionColor); ofLine(kColumnSpacing * .5f, 97, kColumnSpacing * (i + .5f), 120); ofClipWindow(kColumnSpacing * i, 0, kColumnSpacing, ableton::Push2DisplayBitmap::kHeight * kPixelRatio, true); float x; float y; mRoutingOutputModules[i].mModule->GetPosition(x, y, true); mRoutingOutputModules[i].mModule->SetPosition(3 + kColumnSpacing * i, 132); float titleBarHeight; float highlight; mRoutingOutputModules[i].mModule->DrawFrame(kColumnSpacing - 14, 25, true, titleBarHeight, highlight); mRoutingOutputModules[i].mModule->SetPosition(x, y); if (i >= 0 && i < 8) bottomRowLedColors[i] = GetPadColorForType(mRoutingOutputModules[i].mModule->GetModuleCategory(), true); ofPopMatrix(); ofPopStyle(); } { ofPushMatrix(); ofPushStyle(); ofClipWindow(0, 0, kColumnSpacing, ableton::Push2DisplayBitmap::kHeight * kPixelRatio, true); float x; float y; mDisplayModule->GetPosition(x, y, true); mDisplayModule->SetPosition(3, 72); float titleBarHeight; float highlight; mDisplayModule->DrawFrame(kColumnSpacing - 14, 25, true, titleBarHeight, highlight); mDisplayModule->SetPosition(x, y); ofPopMatrix(); ofPopStyle(); } for (int i = 0; i < 8; ++i) { SetLed(kMidiMessage_Control, i + kAboveScreenButtonRow, topRowLedColors[i]); SetLed(kMidiMessage_Control, i + kBelowScreenButtonRow, bottomRowLedColors[i]); } } int Push2Control::GetPadColorForType(ModuleCategory type, bool enabled) const { int color; switch (type) { case kModuleCategory_Instrument: color = enabled ? 26 : 116; break; case kModuleCategory_Note: color = enabled ? 8 : 80; break; case kModuleCategory_Synth: color = enabled ? 11 : 86; break; case kModuleCategory_Audio: color = enabled ? 18 : 96; break; case kModuleCategory_Modulator: color = enabled ? 22 : 110; break; case kModuleCategory_Pulse: color = enabled ? 9 : 82; break; default: color = enabled ? 118 : 119; break; } return color; } ModuleCategory Push2Control::GetModuleTypeForSpawnList(IUIControl* control) { ModuleCategory moduleType = kModuleCategory_Other; if (control == mSpawnLists.mInstrumentModules.GetList()) moduleType = kModuleCategory_Instrument; if (control == mSpawnLists.mNoteModules.GetList()) moduleType = kModuleCategory_Note; if (control == mSpawnLists.mSynthModules.GetList()) moduleType = kModuleCategory_Synth; if (control == mSpawnLists.mAudioModules.GetList()) moduleType = kModuleCategory_Audio; if (control == mSpawnLists.mModulatorModules.GetList()) moduleType = kModuleCategory_Modulator; if (control == mSpawnLists.mPulseModules.GetList()) moduleType = kModuleCategory_Pulse; if (control == mSpawnLists.mOtherModules.GetList()) moduleType = kModuleCategory_Other; if (control == mSpawnLists.mPlugins.GetList()) moduleType = kModuleCategory_Synth; if (control == mSpawnLists.mPrefabs.GetList()) moduleType = kModuleCategory_Other; return moduleType; } void Push2Control::DrawControls(std::vector<IUIControl*> controls, bool sliders, float yPos) { for (int i = (int)controls.size() - 1; i >= 0; --i) { if (i - mModuleViewOffset < -1 || i - mModuleViewOffset > 8) continue; ADSRDisplay* adsr = dynamic_cast<ADSRDisplay*>(controls[i]); ofRectangle originalRect = controls[i]->GetRect(true); if (adsr != nullptr) { adsr->SetDimensions(80, 30); controls[i]->SetPosition(kColumnSpacing * i + 3, yPos - 13); } else { controls[i]->SetPosition(kColumnSpacing * i + 3, yPos); } ofPushMatrix(); ofClipWindow(kColumnSpacing * i, yPos - 15, kColumnSpacing, 100, true); ofPushStyle(); ModuleCategory moduleType = controls[i]->GetModuleParent()->GetModuleCategory(); if (mScreenDisplayMode == ScreenDisplayMode::kAddModule) moduleType = GetModuleTypeForSpawnList(controls[i]); if (controls[i]->IsShowing()) ofSetColor(IDrawableModule::GetColor(moduleType)); else ofSetColor(100, 100, 100); if (adsr == nullptr) { if (mDisplayModule == this) DrawTextBold(juce::String(controls[i]->Path()).replace("~", "\n").toRawUTF8(), kColumnSpacing * i + 3, yPos - 12, 8); else DrawTextBold(controls[i]->Name(), kColumnSpacing * i + 3, yPos - 5, 14); } controls[i]->Render(); ofPopStyle(); ofPopMatrix(); controls[i]->SetPosition(originalRect.x, originalRect.y); if (adsr != nullptr) adsr->SetDimensions(originalRect.width, originalRect.height); ofPushStyle(); int pushControlIndex = i - mModuleViewOffset; if (sliders && pushControlIndex >= 0 && pushControlIndex < 8 && mNoteHeldState[pushControlIndex]) { DropdownList* dropdown = dynamic_cast<DropdownList*>(mSliderControls[i]); if (dropdown != nullptr) { const float kCentering = 7; float w = dropdown->GetMaxItemWidth(); float h = dropdown->GetNumValues() * DropdownList::kItemSpacing; ofPushMatrix(); ofTranslate(kColumnSpacing * i + 3, yPos + kCentering - h * controls[i]->GetMidiValue()); dropdown->DrawDropdown(w, h, true); ofFill(); ofColor color = IDrawableModule::GetColor(controls[i]->GetModuleParent()->GetModuleCategory()); color.a = 25; ofSetColor(color); //ofCircle(w - 4, h * controls[i]->GetMidiValue(), 2); ofRect(0, h * controls[i]->GetMidiValue() - kCentering, w, controls[i]->GetDimensions().y); ofPopMatrix(); } } ofPopStyle(); } } void Push2Control::RenderPush2Display() { auto mainVG = gNanoVG; gNanoVG = sVG; sDrawingPush2Display = true; DrawToFramebuffer(sVG, sFB, gTime / 300, kPixelRatio); sDrawingPush2Display = false; gNanoVG = mainVG; // Tells the bridge we're done with drawing and the frame can be sent to the display ThePushBridge.Flip(mPixels); } void Push2Control::Poll() { if (mPendingSpawnPitch != -1) { int padNum = mPendingSpawnPitch - 36; int gridX = padNum % 8; int gridY = padNum / 8; int gridIndex = gridX + (7 - gridY) * 8; IDrawableModule* existingModule = mModuleGrid[gridIndex]; ofVec2f newModulePos; if (existingModule != nullptr) { ofRectangle existingModuleRect = existingModule->GetRect(); newModulePos = ofVec2f(existingModuleRect.getMinX(), existingModuleRect.getMaxY() + 40); } else { newModulePos = ofVec2f(ofMap(gridX, 0, 7, mModuleGridRect.getMinX(), mModuleGridRect.getMaxX()), ofMap(gridY, 7, 0, mModuleGridRect.getMinY(), mModuleGridRect.getMaxY())); } for (int i = 0; i < mSpawnLists.GetDropdowns().size(); ++i) { if (mSpawnLists.GetDropdowns()[i]->GetList()->GetValue() != -1) { IDrawableModule* module = mSpawnLists.GetDropdowns()[i]->Spawn(mSpawnLists.GetDropdowns()[i]->GetList()->GetValue()); module->SetPosition(newModulePos.x, newModulePos.y); mSpawnLists.GetDropdowns()[i]->GetList()->SetValue(-1, gTime); mScreenDisplayMode = ScreenDisplayMode::kNormal; SetDisplayModule(module, true); if (existingModule != nullptr && existingModule->GetPatchCableSource() != nullptr) { IClickable* insertTarget = existingModule->GetPatchCableSource()->GetTarget(); existingModule->GetPatchCableSource()->FindValidTargets(); if (existingModule->GetPatchCableSource()->IsValidTarget(module)) existingModule->SetTarget(module); if (module->GetPatchCableSource()) { module->GetPatchCableSource()->FindValidTargets(); if (insertTarget != nullptr && module->GetPatchCableSource()->IsValidTarget(insertTarget)) module->SetTarget(insertTarget); } } break; } } mPendingSpawnPitch = -1; } bool controlsChanged = false; if (mDisplayModule != nullptr && mDisplayModule->HasPush2OverrideControls()) { std::vector<IUIControl*> desiredControls; mDisplayModule->GetPush2OverrideControls(desiredControls); if (desiredControls.size() != mDisplayedControls.size()) { controlsChanged = true; } else { for (size_t i = 0; i < desiredControls.size(); ++i) { if (desiredControls[i] != mDisplayedControls[i]) { controlsChanged = true; break; } } } } if (mDisplayModule != nullptr && mDisplayModule->HasPush2OverrideControls() != mDisplayModuleIsShowingOverrideControls) { controlsChanged = true; mDisplayModuleIsShowingOverrideControls = mDisplayModule->HasPush2OverrideControls(); } if (controlsChanged) UpdateControlList(); } bool Push2Control::AllowRepatch() const { if (mHeldModule) return gTime - mModuleHeldTime > 300; return false; } std::string Push2Control::GetModuleTypeToSpawn() { for (int i = 0; i < mSpawnLists.GetDropdowns().size(); ++i) { if (mSpawnLists.GetDropdowns()[i]->GetList()->GetValue() != -1) return mSpawnLists.GetDropdowns()[i]->GetList()->GetDisplayValue(mSpawnLists.GetDropdowns()[i]->GetList()->GetValue()); } return ""; } void Push2Control::SetDisplayModule(IDrawableModule* module, bool addToHistory) { mDisplayModule = module; if (dynamic_cast<IPush2GridController*>(mDisplayModule) != nullptr) mDisplayModuleCanControlGrid = true; else mDisplayModuleCanControlGrid = false; mModuleViewOffset = 0; mModuleViewOffsetSmoothed = 0; UpdateControlList(); mDisplayModuleSnapshots = nullptr; std::vector<IDrawableModule*> modules; TheSynth->GetAllModules(modules); for (auto* searchModule : modules) { Snapshots* snapshotsModule = dynamic_cast<Snapshots*>(searchModule); if (snapshotsModule != nullptr) { if (snapshotsModule->IsTargetingModule(module)) mDisplayModuleSnapshots = snapshotsModule; } } if (module != nullptr && addToHistory && (mModuleHistory.empty() || mModuleHistory[mModuleHistory.size() - 1] != module)) { while (mModuleHistory.size() > mModuleHistoryPosition + 1) mModuleHistory.pop_back(); mModuleHistory.push_back(module); ++mModuleHistoryPosition; } if (mScreenDisplayMode == ScreenDisplayMode::kRouting) UpdateRoutingModules(); } void Push2Control::UpdateControlList() { mSliderControls.clear(); mButtonControls.clear(); std::vector<IUIControl*> controls; if (mScreenDisplayMode == ScreenDisplayMode::kAddModule) { controls = mSpawnModuleControls; } else if (mDisplayModule == this) { controls = mFavoriteControls; } else if (mDisplayModule != nullptr) { if (mDisplayModule->HasPush2OverrideControls()) mDisplayModule->GetPush2OverrideControls(controls); else controls = mDisplayModule->GetUIControls(); } for (int i = 0; i < controls.size(); ++i) { if (controls[i]->IsSliderControl() && controls[i]->GetShouldSaveState()) mSliderControls.push_back(controls[i]); if (controls[i]->IsButtonControl() && (controls[i]->GetShouldSaveState() || dynamic_cast<ClickButton*>(controls[i]) != nullptr)) mButtonControls.push_back(controls[i]); } mDisplayedControls = controls; } void Push2Control::AddFavoriteControl(IUIControl* control) { if (!VectorContains(control, mFavoriteControls)) { mFavoriteControls.push_back(control); UpdateControlList(); } } void Push2Control::RemoveFavoriteControl(IUIControl* control) { auto iter = std::find(mFavoriteControls.begin(), mFavoriteControls.end(), control); if (iter != mFavoriteControls.end()) { mFavoriteControls.erase(iter); UpdateControlList(); } } void Push2Control::BookmarkModuleToSlot(int slotIndex, IDrawableModule* module) { mBookmarkSlots[slotIndex] = module; mAddModuleBookmarkButtonHeld = false; } void Push2Control::SwitchToBookmarkedModule(int slotIndex) { if (mBookmarkSlots[slotIndex] != nullptr && !mBookmarkSlots[slotIndex]->IsDeleted()) SetDisplayModule(mBookmarkSlots[slotIndex], true); } void Push2Control::SetLed(MidiMessageType type, int index, int color, int flashColor /*=-1*/) { if (type == kMidiMessage_Control) index += 128; assert(index >= 0 && index < 128 * 2); int channel = 1; if (flashColor != -1) channel = 10; int stateValue = color | channel << 8; if (mLedState[index] != stateValue) { //bool isPulse = (channel >= 7 && channel <= 11); mLedState[index] = stateValue; if (index < 128) { if (flashColor != -1) mDevice.SendNote(gTime, index, flashColor, false, -1); mDevice.SendNote(gTime, index, color, false, channel); } else { if (flashColor != -1) mDevice.SendCC(index - 128, flashColor); mDevice.SendCC(index - 128, color, channel); } } } void Push2Control::SetGridControlInterface(IPush2GridController* controller, IDrawableModule* module) { mGridControlInterface = controller; mGridControlModule = module; SetLed(kMidiMessage_Control, GetGridControllerOption1Control(), 0); SetLed(kMidiMessage_Control, GetGridControllerOption2Control(), 0); } void Push2Control::OnMidiNote(MidiNote& note) { if (mGridControlInterface != nullptr) { bool handled = mGridControlInterface->OnPush2Control(this, kMidiMessage_Note, note.mPitch, note.mVelocity); if (handled) return; } if (note.mPitch >= 0 && note.mPitch <= 7) //main encoders { if (mScreenDisplayMode == ScreenDisplayMode::kNormal || mScreenDisplayMode == ScreenDisplayMode::kMap) { int controlIndex = note.mPitch + mModuleViewOffset; if (controlIndex < mSliderControls.size()) { if (note.mVelocity > 0) { mSliderControls[controlIndex]->StartBeacon(); if (mNewButtonHeld) { AddFavoriteControl(mSliderControls[controlIndex]); } else if (mDeleteButtonHeld) { RemoveFavoriteControl(mSliderControls[controlIndex]); } else if (mLFOButtonHeld) { FloatSlider* slider = dynamic_cast<FloatSlider*>(mSliderControls[controlIndex]); if (slider != nullptr) { bool hadLFO = (slider->GetLFO() != nullptr); FloatSliderLFOControl* lfo = slider->AcquireLFO(); if (!hadLFO) lfo->SetLFOEnabled(true); SetDisplayModule(lfo, true); } } else if (mAutomateButtonHeld) { if (mSliderControls[controlIndex] != nullptr && mCurrentControlRecorder == nullptr) { std::vector<IDrawableModule*> modules; TheSynth->GetAllModules(modules); for (auto* searchModule : modules) { ControlRecorder* controlRecorderModule = dynamic_cast<ControlRecorder*>(searchModule); if (controlRecorderModule != nullptr) { if (controlRecorderModule->GetPatchCableSource()->GetTarget() == mSliderControls[controlIndex]) mCurrentControlRecorder = controlRecorderModule; } } if (mCurrentControlRecorder == nullptr) //couldn't find one, so make one { ModuleFactory::Spawnable spawnable; spawnable.mLabel = "controlrecorder"; mCurrentControlRecorder = dynamic_cast<ControlRecorder*>(TheSynth->SpawnModuleOnTheFly(spawnable, mSliderControls[controlIndex]->GetRect().getMaxX() + 40, mSliderControls[controlIndex]->GetPosition().y)); mCurrentControlRecorder->SetTarget(mSliderControls[controlIndex]); } mCurrentControlRecorder->SetEnabled(true); mCurrentControlRecorder->SetRecording(true); } } else if (mInMidiControllerBindMode) { sBindToUIControl = mSliderControls[controlIndex]; } if (mHeldModule && AllowRepatch()) { PatchCableSource* cable = mHeldModule->GetPatchCableSource(); if (mHeldModulePatchCableIndex > 0) cable = mHeldModule->GetPatchCableSources()[mHeldModulePatchCableIndex]; if (cable != nullptr) { cable->FindValidTargets(); if (cable->IsValidTarget(mSliderControls[controlIndex])) cable->SetTarget(mSliderControls[controlIndex]); } } } else { if (sBindToUIControl == mSliderControls[controlIndex]) sBindToUIControl = nullptr; } } } if (mScreenDisplayMode == ScreenDisplayMode::kAddModule) { if (note.mVelocity > 0) { for (int i = 0; i < mSpawnLists.GetDropdowns().size(); ++i) { if (i != note.mPitch) mSpawnLists.GetDropdowns()[i]->GetList()->SetValue(-1, gTime); } } } if (note.mVelocity > 0) mHeldKnobIndex = note.mPitch; else mHeldKnobIndex = -1; } else if (note.mPitch >= 36 && note.mPitch <= 99 && mGridControlInterface == nullptr) //pads { if (mScreenDisplayMode == ScreenDisplayMode::kAddModule && mSelectedGridSpawnListIndex != -1 && mSelectedGridSpawnListIndex < (int)mSpawnLists.GetDropdowns().size()) { if (note.mVelocity > 0) { auto* list = mSpawnLists.GetDropdowns()[mSelectedGridSpawnListIndex]->GetList(); int padNum = note.mPitch - 36; int gridX = padNum % 8; int gridY = padNum / 8; int gridIndex = gridX + (7 - gridY) * 8 + mModuleViewOffset * 8; if (gridIndex < list->GetNumValues()) { list->SetValueDirect(gridIndex, gTime); mSelectedGridSpawnListIndex = -1; } } } else if (mScreenDisplayMode == ScreenDisplayMode::kAddModule) { if (note.mVelocity > 0) mPendingSpawnPitch = note.mPitch; } else if (mGridControlInterface == nullptr) { int padNum = note.mPitch - 36; int gridX = padNum % 8; int gridY = padNum / 8; int gridIndex = gridX + (7 - gridY) * 8; if (mModuleGrid[gridIndex] != nullptr) { if (note.mVelocity > 0 && mHeldModule == nullptr) mModuleHeldTime = gTime; if (note.mVelocity == 0 && !mRepatchedHeldModule) SetDisplayModule(mModuleGrid[gridIndex], true); } if (note.mVelocity > 0) { if (mHeldModule != nullptr) { PatchCableSource* heldModuleCable = mHeldModule->GetPatchCableSource(); if (mHeldModulePatchCableIndex > 0) heldModuleCable = mHeldModule->GetPatchCableSources()[mHeldModulePatchCableIndex]; if (AllowRepatch() && heldModuleCable != nullptr) { IDrawableModule* touchedModule = mModuleGrid[gridIndex]; heldModuleCable->FindValidTargets(); if (heldModuleCable->IsValidTarget(touchedModule)) { //insert if (mShiftHeld && touchedModule != nullptr && touchedModule->GetPatchCableSource() != nullptr) { IClickable* oldTarget = heldModuleCable->GetTarget(); touchedModule->GetPatchCableSource()->FindValidTargets(); if (touchedModule->GetPatchCableSource()->IsValidTarget(oldTarget)) touchedModule->SetTarget(oldTarget); } heldModuleCable->SetTarget(touchedModule); } else { heldModuleCable->ClearPatchCables(); } mRepatchedHeldModule = true; } } else { mHeldModule = mModuleGrid[gridIndex]; mRepatchedHeldModule = false; mHeldModulePatchCableIndex = 0; } } else { mHeldModule = nullptr; } } } else { //ofLog() << "note " << note.mPitch << " " << note.mVelocity; } mNoteHeldState[note.mPitch] = note.mVelocity > 0; } void Push2Control::OnMidiControl(MidiControl& control) { if (mGridControlInterface != nullptr) { bool handled = mGridControlInterface->OnPush2Control(this, kMidiMessage_Control, control.mControl, control.mValue); if (handled) return; } if (control.mControl >= 71 && control.mControl <= 78) //main encoders { int controlIndex = control.mControl - 71 + mModuleViewOffset; bool justResetParameter = gTime - mLastResetTime < 1000; if (controlIndex < mSliderControls.size() && !justResetParameter) { float currentNormalized = mSliderControls[controlIndex]->GetMidiValue(); float increment = control.mValue < 64 ? control.mValue : control.mValue - 128; increment *= mShiftHeld ? .0005f : .005f; FloatSlider* floatSlider = dynamic_cast<FloatSlider*>(mSliderControls[controlIndex]); if (floatSlider && floatSlider->GetModulator() && floatSlider->GetModulator()->Active() && floatSlider->GetModulator()->CanAdjustRange()) { IModulator* modulator = floatSlider->GetModulator(); float min = floatSlider->GetMin(); float max = floatSlider->GetMax(); float modMin = ofMap(modulator->GetMin(), min, max, 0, 1); float modMax = ofMap(modulator->GetMax(), min, max, 0, 1); modulator->GetMin() = ofMap(modMin - increment, 0, 1, min, max, K(clamp)); modulator->GetMax() = ofMap(modMax + increment, 0, 1, min, max, K(clamp)); } else { mSliderControls[controlIndex]->SetFromMidiCC(currentNormalized + increment, NextBufferTime(false), false); } } } else if (control.mControl >= kAboveScreenButtonRow && control.mControl < kAboveScreenButtonRow + 8) //buttons below encoders { int controlIndex = control.mControl - kAboveScreenButtonRow; if (mScreenDisplayMode == ScreenDisplayMode::kNormal || mScreenDisplayMode == ScreenDisplayMode::kMap) { controlIndex += mModuleViewOffset; if (controlIndex < mButtonControls.size()) { if (control.mValue > 0) { if (mNewButtonHeld) { mButtonControls[controlIndex]->StartBeacon(); AddFavoriteControl(mButtonControls[controlIndex]); } else if (mDeleteButtonHeld) { mButtonControls[controlIndex]->StartBeacon(); RemoveFavoriteControl(mButtonControls[controlIndex]); } else if (mInMidiControllerBindMode) { sBindToUIControl = mButtonControls[controlIndex]; } else { float current = mButtonControls[controlIndex]->GetMidiValue(); float newValue = current > 0 ? 0 : 1; if (dynamic_cast<ClickButton*>(mButtonControls[controlIndex]) != nullptr) newValue = 1; //always "press" a button mButtonControls[controlIndex]->SetFromMidiCC(newValue, NextBufferTime(false), false); } } else { if (sBindToUIControl == mButtonControls[controlIndex]) sBindToUIControl = nullptr; } } } if (mScreenDisplayMode == ScreenDisplayMode::kAddModule) { if (control.mValue > 0 && controlIndex < mSpawnModuleControls.size()) { if (mSelectedGridSpawnListIndex != controlIndex) mSelectedGridSpawnListIndex = controlIndex; else mSelectedGridSpawnListIndex = -1; for (int i = 0; i < mSpawnLists.GetDropdowns().size(); ++i) mSpawnLists.GetDropdowns()[i]->GetList()->SetValue(-1, gTime); mModuleViewOffset = 0; mModuleViewOffsetSmoothed = 0; } } if (mScreenDisplayMode == ScreenDisplayMode::kRouting) { int index = control.mControl - kAboveScreenButtonRow; if (control.mValue > 0 && index < mRoutingInputModules.size()) SetDisplayModule(mRoutingInputModules[index].mModule, true); } } else if (control.mControl == 14) //leftmost clicky encoder { int increment = control.mValue < 64 ? control.mValue : control.mValue - 128; if (mScreenDisplayMode == ScreenDisplayMode::kAddModule) mModuleViewOffset = std::max(0, mModuleViewOffset + increment); else mModuleViewOffset = (int)ofClamp(mModuleViewOffset + increment, 0, MAX(0, (int)MAX(mSliderControls.size(), mButtonControls.size()) - 8)); } else if (control.mControl == 15) //encoder next to above encoder { float increment = control.mValue < 64 ? control.mValue : control.mValue - 128; increment *= .05f; mModuleListOffset += increment; } else if (control.mControl >= kBelowScreenButtonRow && control.mControl < kBelowScreenButtonRow + 8) //buttons below screen { if (mScreenDisplayMode == ScreenDisplayMode::kNormal || mScreenDisplayMode == ScreenDisplayMode::kMap) { int moduleIndex = control.mControl - kBelowScreenButtonRow + round(mModuleListOffset); if (control.mValue > 0 && moduleIndex < mModules.size()) SetDisplayModule(mModules[moduleIndex], true); } if (mScreenDisplayMode == ScreenDisplayMode::kRouting) { int index = control.mControl - kBelowScreenButtonRow; if (control.mValue > 0 && index < mRoutingOutputModules.size()) SetDisplayModule(mRoutingOutputModules[index].mModule, true); } } else if (control.mControl == kSetupButton && control.mValue > 0) { mInMidiControllerBindMode = !mInMidiControllerBindMode; } else if (control.mControl == kNewButton) { mNewButtonHeld = control.mValue > 0; } else if (control.mControl == kDeleteButton) { mDeleteButtonHeld = control.mValue > 0; } else if (control.mControl == kFixedLengthButton) { mLFOButtonHeld = control.mValue > 0; } else if (control.mControl == kAutomateButton) { mAutomateButtonHeld = control.mValue > 0; if (!mAutomateButtonHeld && mCurrentControlRecorder != nullptr) { mCurrentControlRecorder->SetRecording(false); mCurrentControlRecorder = nullptr; } } else if (control.mControl == kMasterButton) { mAddModuleBookmarkButtonHeld = control.mValue > 0; } else if (control.mControl == kTapTempoButton) { if (gHoveredModule != nullptr && gHoveredModule != mDisplayModule) SetDisplayModule(gHoveredModule, true); } else if (control.mControl == kMetronomeButton) { SetDisplayModule(this, true); } else if (control.mControl == kAddDeviceButton) { if (control.mValue > 0) { if (mScreenDisplayMode == ScreenDisplayMode::kAddModule) { mScreenDisplayMode = ScreenDisplayMode::kNormal; } else { mScreenDisplayMode = ScreenDisplayMode::kAddModule; SetGridControlInterface(nullptr, nullptr); for (int i = 0; i < mSpawnLists.GetDropdowns().size(); ++i) mSpawnLists.GetDropdowns()[i]->GetList()->SetValue(-1, gTime); mSelectedGridSpawnListIndex = -1; } mModuleViewOffset = 0; mModuleViewOffsetSmoothed = 0; mModuleListOffset = 0; mModuleListOffsetSmoothed = 0; UpdateControlList(); } } else if (control.mControl == kUserButton) { if (control.mValue > 0) { if (mScreenDisplayMode == ScreenDisplayMode::kMap) { mScreenDisplayMode = ScreenDisplayMode::kNormal; } else { mScreenDisplayMode = ScreenDisplayMode::kMap; } } } else if (control.mControl == kConvertButton) { if (control.mValue > 0 && mDisplayModule != nullptr) { if (mDisplayModule->GetPatchCableSource() != nullptr && mDisplayModule->GetPatchCableSource()->GetConnectionType() == kConnectionType_Audio && mDisplayModule->GetPatchCableSource()->GetTarget() != nullptr && dynamic_cast<IDrawableModule*>(mDisplayModule->GetPatchCableSource()->GetTarget())->GetTypeName() != "looper") { ModuleFactory::Spawnable spawnable; spawnable.mLabel = "looper"; IDrawableModule* looper = TheSynth->SpawnModuleOnTheFly(spawnable, mDisplayModule->GetRect().getMinX(), mDisplayModule->GetRect().getMaxY() + 40); looper->SetTarget(mDisplayModule->GetPatchCableSource()->GetTarget()); mDisplayModule->SetTarget(looper); SetDisplayModule(looper); } if (mDisplayModule->GetPatchCableSource() != nullptr && mDisplayModule->GetPatchCableSource()->GetConnectionType() == kConnectionType_Note && mDisplayModule->GetPatchCableSource()->GetTarget() != nullptr && dynamic_cast<IDrawableModule*>(mDisplayModule->GetPatchCableSource()->GetTarget())->GetTypeName() != "notelooper") { ModuleFactory::Spawnable spawnable; spawnable.mLabel = "notelooper"; IDrawableModule* notelooper = TheSynth->SpawnModuleOnTheFly(spawnable, mDisplayModule->GetRect().getMinX(), mDisplayModule->GetRect().getMaxY() + 40); notelooper->SetTarget(mDisplayModule->GetPatchCableSource()->GetTarget()); mDisplayModule->SetTarget(notelooper); SetDisplayModule(notelooper); } } } else if (control.mControl == kDoubleLoopButton) { if (control.mValue > 0) { Looper* looper = dynamic_cast<Looper*>(mDisplayModule); if (looper != nullptr) looper->SetNumBars(looper->GetNumBars() * 2); NoteLooper* noteLooper = dynamic_cast<NoteLooper*>(mDisplayModule); if (noteLooper != nullptr) noteLooper->SetNumMeasures(noteLooper->GetNumMeasures() * 2); } } else if (control.mControl == kDeviceButton || control.mControl == kMixButton || control.mControl == kBrowseButton || control.mControl == kClipButton) { if (control.mValue > 0) { int index = 0; if (control.mControl == kDeviceButton) index = 0; if (control.mControl == kMixButton) index = 1; if (control.mControl == kBrowseButton) index = 2; if (control.mControl == kClipButton) index = 3; if (mAddTrackHeld) { if (mDisplayModuleSnapshots == nullptr) { ModuleFactory::Spawnable spawnable; spawnable.mLabel = "snapshots"; mDisplayModuleSnapshots = dynamic_cast<Snapshots*>(TheSynth->SpawnModuleOnTheFly(spawnable, mDisplayModule->GetRect().getMaxX() + 40, mDisplayModule->GetPosition().y)); mDisplayModuleSnapshots->AddSnapshotTarget(mDisplayModule); } if (mDisplayModuleSnapshots != nullptr) mDisplayModuleSnapshots->StoreSnapshot(index, true); } else { if (mDisplayModuleSnapshots != nullptr) mDisplayModuleSnapshots->SetSnapshot(index, gTime); } } } else if (control.mControl == kUpButton || control.mControl == kDownButton || control.mControl == kLeftButton || control.mControl == kRightButton) { if (control.mValue > 0) { ofVec2f direction; if (control.mControl == kUpButton) direction.y -= 1; if (control.mControl == kDownButton) direction.y += 1; if (control.mControl == kLeftButton) direction.x -= 1; if (control.mControl == kRightButton) direction.x += 1; if (mShiftHeld && mDisplayModule) { ofVec2f pos = mDisplayModule->GetPosition(); pos += direction * 50; mDisplayModule->SetPosition(pos.x, pos.y); } else { TheSynth->PanView(direction.x * -100, direction.y * -100); } } } else if (control.mControl == kPageLeftButton || control.mControl == kPageRightButton || control.mControl == kOctaveUpButton || control.mControl == kOctaveDownButton) { if (control.mValue > 0) { if (mHeldKnobIndex == -1) { int direction = 0; if (control.mControl == kPageLeftButton) direction -= 1; if (control.mControl == kPageRightButton) direction += 1; if (direction != 0) { int newHistoryPos = mModuleHistoryPosition + direction; if (newHistoryPos >= 0 && newHistoryPos < mModuleHistory.size()) { mModuleHistoryPosition = newHistoryPos; SetDisplayModule(mModuleHistory[mModuleHistoryPosition], false); } } if (control.mControl == kOctaveUpButton) { std::vector<IDrawableModule*> modules; TheSynth->GetAllModules(modules); for (auto* module : modules) { if (module->GetPatchCableSource() != nullptr && module->GetPatchCableSource()->GetTarget() == mDisplayModule && dynamic_cast<Snapshots*>(module) == nullptr) //don't jump up to a snapshot, just things targeting as input { SetDisplayModule(module, true); break; } } } if (control.mControl == kOctaveDownButton && mDisplayModule != nullptr) { IDrawableModule* target = (mDisplayModule->GetPatchCableSource() != nullptr) ? dynamic_cast<IDrawableModule*>(mDisplayModule->GetPatchCableSource()->GetTarget()) : nullptr; if (target) SetDisplayModule(target, true); } } else { int controlIndex = mHeldKnobIndex + mModuleViewOffset; if (controlIndex < mSliderControls.size() && (mScreenDisplayMode == ScreenDisplayMode::kNormal || mScreenDisplayMode == ScreenDisplayMode::kMap)) { if (control.mControl == kPageRightButton) mSliderControls[controlIndex]->Increment(1); if (control.mControl == kPageLeftButton) mSliderControls[controlIndex]->Increment(-1); if (control.mControl == kOctaveUpButton) mSliderControls[controlIndex]->Double(); if (control.mControl == kOctaveDownButton) mSliderControls[controlIndex]->Halve(); } } } } else if (control.mControl == kNoteButton) { if (control.mValue > 0) { IPush2GridController* controller = dynamic_cast<IPush2GridController*>(mDisplayModule); if (controller != nullptr && controller != mGridControlInterface) { SetGridControlInterface(controller, mDisplayModule); for (int i = 36; i <= 99; ++i) SetLed(kMidiMessage_Note, i, 0); //turn touch strip off std::string touchStripLights = { 0x00, 0x21, 0x1D, 0x01, 0x01, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; GetDevice()->SendSysEx(touchStripLights); mGridControlInterface->OnPush2Connect(); mScreenDisplayMode = ScreenDisplayMode::kNormal; UpdateControlList(); } } } else if (control.mControl == kSessionButton) { if (control.mValue > 0) SetGridControlInterface(nullptr, nullptr); } else if (control.mControl == kScaleButton) { if (control.mValue > 0 && mGridControlModule != nullptr) { SetDisplayModule(mGridControlModule, true); } } else if (control.mControl == kLayoutButton && mDisplayModule != nullptr) { if (control.mValue > 0) { if (mScreenDisplayMode == ScreenDisplayMode::kRouting) { mScreenDisplayMode = ScreenDisplayMode::kNormal; } else { mScreenDisplayMode = ScreenDisplayMode::kRouting; UpdateRoutingModules(); } } } else if (control.mControl >= kQuantizeButtonSection && control.mControl < kQuantizeButtonSection + kNumQuantizeButtons) //quantization level buttons to the right of the main grid, used to bookmark modules { if (control.mValue > 0) { int i = control.mControl - kQuantizeButtonSection; if (mAddModuleBookmarkButtonHeld) BookmarkModuleToSlot(i, mDisplayModule); if (mDeleteButtonHeld) BookmarkModuleToSlot(i, nullptr); else SwitchToBookmarkedModule(i); } } else if (control.mControl == kShiftButton) { mShiftHeld = control.mValue > 0; } else if (control.mControl == kAddTrackButton) { mAddTrackHeld = control.mValue > 0; } else if (control.mControl == kSelectButton) { if (control.mValue > 0 && mDisplayModule != nullptr) { if (mHeldModule != nullptr && mHeldModule->GetPatchCableSources().size() > 1) { mHeldModulePatchCableIndex = (mHeldModulePatchCableIndex + 1) % mHeldModule->GetPatchCableSources().size(); mTextPopup = "setting selected cable output index to " + ofToString(mHeldModulePatchCableIndex); mTextPopupTime = gTime; } else if (mHeldKnobIndex == -1) { ofRectangle rect = mDisplayModule->GetRect(); TheSynth->PanTo(rect.getCenter().x, rect.getCenter().y); } else { int controlIndex = mHeldKnobIndex + mModuleViewOffset; if (controlIndex < mSliderControls.size() && (mScreenDisplayMode == ScreenDisplayMode::kNormal || mScreenDisplayMode == ScreenDisplayMode::kMap)) { mSliderControls[controlIndex]->ResetToOriginal(); mLastResetTime = gTime; } } } } else if (control.mControl == kPlayButton) { if (control.mValue > 0) { if (TheSynth->IsAudioPaused()) TheTransport->Reset(); else TheSynth->SetAudioPaused(true); } } else if (control.mControl == kCircleButton) { if (control.mValue > 0 && mDisplayModule != nullptr) { Checkbox* enabledCheckbox = mDisplayModule->GetEnabledCheckbox(); if (enabledCheckbox != nullptr) enabledCheckbox->SetValue(mDisplayModule->IsEnabled() ? 0 : 1, gTime); else mDisplayModule->SetEnabled(!mDisplayModule->IsEnabled()); } } else { ofLog() << "control " << control.mControl << " " << control.mValue; } } void Push2Control::OnMidiPitchBend(MidiPitchBend& pitchBend) { if (mGridControlInterface != nullptr) { bool handled = mGridControlInterface->OnPush2Control(this, kMidiMessage_PitchBend, pitchBend.mChannel, pitchBend.mValue); if (handled) return; } float value = pitchBend.mValue / MidiDevice::kPitchBendMax; TheSynth->SetZoomLevel(pow(2, value * 2 - 1) + .1f); //ofLog() << "pitchbend " << pitchBend.mChannel << " " << pitchBend.mValue; } int Push2Control::GetGridControllerOption1Control() const { return kRepeatButton; } int Push2Control::GetGridControllerOption2Control() const { return kAccentButton; } void Push2Control::UpdateRoutingModules() { mRoutingInputModules.clear(); mRoutingOutputModules.clear(); std::vector<IDrawableModule*> modules; TheSynth->GetAllModules(modules); for (auto* module : modules) { for (auto* source : module->GetPatchCableSources()) { if (source->GetTarget() == mDisplayModule) mRoutingInputModules.push_back(Routing(module, module->GetPatchCableSource()->GetColor())); } } for (auto* source : mDisplayModule->GetPatchCableSources()) { for (auto* cable : source->GetPatchCables()) { IDrawableModule* target = dynamic_cast<IDrawableModule*>(cable->GetTarget()); if (target != nullptr) mRoutingOutputModules.push_back(Routing(target, cable->GetOwner()->GetColor())); } } } bool Push2Control::IsIgnorableModule(IDrawableModule* module) { return module == TheTitleBar || module == TheSaveDataPanel || module == TheQuickSpawnMenu || module == TheSynth->GetUserPrefsEditor() || module == TheQuickSpawnMenu->GetMainContainerFollower(); } std::vector<IDrawableModule*> Push2Control::SortModules(std::vector<IDrawableModule*> modules) { std::vector<IDrawableModule*> output; for (int i = 0; i < modules.size(); ++i) AddModuleChain(modules[i], modules, output, 0); return output; } void Push2Control::AddModuleChain(IDrawableModule* module, std::vector<IDrawableModule*>& modules, std::vector<IDrawableModule*>& output, int depth) { if (depth > 100) //avoid infinite recursion if there's a patching loop return; if (!VectorContains(module, output)) { //look for parents for (int i = 0; i < modules.size(); ++i) { IClickable* target = nullptr; if (modules[i]->GetPatchCableSource() != nullptr) target = modules[i]->GetPatchCableSource()->GetTarget(); if (target != nullptr && target == dynamic_cast<IClickable*>(module)) { AddModuleChain(modules[i], modules, output, depth + 1); } } if (VectorContains(module, output)) //got added above return; output.push_back(module); //look for children for (int i = 0; i < modules.size(); ++i) { IClickable* target = nullptr; if (module->GetPatchCableSource() != nullptr) target = module->GetPatchCableSource()->GetTarget(); if (target != nullptr && target == dynamic_cast<IClickable*>(modules[i])) { AddModuleChain(modules[i], modules, output, depth + 1); } } } } ```
/content/code_sandbox/Source/Push2Control.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
20,671
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== ModulatorGravity.cpp Created: 30 Apr 2020 3:56:51pm Author: Ryan Challinor ============================================================================== */ #include "ModulatorGravity.h" #include "Profiler.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "UIControlMacros.h" ModulatorGravity::ModulatorGravity() { } void ModulatorGravity::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } void ModulatorGravity::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); FLOATSLIDER(mGravitySlider, "gravity", &mGravity, -1, 1); FLOATSLIDER(mKickAmountSlider, "kick amt", &mKickAmount, -5, 5); FLOATSLIDER(mDragSlider, "drag", &mDrag, 0, .01f); BUTTON(mKickButton, "kick"); ENDUIBLOCK(mWidth, mHeight); mTargetCable = new PatchCableSource(this, kConnectionType_Modulator); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); } ModulatorGravity::~ModulatorGravity() { TheTransport->RemoveAudioPoller(this); } void ModulatorGravity::DrawModule() { if (Minimized() || IsVisible() == false) return; mGravitySlider->Draw(); mKickAmountSlider->Draw(); mDragSlider->Draw(); mKickButton->Draw(); } void ModulatorGravity::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { OnModulatorRepatch(); } void ModulatorGravity::OnTransportAdvanced(float amount) { float dt = amount * TheTransport->MsPerBar(); float newVelocity = mVelocity + mGravity / 100000 * dt; newVelocity -= newVelocity * mDrag * dt; float newValue = ofClamp(mValue + newVelocity * dt, 0, 1); mVelocity = (newValue - mValue) / dt; mValue = newValue; } float ModulatorGravity::Value(int samplesIn) { ComputeSliders(samplesIn); //return ofClamp(mRamp.Value(gTime + samplesIn * gInvSampleRateMs), GetMin(), GetMax()); return ofLerp(GetMin(), GetMax(), mValue); //TODO(integrate over samples) } void ModulatorGravity::OnPulse(double time, float velocity, int flags) { Kick(velocity); } void ModulatorGravity::ButtonClicked(ClickButton* button, double time) { if (button == mKickButton) Kick(1); } void ModulatorGravity::Kick(float strength) { mVelocity += mKickAmount / 1000 * strength; } void ModulatorGravity::SaveLayout(ofxJSONElement& moduleInfo) { } void ModulatorGravity::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void ModulatorGravity::SetUpFromSaveData() { } ```
/content/code_sandbox/Source/ModulatorGravity.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
765
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // VoiceSetter.cpp // Bespoke // // Created by Ryan Challinor on 6/17/15. // // #include "VoiceSetter.h" #include "SynthGlobals.h" void VoiceSetter::CreateUIControls() { IDrawableModule::CreateUIControls(); mVoiceSlider = new IntSlider(this, "voice index", 5, 2, 80, 15, &mVoiceIdx, 0, kNumVoices - 1); } void VoiceSetter::DrawModule() { if (Minimized() || IsVisible() == false) return; mVoiceSlider->Draw(); } void VoiceSetter::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mVoiceSlider) mNoteOutput.Flush(time); } void VoiceSetter::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { PlayNoteOutput(time, pitch, velocity, mVoiceIdx, modulation); } void VoiceSetter::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void VoiceSetter::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/VoiceSetter.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
371
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // VinylTempoControl.h // Bespoke // // Created by Ryan Challinor on 12/18/14. // // #pragma once #include <iostream> #include "IDrawableModule.h" #include "IAudioProcessor.h" #include "IModulator.h" // clang-format off extern "C" { #include "xwax/timecoder.h" } // clang-format on class VinylProcessor { public: VinylProcessor(int sampleRate); ~VinylProcessor(); void Process(float* left, float* right, int numSamples); float GetPitch() { return mPitch; } bool GetStopped() { return mHasSignal == false; } //@TODO(Noxy): There is no way for mHasSignal to go true so GetStopped() (which is used in other places) is always true. private: int mSampleRate; float mPitch{ 0 }; bool mHasSignal{ false }; timecoder mTimecoder; }; class VinylTempoControl : public IDrawableModule, public IAudioProcessor, public IModulator { public: VinylTempoControl(); ~VinylTempoControl(); static IDrawableModule* Create() { return new VinylTempoControl(); } static bool AcceptsAudio() { return true; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } bool ShouldSuppressAutomaticOutputCable() override { return true; } void SetEnabled(bool enabled) override { mEnabled = enabled; } void CreateUIControls() override; void Process(double time) override; void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; //IModulator float Value(int samplesIn = 0) override; bool Active() const override { return mEnabled; } bool CanAdjustRange() const override { return false; } void CheckboxUpdated(Checkbox* checkbox, double time) override; void SaveLayout(ofxJSONElement& moduleInfo) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 1; } bool IsEnabled() const override { return mEnabled; } private: bool CanStartVinylControl(); //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = 90; height = 20; } bool mUseVinylControl{ false }; Checkbox* mUseVinylControlCheckbox{ nullptr }; float mReferencePitch{ 1 }; VinylProcessor mVinylProcessor; //float* mModulationBuffer; float mSpeed{ 1 }; }; ```
/content/code_sandbox/Source/VinylTempoControl.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
731
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== NoteStepper.cpp Created: 15 Jul 2021 9:11:23pm Author: Ryan Challinor ============================================================================== */ #include "NoteStepper.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "UIControlMacros.h" NoteStepper::NoteStepper() { for (int i = 0; i < 128; ++i) mLastNoteDestinations[i] = -1; } void NoteStepper::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK(3, 3, 15 + (kMaxDestinations - 1) * 15); BUTTON(mResetButton, "reset"); INTSLIDER(mLengthSlider, "length", &mLength, 1, kMaxDestinations); ENDUIBLOCK(mWidth, mHeight); mHeight += 15; for (int i = 0; i < kMaxDestinations; ++i) { mDestinationCables[i] = new AdditionalNoteCable(); mDestinationCables[i]->SetPatchCableSource(new PatchCableSource(this, kConnectionType_Note)); mDestinationCables[i]->GetPatchCableSource()->SetOverrideCableDir(ofVec2f(0, 1), PatchCableSource::Side::kBottom); AddPatchCableSource(mDestinationCables[i]->GetPatchCableSource()); mDestinationCables[i]->GetPatchCableSource()->SetManualPosition(10 + i * 15, mHeight - 8); } GetPatchCableSource()->SetEnabled(false); } void NoteStepper::DrawModule() { if (Minimized() || IsVisible() == false) return; mResetButton->Draw(); mLengthSlider->Draw(); for (int i = 0; i < kMaxDestinations; ++i) { mDestinationCables[i]->GetPatchCableSource()->SetEnabled(i < mLength); if (i == mCurrentDestinationIndex) { ofPushStyle(); ofSetColor(255, 255, 255); ofCircle(10 + i * 15, mHeight - 8, 6); ofPopStyle(); } } } void NoteStepper::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { int selectedDestination = 0; if (velocity > 0) { if (time > mLastNoteOnTime + 10 || !mAllowChords) //slop, to make a chord count as a single step mCurrentDestinationIndex = (mCurrentDestinationIndex + 1) % mLength; selectedDestination = mCurrentDestinationIndex; mLastNoteOnTime = time; if (mLastNoteDestinations[pitch] != -1 && mLastNoteDestinations[pitch] != selectedDestination) SendNoteToIndex(mLastNoteDestinations[pitch], time, pitch, 0, voiceIdx, modulation); mLastNoteDestinations[pitch] = selectedDestination; } else { selectedDestination = mLastNoteDestinations[pitch]; if (selectedDestination == -1) return; mLastNoteDestinations[pitch] = -1; } SendNoteToIndex(selectedDestination, time, pitch, velocity, voiceIdx, modulation); } void NoteStepper::SendNoteToIndex(int index, double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { mDestinationCables[index]->PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void NoteStepper::SendCC(int control, int value, int voiceIdx) { SendCCOutput(control, value, voiceIdx); } void NoteStepper::ButtonClicked(ClickButton* button, double time) { if (button == mResetButton) mCurrentDestinationIndex = -1; } void NoteStepper::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadBool("allow_chords", moduleInfo, false); SetUpFromSaveData(); } void NoteStepper::SetUpFromSaveData() { mAllowChords = mModuleSaveData.GetBool("allow_chords"); } void NoteStepper::SaveLayout(ofxJSONElement& moduleInfo) { } ```
/content/code_sandbox/Source/NoteStepper.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,058
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== ModWheelToCV.cpp Created: 28 Nov 2017 10:44:26pm Author: Ryan Challinor ============================================================================== */ #include "ModWheelToCV.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "ModulationChain.h" ModWheelToCV::ModWheelToCV() { } ModWheelToCV::~ModWheelToCV() { } void ModWheelToCV::CreateUIControls() { IDrawableModule::CreateUIControls(); mTargetCable = new PatchCableSource(this, kConnectionType_Modulator); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); mMinSlider = new FloatSlider(this, "min", 3, 2, 100, 15, &mDummyMin, 0, 1); mMaxSlider = new FloatSlider(this, "max", mMinSlider, kAnchor_Below, 100, 15, &mDummyMax, 0, 1); } void ModWheelToCV::DrawModule() { if (Minimized() || IsVisible() == false) return; mMinSlider->Draw(); mMaxSlider->Draw(); } void ModWheelToCV::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { OnModulatorRepatch(); } void ModWheelToCV::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled && velocity > 0) { mModWheel = modulation.modWheel; } } float ModWheelToCV::Value(int samplesIn) { float modWheel = mModWheel ? mModWheel->GetValue(samplesIn) : ModulationParameters::kDefaultModWheel; return ofMap(modWheel, 0, 1, GetMin(), GetMax(), K(clamped)); } void ModWheelToCV::SaveLayout(ofxJSONElement& moduleInfo) { } void ModWheelToCV::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void ModWheelToCV::SetUpFromSaveData() { } ```
/content/code_sandbox/Source/ModWheelToCV.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
586
```objective-c #pragma once #include "OpenFrameworksPort.h" #include "psmove/psmove.h" struct _PSMove; #define MAX_NUM_PS_MOVES 7 class PSMoveListener { public: virtual ~PSMoveListener() {} virtual void OnPSMoveButton(int id, std::string button, int val) = 0; }; class PSMoveMgr { public: PSMoveMgr() {} void Setup(); void Update(); void Exit(); void AddMoves(); void SetVibration(int id, float amount); void SetColor(int id, float r, float g, float b); void GetGyros(int id, ofVec3f& gyros); void GetAccel(int id, ofVec3f& accel); bool IsButtonDown(int id, PSMove_Button button); float GetBattery(int id); void SetListener(PSMoveListener* listener) { mListener = listener; } private: _PSMove* SetUpMove(int id); void SendButtonMessage(int id, std::string button, int val); _PSMove* mMove[MAX_NUM_PS_MOVES]{}; int mButtons[MAX_NUM_PS_MOVES]{}; PSMoveListener* mListener{ nullptr }; }; ```
/content/code_sandbox/Source/PSMoveMgr.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
268
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== INoteReceiver.cpp Created: 17 May 2020 10:59:27pm Author: Ryan Challinor ============================================================================== */ #include "INoteReceiver.h" #include "Profiler.h" NoteInputBuffer::NoteInputBuffer(INoteReceiver* receiver) : mReceiver(receiver) { for (int i = 0; i < kBufferSize; ++i) mBuffer[i].time = -1; } void NoteInputBuffer::Process(double time) { PROFILER(NoteInputBuffer); //process note offs first for (int i = 0; i < kBufferSize; ++i) { if (mBuffer[i].time != -1 && mBuffer[i].velocity == 0 && IsTimeWithinFrame(mBuffer[i].time)) { NoteInputElement& element = mBuffer[i]; mReceiver->PlayNote(element.time, element.pitch, element.velocity, element.voiceIdx, element.modulation); mBuffer[i].time = -1; } } //now process note ons for (int i = 0; i < kBufferSize; ++i) { if (mBuffer[i].time != -1 && mBuffer[i].velocity != 0 && IsTimeWithinFrame(mBuffer[i].time)) { NoteInputElement& element = mBuffer[i]; mReceiver->PlayNote(element.time, element.pitch, element.velocity, element.voiceIdx, element.modulation); mBuffer[i].time = -1; } } } void NoteInputBuffer::QueueNote(double time, int pitch, float velocity, int voiceIdx, ModulationParameters modulation) { for (int i = 0; i < kBufferSize; ++i) { if (mBuffer[i].time == -1) { mBuffer[i].time = time; NoteInputElement& element = mBuffer[i]; element.pitch = pitch; element.velocity = velocity; element.voiceIdx = voiceIdx; element.modulation = modulation; break; } } } //static bool NoteInputBuffer::IsTimeWithinFrame(double time) { return time <= NextBufferTime(false); } ```
/content/code_sandbox/Source/INoteReceiver.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
565
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // BiquadFilterEffect.h // modularSynth // // Created by Ryan Challinor on 11/29/12. // // #pragma once #include <iostream> #include "IAudioEffect.h" #include "DropdownList.h" #include "Slider.h" #include "BiquadFilter.h" #include "RadioButton.h" class BiquadFilterEffect : public IAudioEffect, public IDropdownListener, public IFloatSliderListener, public IRadioButtonListener { public: BiquadFilterEffect(); ~BiquadFilterEffect(); static IAudioEffect* Create() { return new BiquadFilterEffect(); } void CreateUIControls() override; void Init() override; void SetFilterType(FilterType type) { mBiquad[0].SetFilterType(type); } void SetFilterParams(float f, float q) { mBiquad[0].SetFilterParams(f, q); } void Clear(); //IAudioEffect void ProcessAudio(double time, ChannelBuffer* buffer) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } float GetEffectAmount() override; std::string GetType() override { return "biquad"; } bool MouseMoved(float x, float y) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void RadioButtonUpdated(RadioButton* list, int oldVal, double time) override; void LoadLayout(const ofxJSONElement& info) override; void SetUpFromSaveData() override; void SaveLayout(ofxJSONElement& info) override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void GetModuleDimensions(float& width, float& height) override; void DrawModule() override; void ResetFilter(); RadioButton* mTypeSelector{ nullptr }; FloatSlider* mFSlider{ nullptr }; FloatSlider* mQSlider{ nullptr }; FloatSlider* mGSlider{ nullptr }; bool mMouseControl{ false }; BiquadFilter mBiquad[ChannelBuffer::kMaxNumChannels]; ChannelBuffer mDryBuffer; bool mCoefficientsHaveChanged{ true }; }; ```
/content/code_sandbox/Source/BiquadFilterEffect.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
608
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // NoteChainNode.h // Bespoke // // Created by Ryan Challinor on 5/1/16. // // #pragma once #include "IDrawableModule.h" #include "INoteSource.h" #include "ClickButton.h" #include "TextEntry.h" #include "Slider.h" #include "Transport.h" #include "DropdownList.h" #include "IPulseReceiver.h" class NoteChainNode : public IDrawableModule, public INoteSource, public IButtonListener, public ITextEntryListener, public IFloatSliderListener, public IAudioPoller, public IDropdownListener, public ITimeListener, public IPulseSource, public IPulseReceiver { public: NoteChainNode(); virtual ~NoteChainNode(); static IDrawableModule* Create() { return new NoteChainNode(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return true; } void CreateUIControls() override; void Init() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //IPulseReceiver void OnPulse(double time, float velocity, int flags) override; void OnTimeEvent(double time) override; void OnTransportAdvanced(float amount) override; void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void ButtonClicked(ClickButton* button, double time) override; void TextEntryComplete(TextEntry* entry) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} void DropdownUpdated(DropdownList* list, int oldVal, double time) override {} void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override { w = 110; h = 76; } void TriggerNote(double time); ClickButton* mTriggerButton{ nullptr }; TextEntry* mPitchEntry{ nullptr }; FloatSlider* mVelocitySlider{ nullptr }; FloatSlider* mDurationSlider{ nullptr }; DropdownList* mNextSelector{ nullptr }; int mPitch{ 48 }; float mVelocity{ 1 }; float mDuration{ .25 }; float mDurationMs{ 50 }; NoteInterval mNextInterval{ NoteInterval::kInterval_8n }; float mNext{ 0 }; double mStartTime{ 0 }; bool mNoteOn{ false }; bool mWaitingToTrigger{ false }; bool mQueueTrigger{ false }; PatchCableSource* mNextNodeCable{ nullptr }; }; ```
/content/code_sandbox/Source/NoteChainNode.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
725
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // Snapshots.h // modularSynth // // Created by Ryan Challinor on 7/29/13. // // #pragma once #include <iostream> #include "IDrawableModule.h" #include "UIGrid.h" #include "ClickButton.h" #include "Checkbox.h" #include "FloatSliderLFOControl.h" #include "Slider.h" #include "Ramp.h" #include "INoteReceiver.h" #include "DropdownList.h" #include "TextEntry.h" #include "Push2Control.h" class Snapshots : public IDrawableModule, public IButtonListener, public IAudioPoller, public IFloatSliderListener, public IDropdownListener, public INoteReceiver, public ITextEntryListener, public IPush2GridController { public: Snapshots(); virtual ~Snapshots(); static IDrawableModule* Create() { return new Snapshots(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; //IDrawableModule void Init() override; void Poll() override; bool IsResizable() const override { return true; } void Resize(float w, float h) override; bool HasSnapshot(int index) const; int GetCurrentSnapshot() const { return mCurrentSnapshot; } bool IsTargetingModule(IDrawableModule* module) const; void AddSnapshotTarget(IDrawableModule* target); void SetSnapshot(int idx, double time); void StoreSnapshot(int idx, bool setAsCurrent); void DeleteSnapshot(int idx); void OnTransportAdvanced(float amount) override; //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; void SendCC(int control, int value, int voiceIdx = -1) override {} //IPush2GridController bool OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue) override; void UpdatePush2Leds(Push2Control* push2) override; void ButtonClicked(ClickButton* button, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override {} void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void TextEntryComplete(TextEntry* entry) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SaveLayout(ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; bool LoadOldControl(FileStreamIn& in, std::string& oldName) override; int GetModuleSaveStateRev() const override { return 3; } std::vector<IUIControl*> ControlsToNotSetDuringLoadState() const override; void UpdateOldControlName(std::string& oldName) override; static std::vector<IUIControl*> sSnapshotHighlightControls; //IPatchable void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; bool IsEnabled() const override { return true; } private: void UpdateGridValues(); void SetGridSize(float w, float h); bool IsConnectedToPath(std::string path) const; void RandomizeTargets(); void RandomizeControl(IUIControl* control); //IDrawableModule void DrawModule() override; void DrawModuleUnclipped() override; void GetModuleDimensions(float& w, float& h) override; void OnClicked(float x, float y, bool right) override; bool MouseMoved(float x, float y) override; struct Snapshot { Snapshot() {} Snapshot(std::string path, float val) : mControlPath(path) , mValue(val) {} Snapshot(IUIControl* control, Snapshots* snapshots); bool operator==(const Snapshot& other) const { return mControlPath == other.mControlPath && mValue == other.mValue && mHasLFO == other.mHasLFO; } std::string mControlPath; float mValue{ 0 }; bool mHasLFO{ false }; LFOSettings mLFOSettings; int mGridCols{ 0 }; int mGridRows{ 0 }; std::vector<float> mGridContents{}; std::string mString; }; struct SnapshotCollection { std::list<Snapshot> mSnapshots; std::string mLabel; }; struct ControlRamp { IUIControl* mUIControl{ nullptr }; Ramp mRamp; }; UIGrid* mGrid{ nullptr }; std::vector<SnapshotCollection> mSnapshotCollection; ClickButton* mRandomizeButton{ nullptr }; ClickButton* mAddButton{ nullptr }; int mDrawSetSnapshotCountdown{ 0 }; std::vector<IDrawableModule*> mSnapshotModules{}; std::vector<IUIControl*> mSnapshotControls{}; bool mBlending{ false }; float mBlendTime{ 0 }; FloatSlider* mBlendTimeSlider{ nullptr }; float mBlendProgress{ 0 }; std::vector<ControlRamp> mBlendRamps; ofMutex mRampMutex; int mCurrentSnapshot{ 0 }; DropdownList* mCurrentSnapshotSelector{ nullptr }; PatchCableSource* mModuleCable{ nullptr }; PatchCableSource* mUIControlCable{ nullptr }; int mQueuedSnapshotIndex{ -1 }; bool mAllowSetOnAudioThread{ false }; TextEntry* mSnapshotLabelEntry{ nullptr }; std::string mSnapshotLabel; int mLoadRev{ -1 }; ClickButton* mClearButton{ nullptr }; bool mStoreMode{ false }; Checkbox* mStoreCheckbox{ nullptr }; bool mDeleteMode{ false }; Checkbox* mDeleteCheckbox{ nullptr }; bool mAutoStoreOnSwitch{ false }; Checkbox* mAutoStoreOnSwitchCheckbox{ nullptr }; }; ```
/content/code_sandbox/Source/Snapshots.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,469
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // VSTWindow.cpp // Bespoke // // Created by Ryan Challinor on 1/23/16. // // #include "VSTWindow.h" #include "VSTPlugin.h" #include "ModularSynth.h" #include "UserPrefs.h" #include "juce_gui_extra/juce_gui_extra.h" VSTWindow::VSTWindow(VSTPlugin* vst, Component* const pluginEditor, WindowFormatType t) : DocumentWindow(pluginEditor->getName(), juce::Colours::lightblue, DocumentWindow::minimiseButton | DocumentWindow::closeButton) , mType(t) , mOwner(vst) { setSize(400, 300); setResizable(true, true); setContentOwned(pluginEditor, true); if (const auto* dpy = juce::Desktop::getInstance().getDisplays().getDisplayForRect(TheSynth->GetMainComponent()->getScreenBounds())) { const auto& mainMon = dpy->userArea; setTopLeftPosition(mainMon.getX() + mainMon.getWidth() / 4, mainMon.getY() + mainMon.getHeight() / 4); } setVisible(true); #if BESPOKE_LINUX setUsingNativeTitleBar(true); #endif #ifdef JUCE_MAC if (pluginEditor->getNumChildComponents() > 0) mNSViewComponent = dynamic_cast<juce::NSViewComponent*>(pluginEditor->getChildComponent(0)); #endif } //static VSTWindow* VSTWindow::CreateVSTWindow(VSTPlugin* vst, WindowFormatType type) { juce::AudioProcessorEditor* ui = nullptr; if (type == Normal) { ui = vst->GetAudioProcessor()->createEditorIfNeeded(); if (ui == nullptr) type = Generic; } if (ui == nullptr) { if (type == Generic || type == Parameters) ui = new juce::GenericAudioProcessorEditor(*vst->GetAudioProcessor()); else if (type == Programs) ui = new ProgramAudioProcessorEditor(vst->GetAudioProcessor()); } if (ui != nullptr) { if (juce::AudioPluginInstance* const plugin = dynamic_cast<juce::AudioPluginInstance*>(vst->GetAudioProcessor())) ui->setName(plugin->getName()); return new VSTWindow(vst, ui, type); } return nullptr; } VSTWindow::~VSTWindow() { clearContentComponent(); } void VSTWindow::ShowWindow() { #if !BESPOKE_LINUX setAlwaysOnTop(UserPrefs.vst_always_on_top.Get()); #endif toFront(true); } void VSTWindow::moved() { // owner->properties.set (getLastXProp (mType), getX()); // owner->properties.set (getLastYProp (mType), getY()); } void VSTWindow::closeButtonPressed() { mOwner->OnVSTWindowClosed(); delete this; } ```
/content/code_sandbox/Source/VSTWindow.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
741
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // PSMoveController.h // modularSynth // // Created by Ryan Challinor on 1/18/13. // // #pragma once #include <iostream> #include "IDrawableModule.h" #include "PSMoveMgr.h" #include "Checkbox.h" #include "ClickButton.h" #include "Ramp.h" #include "Transport.h" #include "Slider.h" class IUIControl; class PSMoveController : public IDrawableModule, public IButtonListener, public ITimeListener, public IFloatSliderListener { public: PSMoveController(); ~PSMoveController(); static IDrawableModule* Create() { return new PSMoveController(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Init() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } void Poll() override; void Exit() override; void SetPitchControl(IUIControl* control) { mPitchUIControl = control; } void SetYawControl(IUIControl* control) { mYawUIControl = control; } void SetRollControl(IUIControl* control) { mRollUIControl = control; } void SetEnergyControl(IUIControl* control) { mEnergyUIControl = control; } void CheckboxUpdated(Checkbox* checkbox, double time) override; //IButtonListener void ButtonClicked(ClickButton* button, double time) override; //ITimeListener void OnTimeEvent(double time) override; //IFloatSliderLIstener void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = 152; height = 140; } PSMoveMgr mMoveMgr; Ramp mVibration; bool mVibronomeOn{ false }; Checkbox* mVibronomeCheckbox{ nullptr }; ClickButton* mConnectButton{ nullptr }; float mMetronomeLagOffset{ 50 }; FloatSlider* mOffsetSlider{ nullptr }; float mRoll{ .5 }; float mPitch{ .5 }; float mYaw{ 0 }; float mEnergy{ 0 }; FloatSlider* mPitchSlider{ nullptr }; FloatSlider* mYawSlider{ nullptr }; FloatSlider* mRollSlider{ nullptr }; FloatSlider* mEnergySlider{ nullptr }; ClickButton* mBindPitch{ nullptr }; ClickButton* mBindYaw{ nullptr }; ClickButton* mBindRoll{ nullptr }; ClickButton* mBindEnergy{ nullptr }; IUIControl* mPitchUIControl{ nullptr }; IUIControl* mYawUIControl{ nullptr }; IUIControl* mRollUIControl{ nullptr }; IUIControl* mEnergyUIControl{ nullptr }; bool mPSButtonDown{ false }; TransportListenerInfo* mTransportListenerInfo{ nullptr }; }; ```
/content/code_sandbox/Source/PSMoveController.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
819
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== VelocityToCV.cpp Created: 28 Nov 2017 9:44:00pm Author: Ryan Challinor ============================================================================== */ #include "VelocityToCV.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "ModulationChain.h" VelocityToCV::VelocityToCV() { } VelocityToCV::~VelocityToCV() { } void VelocityToCV::CreateUIControls() { IDrawableModule::CreateUIControls(); mTargetCable = new PatchCableSource(this, kConnectionType_Modulator); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); mMinSlider = new FloatSlider(this, "min", 3, 2, 100, 15, &mDummyMin, 0, 1); mMaxSlider = new FloatSlider(this, "max", mMinSlider, kAnchor_Below, 100, 15, &mDummyMax, 0, 1); mPassZeroCheckbox = new Checkbox(this, "0 at note off", mMaxSlider, kAnchor_Below, &mPassZero); } void VelocityToCV::DrawModule() { if (Minimized() || IsVisible() == false) return; mMinSlider->Draw(); mMaxSlider->Draw(); mPassZeroCheckbox->Draw(); } void VelocityToCV::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { OnModulatorRepatch(); } void VelocityToCV::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled && (mPassZero || velocity > 0)) { mVelocity = velocity; } } float VelocityToCV::Value(int samplesIn) { return ofMap(mVelocity, 0, 127, GetMin(), GetMax(), K(clamped)); } void VelocityToCV::SaveLayout(ofxJSONElement& moduleInfo) { } void VelocityToCV::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void VelocityToCV::SetUpFromSaveData() { } ```
/content/code_sandbox/Source/VelocityToCV.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
585
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // IUIControl.h // modularSynth // // Created by Ryan Challinor on 1/13/13. // // #pragma once #include "IClickable.h" #include "SynthGlobals.h" class FileStreamIn; class FileStreamOut; class PatchCableSource; #define HIDDEN_UICONTROL 9999 enum AnchorDirection { kAnchor_Below, kAnchor_Right, kAnchor_Right_Padded }; class IUIControl : public IClickable { public: IUIControl() {} virtual void Delete() { delete this; } void AddRemoteController() { ++mRemoteControlCount; } void RemoveRemoteController() { --mRemoteControlCount; } virtual void SetFromMidiCC(float slider, double time, bool setViaModulator) = 0; virtual float GetValueForMidiCC(float slider) const { return 0; } virtual void SetValue(float value, double time, bool forceUpdate = false) = 0; virtual void SetValueDirect(float value, double time) { SetValue(value, time); } //override if you need special control here virtual float GetValue() const { return 0; } virtual float GetMidiValue() const { return 0; } virtual int GetNumValues() { return 0; } //the number of distinct values that you can have for this control, zero indicates infinite (like a float slider) virtual std::string GetDisplayValue(float val) const { return "unimplemented"; } virtual void Init() {} virtual void Poll() {} virtual void KeyPressed(int key, bool isRepeat) {} void StartBeacon() override; bool IsPreset(); virtual void GetRange(float& min, float& max) { min = 0; max = 1; } virtual bool IsBitmask() { return false; } bool TestHover(int x, int y); void CheckHover(int x, int y); void DrawHover(float x, float y, float w, float h); void DrawPatchCableHover(); virtual bool CanBeTargetedBy(PatchCableSource* source) const; virtual bool InvertScrollDirection() { return false; } virtual void Double() {} virtual void Halve() {} virtual void ResetToOriginal() {} virtual void Increment(float amount) {} void SetCableTargetable(bool targetable) { mCableTargetable = targetable; } bool GetCableTargetable() const { return mCableTargetable; } void SetNoHover(bool noHover) { mNoHover = noHover; } virtual bool GetNoHover() const { return mNoHover; } virtual bool AttemptTextInput() { return false; } void PositionTo(IUIControl* anchor, AnchorDirection direction); void GetColors(ofColor& color, ofColor& textColor); bool GetShouldSaveState() const { return mShouldSaveState; } void SetShouldSaveState(bool save) { mShouldSaveState = save; } void RemoveFromOwner(); virtual bool IsSliderControl() { return true; } virtual bool IsButtonControl() { return false; } virtual bool IsMouseDown() const { return false; } virtual bool IsTextEntry() const { return false; } virtual bool ModulatorUsesLiteralValue() const { return false; } virtual float GetModulationRangeMin() const { return 0; } virtual float GetModulationRangeMax() const { return 1; } virtual bool ShouldSerializeForSnapshot() const { return false; } static void SetNewManualHoverViaTab(int direction); static void SetNewManualHoverViaArrow(ofVec2f direction); static bool WasLastHoverSetManually() { return sLastUIHoverWasSetManually; } static void DestroyCablesTargetingControls(std::vector<IUIControl*> controls); virtual void SaveState(FileStreamOut& out) = 0; virtual void LoadState(FileStreamIn& in, bool shouldSetValue = true) = 0; protected: virtual ~IUIControl(); int mRemoteControlCount{ 0 }; bool mCableTargetable{ true }; bool mNoHover{ false }; bool mShouldSaveState{ true }; static IUIControl* sLastHoveredUIControl; static bool sLastUIHoverWasSetManually; }; ```
/content/code_sandbox/Source/IUIControl.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,041
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // TremoloEffect.h // modularSynth // // Created by Ryan Challinor on 12/27/12. // // #pragma once #include <iostream> #include "IAudioEffect.h" #include "Slider.h" #include "Checkbox.h" #include "LFO.h" #include "DropdownList.h" class TremoloEffect : public IAudioEffect, public IDropdownListener, public IFloatSliderListener { public: TremoloEffect(); static IAudioEffect* Create() { return new TremoloEffect(); } void CreateUIControls() override; //IAudioEffect void ProcessAudio(double time, ChannelBuffer* buffer) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } float GetEffectAmount() override; std::string GetType() override { return "tremolo"; } //IDropdownListener void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; //IFloatSliderListener void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } float mAmount{ 0 }; FloatSlider* mAmountSlider{ nullptr }; float mOffset{ 0 }; FloatSlider* mOffsetSlider{ nullptr }; LFO mLFO; NoteInterval mInterval{ NoteInterval::kInterval_16n }; DropdownList* mIntervalSelector{ nullptr }; OscillatorType mOscType{ OscillatorType::kOsc_Square }; DropdownList* mOscSelector{ nullptr }; FloatSlider* mDutySlider{ nullptr }; float mDuty{ .5 }; static const int kAntiPopWindowSize = 300; float mWindow[kAntiPopWindowSize]{}; int mWindowPos{ 0 }; float mWidth{ 200 }; float mHeight{ 20 }; }; ```
/content/code_sandbox/Source/TremoloEffect.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
565
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // INoteSource.cpp // modularSynth // // Created by Ryan Challinor on 12/14/12. // // #include "NoteOutputQueue.h" #include "INoteSource.h" #include "ModularSynth.h" void NoteOutputQueue::QueuePlayNote(NoteOutput* target, double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { PendingNoteOutput output; output.target = target; output.time = time; output.pitch = pitch; output.velocity = velocity; output.voiceIdx = voiceIdx; output.modulation = modulation; mQueue.enqueue(output); } void NoteOutputQueue::QueueFlush(NoteOutput* target, double time) { PendingNoteOutput output; output.target = target; output.isFlush = true; output.time = time; mQueue.enqueue(output); } void NoteOutputQueue::Process() { assert(IsAudioThread()); PendingNoteOutput output; while (true) { bool hasData = mQueue.try_dequeue(output); if (!hasData) break; if (output.isFlush) { output.target->Flush(output.time); } else { //ofLog() << "playing queued note " << output.time << " " << output.pitch << " " << output.velocity << " " << gTime; output.target->PlayNoteInternal(output.time, output.pitch, output.velocity, output.voiceIdx, output.modulation, false); } } } ```
/content/code_sandbox/Source/NoteOutputQueue.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
417
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // GateEffect.cpp // modularSynth // // Created by Ryan Challinor on 4/19/13. // // #include "GateEffect.h" #include "SynthGlobals.h" #include "Profiler.h" GateEffect::GateEffect() { } void GateEffect::CreateUIControls() { IDrawableModule::CreateUIControls(); mThresholdSlider = new FloatSlider(this, "threshold", 5, 2, 110, 15, &mThreshold, 0, 1); mAttackSlider = new FloatSlider(this, "attack", 5, 18, 110, 15, &mAttackTime, .1f, 500); mReleaseSlider = new FloatSlider(this, "release", 5, 34, 110, 15, &mReleaseTime, .1f, 500); mThresholdSlider->SetMode(FloatSlider::kSquare); } void GateEffect::ProcessAudio(double time, ChannelBuffer* buffer) { PROFILER(GateEffect); if (!mEnabled) return; float bufferSize = buffer->BufferSize(); ComputeSliders(0); for (int i = 0; i < bufferSize; ++i) { const float decayTime = .01f; float scalar = powf(0.5f, 1.0f / (decayTime * gSampleRate)); float input = 0; for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) input = MAX(input, fabsf(buffer->GetChannel(ch)[i])); if (input >= mPeak) { /* When we hit a peak, ride the peak to the top. */ mPeak = input; } else { /* Exponential decay of output when signal is low. */ mPeak = mPeak * scalar; if (mPeak < FLT_EPSILON) mPeak = 0.0; } if (mPeak >= mThreshold && mEnvelope < 1) mEnvelope = MIN(1, mEnvelope + gInvSampleRateMs / mAttackTime); if (mPeak < mThreshold && mEnvelope > 0) mEnvelope = MAX(0, mEnvelope - gInvSampleRateMs / mReleaseTime); for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) buffer->GetChannel(ch)[i] *= mEnvelope; time += gInvSampleRateMs; } } void GateEffect::DrawModule() { mThresholdSlider->Draw(); mAttackSlider->Draw(); mReleaseSlider->Draw(); ofPushStyle(); ofFill(); ofSetColor(0, 255, 0, gModuleDrawAlpha * .4f); ofRect(5, 2, 110 * sqrtf(mPeak), 7); ofSetColor(255, 0, 0, gModuleDrawAlpha * .4f); ofRect(5, 9, 110 * mEnvelope, 7); ofPopStyle(); } void GateEffect::CheckboxUpdated(Checkbox* checkbox, double time) { } void GateEffect::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void GateEffect::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } ```
/content/code_sandbox/Source/GateEffect.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
819
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // Neighborhooder.cpp // modularSynth // // Created by Ryan Challinor on 3/10/13. // // #include "Neighborhooder.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" Neighborhooder::Neighborhooder() { } void Neighborhooder::CreateUIControls() { IDrawableModule::CreateUIControls(); mMinSlider = new IntSlider(this, "min", 4, 3, 84, 15, &mMinPitch, 0, 127); mRangeSlider = new IntSlider(this, "range", mMinSlider, kAnchor_Below, 116, 15, &mPitchRange, 12, 36); } void Neighborhooder::DrawModule() { if (Minimized() || IsVisible() == false) return; mMinSlider->Draw(); mRangeSlider->Draw(); DrawTextNormal(NoteName(mMinPitch) + ofToString(mMinPitch / 12 - 2), 91, 15); } void Neighborhooder::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) mNoteOutput.Flush(time); } void Neighborhooder::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mMinSlider || slider == mRangeSlider) mNoteOutput.Flush(time); } void Neighborhooder::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (!mEnabled) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); return; } while (pitch >= mMinPitch + mPitchRange) pitch -= TheScale->GetPitchesPerOctave(); while (pitch < mMinPitch) pitch += TheScale->GetPitchesPerOctave(); PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void Neighborhooder::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void Neighborhooder::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/Neighborhooder.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
579
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // DrumPlayer.h // modularSynth // // Created by Ryan Challinor on 11/25/12. // // #pragma once #include <iostream> #include "IAudioSource.h" #include "Sample.h" #include "INoteReceiver.h" #include "IDrawableModule.h" #include "Slider.h" #include "DropdownList.h" #include "Checkbox.h" #include "ClickButton.h" #include "Transport.h" #include "MidiDevice.h" #include "TextEntry.h" #include "ADSR.h" #include "BiquadFilter.h" #include "ADSRDisplay.h" #include "PatchCableSource.h" #include "RollingBuffer.h" #include "GridController.h" #include "Push2Control.h" #define NUM_DRUM_HITS 16 class SamplePlayer; class DrumPlayer : public IAudioSource, public INoteReceiver, public IDrawableModule, public IFloatSliderListener, public IDropdownListener, public IButtonListener, public IIntSliderListener, public ITextEntryListener, public IGridControllerListener, public ITimeListener, public IPush2GridController { public: DrumPlayer(); ~DrumPlayer(); static IDrawableModule* Create() { return new DrumPlayer(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Init() override; void Poll() override; static void SetUpHitDirectories(); void ImportSampleCuePoint(SamplePlayer* player, int sourceCueIndex, int destHitIndex); //IAudioSource void Process(double time) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } int GetNumTargets() override { return 1 + (int)mIndividualOutputs.size(); } //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; void SendCC(int control, int value, int voiceIdx = -1) override {} //IDrawableModule void FilesDropped(std::vector<std::string> files, int x, int y) override; void SampleDropped(int x, int y, Sample* sample) override; bool CanDropSample() const override { return true; } //IGridControllerListener void OnControllerPageSelected() override; void OnGridButton(int x, int y, float velocity, IGridController* grid) override; //ITimeListener void OnTimeEvent(double time) override; //IPush2GridController bool OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue) override; void UpdatePush2Leds(Push2Control* push2) override; bool HasPush2OverrideControls() const override { return mPush2SelectedHitIdx != -1; } void GetPush2OverrideControls(std::vector<IUIControl*>& controls) const override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void ButtonClicked(ClickButton* button, double time) override; void TextEntryComplete(TextEntry* entry) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, int rev) override; int GetModuleSaveStateRev() const override { return 1; } bool IsEnabled() const override { return mEnabled; } private: struct StoredDrumKit { std::string mName; std::string mSampleFiles[NUM_DRUM_HITS]; int mLinkIds[NUM_DRUM_HITS]{}; float mVols[NUM_DRUM_HITS]{}; float mSpeeds[NUM_DRUM_HITS]{}; float mPans[NUM_DRUM_HITS]{}; }; void LoadKit(int kit); int GetAssociatedSampleIndex(int x, int y); void ReadKits(); void SaveKits(); void CreateKit(); void ShuffleKit(); void UpdateVisibleControls(); int GetIndividualOutputIndex(int hitIndex); void UpdateLights(); void SetUpNewDrumPlayer(); void SetHitSample(int sampleIndex, Sample* sample); //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; void OnClicked(float x, float y, bool right) override; std::vector<IUIControl*> ControlsToNotSetDuringLoadState() const override; ChannelBuffer mOutputBuffer; float mSpeed{ 1 }; float mSpeedRandomization{ 0 }; float mVolume{ 1 }; int mLoadedKit{ 0 }; FloatSlider* mVolSlider{ nullptr }; FloatSlider* mSpeedSlider{ nullptr }; FloatSlider* mSpeedRandomizationSlider{ nullptr }; DropdownList* mKitSelector{ nullptr }; bool mEditMode{ false }; Checkbox* mEditCheckbox{ nullptr }; std::vector<StoredDrumKit> mKits; ClickButton* mSaveButton{ nullptr }; ClickButton* mNewKitButton{ nullptr }; int mAuditionSampleIdx{ 0 }; float mAuditionInc{ 0 }; FloatSlider* mAuditionSlider{ nullptr }; std::string mAuditionDir; char mNewKitName[MAX_TEXTENTRY_LENGTH]{}; TextEntry* mNewKitNameEntry{ nullptr }; ofMutex mLoadSamplesAudioMutex; ofMutex mLoadSamplesDrawMutex; bool mLoadingSamples{ false }; ClickButton* mShuffleButton{ nullptr }; int mSelectedHitIdx{ 0 }; bool mMonoOutput{ false }; Checkbox* mMonoCheckbox{ nullptr }; bool mSingleVoice{ false }; Checkbox* mSingleVoiceCheckbox{ nullptr }; GridControlTarget* mGridControlTarget{ nullptr }; NoteInputBuffer mNoteInputBuffer{ nullptr }; bool mNeedSetup{ true }; bool mNoteRepeat{ false }; Checkbox* mNoteRepeatCheckbox{ nullptr }; NoteInterval mQuantizeInterval{ NoteInterval::kInterval_None }; DropdownList* mQuantizeIntervalSelector{ nullptr }; bool mFullVelocity{ false }; Checkbox* mFullVelocityCheckbox{ nullptr }; int mPush2SelectedHitIdx{ -1 }; void LoadSampleLock(); void LoadSampleUnlock(); struct IndividualOutput { IndividualOutput(DrumPlayer* owner, int hitIndex) : mDrumPlayer(owner) , mHitIndex(hitIndex) { mVizBuffer = new RollingBuffer(VIZ_BUFFER_SECONDS * gSampleRate); mPatchCableSource = new PatchCableSource(owner, kConnectionType_Audio); mPatchCableSource->SetOverrideVizBuffer(mVizBuffer); mPatchCableSource->SetManualSide(PatchCableSource::Side::kRight); owner->AddPatchCableSource(mPatchCableSource); } ~IndividualOutput() { delete mVizBuffer; } void UpdatePosition(int outputIndex) { float w, h; mDrumPlayer->GetDimensions(w, h); mPatchCableSource->SetManualPosition(w, 7 + outputIndex * 12); } DrumPlayer* mDrumPlayer{ nullptr }; int mHitIndex{ 0 }; RollingBuffer* mVizBuffer{ nullptr }; PatchCableSource* mPatchCableSource{ nullptr }; }; std::vector<IndividualOutput*> mIndividualOutputs; struct DrumHit { struct Playhead { double mStartTime{ -1 }; double mCutOffTime{ -1 }; double mOffset{ 0 }; double mEnvelopeTime{ 0 }; double mEnvelopeScale{ 1 }; float mSpeedTweak{ 1 }; }; DrumHit() { mEnvelope.GetHasSustainStage() = false; mEnvelope.Start(0, 1); } void CreateUIControls(DrumPlayer* owner, int index); bool Process(double time, float speed, float vol, ChannelBuffer* out, int bufferSize); void SetUIControlsShowing(bool showing); void DrawUIControls(); void UpdateHitDirectoryDropdown(); void LoadRandomSample(); void LoadNextSample(int direction); void LoadSample(std::string path); void GrabSample(); void StartPlayhead(double time, float startOffsetPercent, float velocity); void StopLinked(double time); float GetPlayProgress(double time); Sample mSample; int mLinkId{ -1 }; float mVol{ 1 }; float mSpeed{ 1 }; float mVelocity{ 1 }; float mPanInput{ 0 }; float mStartOffset{ 0 }; ModulationChain* mPitchBend{ nullptr }; bool mUseEnvelope{ false }; ::ADSR mEnvelope{ 1, 1, 1, 100 }; float mEnvelopeLength{ 200 }; float mPan{ 0 }; int mWiden{ 0 }; bool mHasIndividualOutput{ false }; std::string mHitDirectory; int mButtonHeldVelocity{ 0 }; DrumPlayer* mOwner{ nullptr }; FloatSlider* mVolSlider{ nullptr }; FloatSlider* mSpeedSlider{ nullptr }; ClickButton* mTestButton{ nullptr }; ClickButton* mRandomButton{ nullptr }; ClickButton* mNextButton{ nullptr }; ClickButton* mPrevButton{ nullptr }; ClickButton* mGrabSampleButton{ nullptr }; Checkbox* mUseEnvelopeCheckbox{ nullptr }; ADSRDisplay* mEnvelopeDisplay{ nullptr }; FloatSlider* mPanSlider{ nullptr }; IntSlider* mWidenSlider{ nullptr }; Checkbox* mIndividualOutputCheckbox{ nullptr }; FloatSlider* mEnvelopeLengthSlider{ nullptr }; IntSlider* mLinkIdSlider{ nullptr }; DropdownList* mHitCategoryDropdown{ nullptr }; FloatSlider* mStartOffsetSlider{ nullptr }; int mHitCategoryIndex{ -1 }; std::string mHitCategory; RollingBuffer mWidenerBuffer{ 2048 }; int mSamplesRemainingToProcess{ 0 }; std::array<Playhead, 2> mPlayheads; int mCurrentPlayheadIndex{ 0 }; }; std::array<DrumHit, NUM_DRUM_HITS> mDrumHits; }; ```
/content/code_sandbox/Source/DrumPlayer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,447
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // BitcrushEffect.cpp // additiveSynth // // Created by Ryan Challinor on 11/21/12. // // #include "BitcrushEffect.h" #include "OpenFrameworksPort.h" #include "SynthGlobals.h" #include "Profiler.h" #include "UIControlMacros.h" BitcrushEffect::BitcrushEffect() { } void BitcrushEffect::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); FLOATSLIDER(mCrushSlider, "crush", &mCrush, 1, 24); FLOATSLIDER_DIGITS(mDownsampleSlider, "downsamp", &mDownsample, 1, 40, 0); ENDUIBLOCK(mWidth, mHeight); } void BitcrushEffect::ProcessAudio(double time, ChannelBuffer* buffer) { PROFILER(BitcrushEffect); if (!mEnabled) return; float bufferSize = buffer->BufferSize(); ComputeSliders(0); float bitDepth = powf(2, 25 - mCrush); float invBitDepth = 1.f / bitDepth; for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) { for (int i = 0; i < bufferSize; ++i) { if (mSampleCounter[ch] < (int)mDownsample - 1) { ++mSampleCounter[ch]; } else { mHeldDownsample[ch] = buffer->GetChannel(ch)[i]; mSampleCounter[ch] = 0; } buffer->GetChannel(ch)[i] = ((int)(mHeldDownsample[ch] * bitDepth)) * invBitDepth; } } } void BitcrushEffect::DrawModule() { if (!mEnabled) return; mDownsampleSlider->Draw(); mCrushSlider->Draw(); } float BitcrushEffect::GetEffectAmount() { if (!mEnabled) return 0; return ofClamp((mCrush - 1) / 24.0f + ((int)mDownsample - 1) / 40.0f, 0, 1); } void BitcrushEffect::CheckboxUpdated(Checkbox* checkbox, double time) { } void BitcrushEffect::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void BitcrushEffect::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } ```
/content/code_sandbox/Source/BitcrushEffect.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
647
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // LaunchpadKeyboard.cpp // modularSynth // // Created by Ryan Challinor on 11/24/12. // // #include "LaunchpadKeyboard.h" #include "SynthGlobals.h" #include "Scale.h" #include "ModularSynth.h" #include "Chorder.h" #include "MidiController.h" #include "FillSaveDropdown.h" #define INVALID_PITCH -999 #define CHORD_BUTTON_OFFSET -100 #define CHORD_ENABLE_BUTTON -998 #define CHORD_LATCH_BUTTON -997 #define KEY_LATCH_BUTTON -996 LaunchpadKeyboard::LaunchpadKeyboard() { for (int i = 0; i < 128; ++i) mCurrentNotes[i] = 0; TheScale->AddListener(this); mHeldChordTones.push_back(0); std::vector<int> chord; //triad chord.push_back(0); chord.push_back(4); chord.push_back(7); mChords.push_back(chord); chord.clear(); //7 chord.push_back(0); chord.push_back(4); chord.push_back(7); chord.push_back(11); mChords.push_back(chord); chord.clear(); //6 chord.push_back(0); chord.push_back(4); chord.push_back(7); chord.push_back(9); mChords.push_back(chord); chord.clear(); //inv chord.push_back(-5); chord.push_back(0); chord.push_back(4); mChords.push_back(chord); chord.clear(); //sus4 chord.push_back(0); chord.push_back(5); chord.push_back(7); mChords.push_back(chord); chord.clear(); //sus2 chord.push_back(0); chord.push_back(2); chord.push_back(7); mChords.push_back(chord); chord.clear(); //9 chord.push_back(0); chord.push_back(2); chord.push_back(4); chord.push_back(7); chord.push_back(11); mChords.push_back(chord); chord.clear(); //11 chord.push_back(0); chord.push_back(2); chord.push_back(4); chord.push_back(5); chord.push_back(7); chord.push_back(11); mChords.push_back(chord); chord.clear(); //africa chord.push_back(-12); chord.push_back(0); chord.push_back(4); chord.push_back(12); chord.push_back(16); chord.push_back(28); mChords.push_back(chord); chord.clear(); } void LaunchpadKeyboard::Init() { IDrawableModule::Init(); TheTransport->AddListener(this, kInterval_8n, OffsetInfo(0, true), false); } void LaunchpadKeyboard::CreateUIControls() { IDrawableModule::CreateUIControls(); mLayoutDropdown = new DropdownList(this, "layout", 6, 22, (int*)(&mLayout)); mOctaveSlider = new IntSlider(this, "octave", 6, 40, 100, 15, &mOctave, 0, 8); mLatchCheckbox = new Checkbox(this, "latch", 6, 59, &mLatch); mArrangementModeDropdown = new DropdownList(this, "arrangement", 6, 4, ((int*)(&mArrangementMode))); mLatchChordsCheckbox = new Checkbox(this, "ch.latch", 55, 59, &mLatchChords); mPreserveChordRootCheckbox = new Checkbox(this, "p.root", 70, 4, &mPreserveChordRoot); mGridControlTarget = new GridControlTarget(this, "grid", 90, 22); mLayoutDropdown->AddLabel("chromatic", kChromatic); mLayoutDropdown->AddLabel("diatonic", kDiatonic); mLayoutDropdown->AddLabel("major thirds", kMajorThirds); mLayoutDropdown->AddLabel("chord indiv", kChordIndividual); mLayoutDropdown->AddLabel("chord", kChord); mLayoutDropdown->AddLabel("guitar", kGuitar); mLayoutDropdown->AddLabel("septatonic", kSeptatonic); mLayoutDropdown->AddLabel("drum", kDrum); mLayoutDropdown->AddLabel("all pads", kAllPads); mArrangementModeDropdown->AddLabel("full", kFull); mArrangementModeDropdown->AddLabel("five", kFive); mArrangementModeDropdown->AddLabel("six", kSix); } LaunchpadKeyboard::~LaunchpadKeyboard() { TheScale->RemoveListener(this); TheTransport->RemoveListener(this); } void LaunchpadKeyboard::OnGridButton(int x, int y, float velocity, IGridController* grid) { bool bOn = velocity > 0; int pitch = GridToPitch(x, y); double time = NextBufferTime(false); if (pitch == INVALID_PITCH) { ReleaseNoteFor(x, y); return; } if (pitch == CHORD_ENABLE_BUTTON) { if (bOn && mChorder) mChorder->SetEnabled(!mChorder->IsEnabled()); return; } if (pitch == CHORD_LATCH_BUTTON) { if (bOn) { mLatchChords = !mLatchChords; UpdateLights(); } return; } if (pitch == KEY_LATCH_BUTTON) { if (bOn) { mLatch = !mLatch; if (!mLatch) mNoteOutput.Flush(NextBufferTime(false)); UpdateLights(); } return; } if (pitch < 0) { HandleChordButton(pitch, bOn); UpdateLights(); return; } if (!mLatch && mLayout != kChord) { //handled below } else if (mLatch) { if (bOn) //only presses matter in latch, not releases { int currentPitch = -1; for (int i = 0; i < 128; ++i) //we should only have one at a time in latch mode { if (mCurrentNotes[i] > 0) currentPitch = i; mCurrentNotes[i] = 0; } mNoteOutput.Flush(NextBufferTime(false)); if (currentPitch == pitch) { bOn = false; //pressed the note again, this is a note-off } else { PressedNoteFor(x, y, (int)127 * velocity); bOn = true; } } else { return; } } if (mLayout == kChord) { if (bOn) { for (int i = 0; i < 128; ++i) mCurrentNotes[i] = 0; PressedNoteFor(x, y, (int)127 * velocity); mNoteOutput.Flush(time); for (int i = 0; i < mChords[x].size(); ++i) PlayKeyboardNote(time, TheScale->MakeDiatonic(pitch + mChords[x][i]), 127 * velocity); } else { int currentPitch = -1; for (int i = 0; i < 128; ++i) { if (mCurrentNotes[i] > 0) currentPitch = i; } if (GridToPitch(x, y) == currentPitch) { for (int i = 0; i < 128; ++i) mCurrentNotes[i] = 0; mNoteOutput.Flush(time); } } } else { if (bOn) { PlayKeyboardNote(time, pitch, 127 * velocity); PressedNoteFor(x, y, (int)127 * velocity); } else { ReleaseNoteFor(x, y); } } if (mDisplayer == nullptr) //we don't have a displayer, handle it ourselves UpdateLights(); } void LaunchpadKeyboard::PressedNoteFor(int x, int y, int velocity) { int pitch = GridToPitch(x, y); if (pitch >= 0 && pitch < 128) mCurrentNotes[pitch] = velocity; } void LaunchpadKeyboard::ReleaseNoteFor(int x, int y) { int pitch = GridToPitch(x, y); if (pitch >= 0 && pitch < 128) { double time = NextBufferTime(false); PlayKeyboardNote(time, pitch, 0); mCurrentNotes[pitch] = 0; } } void LaunchpadKeyboard::PlayKeyboardNote(double time, int pitch, int velocity) { if (mEnabled || velocity == 0) { if (velocity == 0) time += .001f; //TODO(Ryan) gross hack. need to handle the case better of receiving a note-on followed by a note-off for one pitch at the exact same time. right now it causes stuck notes. PlayNoteOutput(time, pitch, velocity, -1); } if (mDrawDebug) AddDebugLine("PlayNote(" + ofToString(time / 1000) + ", " + ofToString(pitch) + ", " + ofToString(velocity) + ")", 40); } void LaunchpadKeyboard::HandleChordButton(int pitch, bool bOn) { int chordTone = pitch - CHORD_BUTTON_OFFSET; if (mPreserveChordRoot && chordTone == 0) //root always pressed return; if (!mLatchChords) { if (bOn) { mHeldChordTones.push_back(chordTone); if (mChorder) mChorder->AddTone(chordTone); } else { mHeldChordTones.remove(chordTone); if (mChorder) mChorder->RemoveTone(chordTone); } } else if (bOn) //latch only pays attention to presses { if (!ListContains(chordTone, mHeldChordTones)) { mHeldChordTones.push_back(chordTone); if (mChorder) mChorder->AddTone(chordTone); } else { mHeldChordTones.remove(chordTone); if (mChorder) mChorder->RemoveTone(chordTone); } } } bool LaunchpadKeyboard::IsChordButtonPressed(int pitch) { int chordTone = pitch - CHORD_BUTTON_OFFSET; if (mPreserveChordRoot && chordTone == 0) //root always pressed return true; return ListContains(chordTone, mHeldChordTones); } void LaunchpadKeyboard::OnTimeEvent(double time) { } bool LaunchpadKeyboard::OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue) { if (type == kMidiMessage_Note && controlIndex >= 36 && controlIndex <= 99) { int gridIndex = controlIndex - 36; int gridX = gridIndex % 8; int gridY = 7 - gridIndex / 8; OnGridButton(gridX, gridY, midiValue / 127, nullptr); return true; } return false; } void LaunchpadKeyboard::UpdatePush2Leds(Push2Control* push2) { for (int x = 0; x < 8; ++x) { for (int y = 0; y < 8; ++y) { GridColor color = GetGridSquareColor(x, y); int pushColor = 0; switch (color) { case kGridColorOff: //off pushColor = 0; break; case kGridColor1Dim: // pushColor = 86; break; case kGridColor1Bright: //pressed pushColor = 32; break; case kGridColor2Dim: pushColor = 114; break; case kGridColor2Bright: //root pushColor = 25; break; case kGridColor3Dim: //not in pentatonic pushColor = 116; break; case kGridColor3Bright: //in pentatonic pushColor = 115; break; } push2->SetLed(kMidiMessage_Note, x + (7 - y) * 8 + 36, pushColor); //push2->SetLed(kMidiMessage_Note, x + (7-y)*8 + 36, x + y*8 + 64); } } } void LaunchpadKeyboard::DisplayNote(int pitch, int velocity) { if (pitch >= 0 && pitch < 128) mCurrentNotes[pitch] = velocity; UpdateLights(); } void LaunchpadKeyboard::DrawModule() { if (mChorder) DrawConnection(mChorder); if (Minimized() || IsVisible() == false) return; mLayoutDropdown->Draw(); mOctaveSlider->Draw(); mLatchCheckbox->Draw(); mLatchChordsCheckbox->Draw(); mArrangementModeDropdown->Draw(); mPreserveChordRootCheckbox->Draw(); mGridControlTarget->Draw(); } void LaunchpadKeyboard::DrawModuleUnclipped() { if (mDrawDebug) { DrawTextNormal(mDebugDisplayText, 0, 90); for (int i = 0; i < 128; ++i) DrawTextNormal(ofToString(i) + " " + ofToString(mCurrentNotes[i]), 180 + (i / 24) * 20, (i % 24) * 9, 6); } } int LaunchpadKeyboard::GridToPitch(int x, int y) { y = 7 - y; if (mArrangementMode == kSix) { if (x < 2) { return GridToPitchChordSection(x, y); } else { x -= 2; } return TheScale->ScaleRoot() + x + 6 * y + TheScale->GetPitchesPerOctave() * mOctave; } if (mLayout == kChromatic) { if (mArrangementMode == kFive) { if (x < 3) { return GridToPitchChordSection(x, y); } else { x -= 3; } } return mRootNote + x + 5 * y + TheScale->GetPitchesPerOctave() * mOctave; } if (mLayout == kMajorThirds) { if (mArrangementMode == kFive) { if (x < 3) { return GridToPitchChordSection(x, y); } else { x -= 3; } } return mRootNote + x + 4 * y + TheScale->GetPitchesPerOctave() * mOctave; } if (mLayout == kGuitar) { return mRootNote + x + 5 * y + TheScale->GetPitchesPerOctave() * mOctave + (y >= 4 ? -1 : 0); } else if (mLayout == kDiatonic) { if (mArrangementMode == kFive) { if (x < 3) { return GridToPitchChordSection(x, y); } else if (x == 3 || x == 7) { return INVALID_PITCH; } else { x -= 4; } } return TheScale->GetPitchFromTone(x + 3 * y) + TheScale->GetPitchesPerOctave() * (mRootNote / TheScale->GetPitchesPerOctave()) + TheScale->GetPitchesPerOctave() * mOctave; } else if (mLayout == kChordIndividual) { int note = x % mChords[mCurrentChord].size(); int oct = x / mChords[mCurrentChord].size(); return TheScale->MakeDiatonic(TheScale->GetPitchFromTone(y) + mChords[mCurrentChord][note]) + TheScale->GetPitchesPerOctave() * (mOctave + oct); } else if (mLayout == kChord) { if (x < mChords.size()) return TheScale->GetPitchFromTone(y) + TheScale->GetPitchesPerOctave() * mOctave; else return INVALID_PITCH; } else if (mLayout == kSeptatonic) { if (mArrangementMode == kFive) { if (x < 3) { return GridToPitchChordSection(x, y); } else if (x == 3) { if (TheScale->NumTonesInScale() == 7) //septatonic scales only { if (y % 2 == 0) // 7 or maj7 { int nonDiatonic = TheScale->GetPitchFromTone(0) - 1 + TheScale->GetPitchesPerOctave() * (mRootNote / TheScale->GetPitchesPerOctave()) + TheScale->GetPitchesPerOctave() * (mOctave + y / 2); if (TheScale->IsInScale(nonDiatonic)) --nonDiatonic; return nonDiatonic; } if (y % 2 == 1) // 4 or sharp 4 { int nonDiatonic = TheScale->GetPitchFromTone(4) - 1 + TheScale->GetPitchesPerOctave() * (mRootNote / TheScale->GetPitchesPerOctave()) + TheScale->GetPitchesPerOctave() * (mOctave + y / 2); if (TheScale->IsInScale(nonDiatonic)) --nonDiatonic; return nonDiatonic; } } return INVALID_PITCH; } else { x -= 4; } } int numPitchesInScale = TheScale->NumTonesInScale(); if (numPitchesInScale > 8) return INVALID_PITCH; int pos = x + 4 * y; int set = pos / 8; int tone = pos - set * (8 - numPitchesInScale); // + TheScale->GetScaleDegree(); add this for chord following if (pos % 8 >= numPitchesInScale) return INVALID_PITCH; return TheScale->GetPitchFromTone(tone) + TheScale->GetPitchesPerOctave() * (mRootNote / TheScale->GetPitchesPerOctave()) + TheScale->GetPitchesPerOctave() * mOctave; } else if (mLayout == kDrum) { if (x < 4 && y < 4) return x + y * 4; else return INVALID_PITCH; } else if (mLayout == kAllPads) { return x + y * 8; } return 0; } int LaunchpadKeyboard::GridToPitchChordSection(int x, int y) { int numPitchesInScale = TheScale->NumTonesInScale(); if (y < 7 && y < numPitchesInScale) { return CHORD_BUTTON_OFFSET + (numPitchesInScale * (x - 1)) + y; } else if (y == 7) { if (x == 0) return CHORD_ENABLE_BUTTON; if (x == 1) return CHORD_LATCH_BUTTON; if (x == 2) return KEY_LATCH_BUTTON; } return INVALID_PITCH; } void LaunchpadKeyboard::UpdateLights(bool force) { if (mGridControlTarget->GetGridController()) { for (int x = 0; x < mGridControlTarget->GetGridController()->NumCols(); ++x) { for (int y = 0; y < mGridControlTarget->GetGridController()->NumRows(); ++y) { GridColor color = GetGridSquareColor(x, y); mGridControlTarget->GetGridController()->SetLight(x, y, color, force); } } } } GridColor LaunchpadKeyboard::GetGridSquareColor(int x, int y) { int pitch = GridToPitch(x, y); bool inScale = TheScale->MakeDiatonic(pitch) == pitch; bool isRoot = pitch % TheScale->GetPitchesPerOctave() == TheScale->ScaleRoot(); bool isHeld = GetHeldVelocity(GridToPitch(x, y)) > 0; bool isInPentatonic = pitch >= 0 && TheScale->IsInPentatonic(pitch); bool isChordButton = pitch != INVALID_PITCH && pitch < 0; bool isPressedChordButton = isChordButton && IsChordButtonPressed(pitch); bool isChorderEnabled = mChorder && mChorder->IsEnabled(); GridColor color; if (pitch == INVALID_PITCH) { color = kGridColorOff; } else if (pitch == CHORD_ENABLE_BUTTON) { if (mChorder && mChorder->IsEnabled()) color = kGridColor1Bright; else color = kGridColor1Dim; } else if (pitch == CHORD_LATCH_BUTTON) { if (mLatchChords) color = kGridColor3Bright; else color = kGridColor3Dim; } else if (pitch == KEY_LATCH_BUTTON) { if (mLatch) color = kGridColor1Bright; else color = kGridColor1Dim; } else if (isPressedChordButton && isChorderEnabled) { color = kGridColor2Bright; } else if (isChordButton && !isChorderEnabled) { color = kGridColor1Dim; } else if (isChordButton) { color = kGridColor2Dim; } else if (isHeld) { color = kGridColor1Bright; } else if (mLayout == kDrum || mLayout == kAllPads) { color = kGridColor3Bright; } else if (isRoot) { color = kGridColor2Bright; } else if (isInPentatonic) { color = kGridColor3Bright; } else if (inScale) { color = kGridColor3Dim; } else { color = kGridColorOff; } return color; } void LaunchpadKeyboard::OnControllerPageSelected() { UpdateLights(); } void LaunchpadKeyboard::OnScaleChanged() { UpdateLights(); } void LaunchpadKeyboard::KeyPressed(int key, bool isRepeat) { IDrawableModule::KeyPressed(key, isRepeat); } void LaunchpadKeyboard::KeyReleased(int key) { IDrawableModule::KeyReleased(key); } void LaunchpadKeyboard::Poll() { bool chorderEnabled = mChorder && mChorder->IsEnabled(); if (chorderEnabled != mWasChorderEnabled) { mWasChorderEnabled = chorderEnabled; UpdateLights(); } } void LaunchpadKeyboard::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) { mHeldChordTones.clear(); mNoteOutput.Flush(time); } if (checkbox == mPreserveChordRootCheckbox) { if (!ListContains(0, mHeldChordTones)) { mHeldChordTones.push_back(0); if (mChorder) mChorder->AddTone(0); UpdateLights(); } } if (checkbox == mLatchCheckbox) { if (!mLatch) { mNoteOutput.Flush(time); } } } void LaunchpadKeyboard::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mOctaveSlider) { for (int i = 0; i < 128; ++i) mCurrentNotes[i] = 0; mNoteOutput.Flush(time); UpdateLights(); } } void LaunchpadKeyboard::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void LaunchpadKeyboard::Exit() { IDrawableModule::Exit(); if (mGridControlTarget->GetGridController()) mGridControlTarget->GetGridController()->ResetLights(); } void LaunchpadKeyboard::DropdownUpdated(DropdownList* list, int oldVal, double time) { UpdateLights(); } void LaunchpadKeyboard::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadString("chorder", moduleInfo, "", FillDropdown<Chorder*>); mModuleSaveData.LoadEnum<ArrangementMode>("arrangement", moduleInfo, kFull, mArrangementModeDropdown); mModuleSaveData.LoadEnum<LaunchpadLayout>("layout", moduleInfo, kChromatic, mLayoutDropdown); SetUpFromSaveData(); } void LaunchpadKeyboard::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); SetChorder(dynamic_cast<Chorder*>(TheSynth->FindModule(mModuleSaveData.GetString("chorder"), false))); mArrangementMode = mModuleSaveData.GetEnum<ArrangementMode>("arrangement"); mLayout = mModuleSaveData.GetEnum<LaunchpadLayout>("layout"); } ```
/content/code_sandbox/Source/LaunchpadKeyboard.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
5,957
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== PulseSequence.cpp Created: 21 Oct 2018 11:26:09pm Author: Ryan Challinor ============================================================================== */ #include "PulseSequence.h" #include "OpenFrameworksPort.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Profiler.h" #include "PatchCableSource.h" PulseSequence::PulseSequence() { for (int i = 0; i < kMaxSteps; ++i) mVels[i] = 1; } void PulseSequence::Init() { IDrawableModule::Init(); mTransportListenerInfo = TheTransport->AddListener(this, mInterval, OffsetInfo(0, true), false); TheTransport->AddAudioPoller(this); } void PulseSequence::CreateUIControls() { IDrawableModule::CreateUIControls(); mLengthSlider = new IntSlider(this, "length", 3, 2, 96, 15, &mLength, 1, kMaxSteps); mIntervalSelector = new DropdownList(this, "interval", mLengthSlider, kAnchor_Right, (int*)(&mInterval)); mVelocityGrid = new UIGrid("uigrid", 3, 20, 174, 15, mLength, 1, this); mIntervalSelector->AddLabel("1n", kInterval_1n); mIntervalSelector->AddLabel("2n", kInterval_2n); mIntervalSelector->AddLabel("4n", kInterval_4n); mIntervalSelector->AddLabel("4nt", kInterval_4nt); mIntervalSelector->AddLabel("8n", kInterval_8n); mIntervalSelector->AddLabel("8nt", kInterval_8nt); mIntervalSelector->AddLabel("16n", kInterval_16n); mIntervalSelector->AddLabel("16nt", kInterval_16nt); mIntervalSelector->AddLabel("32n", kInterval_32n); mIntervalSelector->AddLabel("64n", kInterval_64n); mIntervalSelector->AddLabel("none", kInterval_None); mAdvanceBackwardButton = new ClickButton(this, "<", mIntervalSelector, kAnchor_Right); mAdvanceForwardButton = new ClickButton(this, ">", mAdvanceBackwardButton, kAnchor_Right); mVelocityGrid->SetGridMode(UIGrid::kMultisliderBipolar); mVelocityGrid->SetListener(this); mVelocityGrid->SetRequireShiftForMultislider(true); for (int i = 0; i < kMaxSteps; ++i) mVelocityGrid->SetVal(i, 0, mVels[i], !K(notifyListener)); for (int i = 0; i < kIndividualStepCables; ++i) { mStepCables[i] = new PatchCableSource(this, kConnectionType_Pulse); mStepCables[i]->SetOverrideCableDir(ofVec2f(0, 1), PatchCableSource::Side::kBottom); AddPatchCableSource(mStepCables[i]); } } PulseSequence::~PulseSequence() { TheTransport->RemoveListener(this); TheTransport->RemoveAudioPoller(this); } void PulseSequence::DrawModule() { if (Minimized() || IsVisible() == false) return; ofSetColor(255, 255, 255, gModuleDrawAlpha); mIntervalSelector->SetShowing(!mHasExternalPulseSource); mIntervalSelector->Draw(); mLengthSlider->Draw(); mVelocityGrid->Draw(); mAdvanceBackwardButton->Draw(); mAdvanceForwardButton->Draw(); for (int i = 0; i < kIndividualStepCables; ++i) { if (i < mLength) { ofVec2f pos = mVelocityGrid->GetCellPosition(i, 0) + mVelocityGrid->GetPosition(true); pos.x += mVelocityGrid->GetWidth() / float(mLength) * .5f; pos.y += mVelocityGrid->GetHeight() + 8; mStepCables[i]->SetManualPosition(pos.x, pos.y); mStepCables[i]->SetEnabled(true); } else { mStepCables[i]->SetEnabled(false); } } } void PulseSequence::CheckboxUpdated(Checkbox* checkbox, double time) { } void PulseSequence::OnTransportAdvanced(float amount) { PROFILER(PulseSequence); ComputeSliders(0); } void PulseSequence::OnTimeEvent(double time) { if (!mHasExternalPulseSource) Step(time, 1, 0); } void PulseSequence::OnPulse(double time, float velocity, int flags) { mHasExternalPulseSource = true; Step(time, velocity, flags); } void PulseSequence::Step(double time, float velocity, int flags) { if (!mEnabled) return; int direction = 1; if (flags & kPulseFlag_Backward) direction = -1; mStep = (mStep + direction + mLength) % mLength; if (flags & kPulseFlag_Reset) mStep = 0; else if (flags & kPulseFlag_Random) mStep = gRandom() % mLength; if (!mHasExternalPulseSource || (flags & kPulseFlag_SyncToTransport)) { mStep = TheTransport->GetSyncedStep(time, this, mTransportListenerInfo, mLength); } if (flags & kPulseFlag_Align) { int stepsPerMeasure = TheTransport->GetStepsPerMeasure(this); int numMeasures = ceil(float(mLength) / stepsPerMeasure); int measure = TheTransport->GetMeasure(time) % numMeasures; mStep = ((TheTransport->GetQuantized(time, mTransportListenerInfo) % stepsPerMeasure) + measure * stepsPerMeasure) % mLength; } float v = mVels[mStep] * velocity; if (v > 0) { DispatchPulse(GetPatchCableSource(), time, v, 0); if (mStep < kIndividualStepCables) DispatchPulse(mStepCables[mStep], time, v, 0); } mVelocityGrid->SetHighlightCol(time, mStep); } void PulseSequence::GetModuleDimensions(float& width, float& height) { width = 180; height = 52; } void PulseSequence::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); mVelocityGrid->TestClick(x, y, right); } void PulseSequence::MouseReleased() { IDrawableModule::MouseReleased(); mVelocityGrid->MouseReleased(); } bool PulseSequence::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); mVelocityGrid->NotifyMouseMoved(x, y); return false; } bool PulseSequence::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) { mVelocityGrid->NotifyMouseScrolled(x, y, scrollX, scrollY, isSmoothScroll, isInvertedScroll); return false; } void PulseSequence::ButtonClicked(ClickButton* button, double time) { if (button == mAdvanceBackwardButton) Step(time, 0, kPulseFlag_Backward); if (button == mAdvanceForwardButton) Step(time, 0, 0); } void PulseSequence::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mIntervalSelector) { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) transportListenerInfo->mInterval = mInterval; } } void PulseSequence::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void PulseSequence::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mLengthSlider) { mVelocityGrid->SetGrid(mLength, 1); GridUpdated(mVelocityGrid, 0, 0, 0, 0); } } void PulseSequence::GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) { if (grid == mVelocityGrid) { for (int i = 0; i < mVelocityGrid->GetCols(); ++i) mVels[i] = mVelocityGrid->GetVal(i, 0); } } void PulseSequence::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); mVelocityGrid->SaveState(out); out << mHasExternalPulseSource; } void PulseSequence::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); mVelocityGrid->LoadState(in); GridUpdated(mVelocityGrid, 0, 0, 0, 0); if (rev >= 2) in >> mHasExternalPulseSource; } void PulseSequence::SaveLayout(ofxJSONElement& moduleInfo) { } void PulseSequence::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void PulseSequence::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/PulseSequence.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,243
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // Stutter.h // modularSynth // // Created by Ryan Challinor on 12/24/12. // // #pragma once #include "MidiDevice.h" #include "RollingBuffer.h" #include "Checkbox.h" #include "Ramp.h" #include "Transport.h" #include "Slider.h" #include "JumpBlender.h" #define STUTTER_BLEND_WRAPAROUND_SAMPLES 100 #define STUTTER_START_BLEND_MS 3 #define STUTTER_BUFFER_SIZE 5 * gSampleRate class Looper; class PatchCableSource; struct StutterParams { StutterParams() {} StutterParams(NoteInterval _interval, float _speed) : interval(_interval) , speedStart(_speed) , speedEnd(_speed) {} StutterParams(NoteInterval _interval, float _speedStart, float _speedEnd, float _speedBlendTime) : interval(_interval) , speedStart(_speedStart) , speedEnd(_speedEnd) , speedBlendTime(_speedBlendTime) {} bool operator==(const StutterParams& other) const { return interval == other.interval && speedStart == other.speedStart && speedEnd == other.speedEnd && speedBlendTime == other.speedBlendTime; } NoteInterval interval{ NoteInterval::kInterval_16n }; float speedStart{ 1 }; float speedEnd{ 1 }; float speedBlendTime{ 0 }; }; class Stutter : public ITimeListener { public: Stutter(); ~Stutter(); void Init(); void DrawStutterBuffer(float x, float y, float width, float height); void StartStutter(double time, StutterParams stutter); void EndStutter(double time, StutterParams stutter); void SetEnabled(double time, bool enabled); //IAudioEffect void ProcessAudio(double time, ChannelBuffer* buffer); //ITimeListener void OnTimeEvent(double time) override; float mFreeStutterLength{ .1 }; float mFreeStutterSpeed{ 1 }; private: void DoCapture(); float GetStutterSampleWithWraparoundBlend(int pos, int ch); void DoStutter(double time, StutterParams stutter); void StopStutter(double time); float GetBufferReadPos(float stutterPos); RollingBuffer mRecordBuffer; ChannelBuffer mStutterBuffer; bool mEnabled{ true }; bool mStuttering{ false }; int mCaptureLength{ 1 }; int mStutterLength{ 1 }; Ramp mStutterSpeed; float mStutterPos{ 0 }; bool mAutoStutter{ false }; Checkbox* mAutoCheckbox{ nullptr }; Ramp mBlendRamp; static bool sQuantize; ofMutex mMutex; StutterParams mCurrentStutter; static int sStutterSubdivide; IntSlider* mSubdivideSlider{ nullptr }; JumpBlender mJumpBlender[ChannelBuffer::kMaxNumChannels]{}; int mNanopadScene{ 0 }; std::list<StutterParams> mStutterStack; Ramp mStutterLengthRamp; bool mFadeStutter{ false }; Checkbox* mFadeCheckbox{ nullptr }; }; ```
/content/code_sandbox/Source/Stutter.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
806
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // RollingBuffer.cpp // modularSynth // // Created by Ryan Challinor on 11/25/12. // // #include "RollingBuffer.h" #include "SynthGlobals.h" RollingBuffer::RollingBuffer(int sizeInSamples) : mBuffer(sizeInSamples) { } RollingBuffer::~RollingBuffer() { } float RollingBuffer::GetSample(int samplesAgo, int channel) { assert(samplesAgo >= 0); assert(samplesAgo < Size()); return mBuffer.GetChannel(channel)[(Size() + mOffsetToNow[channel] - samplesAgo) % Size()]; } void RollingBuffer::ReadChunk(float* dst, int size, int samplesAgo, int channel) { assert(size <= Size()); int offset = mOffsetToNow[channel] - samplesAgo; if (offset < 0) offset += Size(); int wrapSamples = size - offset; if (wrapSamples <= 0) //no wraparound { BufferCopy(dst, mBuffer.GetChannel(channel) + (offset - size), size); } else //wrap around loop point { BufferCopy(dst, mBuffer.GetChannel(channel) + (Size() - wrapSamples), wrapSamples); BufferCopy(dst + wrapSamples, mBuffer.GetChannel(channel), (size - wrapSamples)); } } void RollingBuffer::Accum(int samplesAgo, float sample, int channel) { assert(samplesAgo < Size()); mBuffer.GetChannel(channel)[(Size() + mOffsetToNow[channel] - samplesAgo) % Size()] += sample; } void RollingBuffer::WriteChunk(float* samples, int size, int channel) { assert(size < Size()); int wrapSamples = (mOffsetToNow[channel] + size) - Size(); if (wrapSamples <= 0) //no wraparound { BufferCopy(mBuffer.GetChannel(channel) + mOffsetToNow[channel], samples, size); } else //wrap around loop point { BufferCopy(mBuffer.GetChannel(channel) + mOffsetToNow[channel], samples, (size - wrapSamples)); BufferCopy(mBuffer.GetChannel(channel), samples + (size - wrapSamples), wrapSamples); } mOffsetToNow[channel] = (mOffsetToNow[channel] + size) % Size(); if (channel != 0 && mOffsetToNow[channel] < mOffsetToNow[0] - gBufferSize * 2) //channels out of sync, probably was only writing to channel 0 for a while mOffsetToNow[channel] = mOffsetToNow[0]; } void RollingBuffer::Write(float sample, int channel) { mBuffer.GetChannel(channel)[mOffsetToNow[channel]] = sample; mOffsetToNow[channel] = (mOffsetToNow[channel] + 1) % Size(); if (channel != 0 && mOffsetToNow[channel] < mOffsetToNow[0] - gBufferSize * 2) //channels out of sync, probably was only writing to channel 0 for a while mOffsetToNow[channel] = mOffsetToNow[0]; } void RollingBuffer::ClearBuffer() { mBuffer.Clear(); for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i) mOffsetToNow[i] = 0; } void RollingBuffer::Draw(int x, int y, int width, int height, int length /*= -1*/, int channel /*= -1*/, int delayOffset /*= 0*/) { ofPushStyle(); ofPushMatrix(); ofTranslate(x, y); if (length == -1) //draw full rolling buffer { if (channel == -1) DrawAudioBuffer(width, height, &mBuffer, 0, Size(), -1); else DrawAudioBuffer(width, height, mBuffer.GetChannel(channel), 0, Size(), -1); } else //draw segment { int startSample; if (channel == -1) startSample = mOffsetToNow[0] - length - delayOffset; else startSample = mOffsetToNow[channel] - length - delayOffset; while (startSample < 0) startSample += Size(); int endSample = startSample + length; while (endSample >= Size()) endSample -= Size(); //draw wraparound if (channel == -1) DrawAudioBuffer(width, height, &mBuffer, startSample, endSample, -1, 1, ofColor::black, Size()); else DrawAudioBuffer(width, height, mBuffer.GetChannel(channel), startSample, endSample, -1, 1, ofColor::black, Size()); } ofPopMatrix(); ofPopStyle(); } namespace { const int kSaveStateRev = 3; } void RollingBuffer::SaveState(FileStreamOut& out) { out << kSaveStateRev; out << mBuffer.NumActiveChannels(); out << Size(); for (int i = 0; i < mBuffer.NumActiveChannels(); ++i) { out << mOffsetToNow[i]; out.Write(mBuffer.GetChannel(i), Size()); } } void RollingBuffer::LoadState(FileStreamIn& in) { int rev; in >> rev; int channels = ChannelBuffer::kMaxNumChannels; if (rev >= 2) in >> channels; int savedSize = Size(); if (rev >= 3) in >> savedSize; mBuffer.SetNumActiveChannels(channels); for (int i = 0; i < channels; ++i) { in >> mOffsetToNow[i]; mOffsetToNow[i] %= Size(); if (savedSize <= Size()) { in.Read(mBuffer.GetChannel(i), savedSize); } else { //saved with a longer buffer than we have... not sure what the right solution here is, but lets just fill the buffer over and over again until we consume all of the samples int sizeLeft = savedSize; while (sizeLeft > 0) { in.Read(mBuffer.GetChannel(i), MIN(sizeLeft, Size())); sizeLeft -= Size(); } } } } ```
/content/code_sandbox/Source/RollingBuffer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,460
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== SampleCapturer.cpp Created: 12 Nov 2020 6:36:00pm Author: Ryan Challinor ============================================================================== */ #include "SampleCapturer.h" #include "ModularSynth.h" #include "Profiler.h" #include "UIControlMacros.h" #include "Sample.h" #include "Checkbox.h" #include "juce_gui_basics/juce_gui_basics.h" SampleCapturer::SampleCapturer() : IAudioProcessor(gBufferSize) { } void SampleCapturer::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); CHECKBOX(mWantRecordCheckbox, "record", &mWantRecord); BUTTON_STYLE(mPlayButton, "play", ButtonDisplayStyle::kPlay); BUTTON(mSaveButton, "save"); BUTTON(mDeleteButton, "delete"); ENDUIBLOCK0(); } SampleCapturer::~SampleCapturer() { } void SampleCapturer::Process(double time) { PROFILER(SampleCapturer); IAudioReceiver* target = GetTarget(); if (target == nullptr) return; SyncBuffers(); if (!mEnabled) { for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { Add(target->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize()); GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize(), ch); } GetBuffer()->Reset(); return; } int bufferSize = GetBuffer()->BufferSize(); ChannelBuffer* out = target->GetBuffer(); gWorkChannelBuffer.SetNumActiveChannels(GetBuffer()->NumActiveChannels()); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { Add(out->GetChannel(ch), GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize()); BufferCopy(gWorkChannelBuffer.GetChannel(ch), GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize()); } for (int i = 0; i < bufferSize; ++i) { if (mWantRecord) { for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { if (mIsRecording || GetBuffer()->GetChannel(ch)[i] != 0) { auto& sample = mSamples[mCurrentSampleIndex]; if (!mIsRecording) { mIsRecording = true; sample.mBuffer.SetNumActiveChannels(GetBuffer()->NumActiveChannels()); sample.mBuffer.Clear(); } sample.mBuffer.GetChannel(ch)[sample.mRecordingLength] = GetBuffer()->GetChannel(ch)[i]; } } if (mIsRecording) { ++mSamples[mCurrentSampleIndex].mRecordingLength; if (mSamples[mCurrentSampleIndex].mRecordingLength >= mSamples[mCurrentSampleIndex].mBuffer.BufferSize()) { mIsRecording = false; mWantRecord = false; mCurrentSampleIndex = (mCurrentSampleIndex + 1) % mSamples.size(); } } } else { if (mIsRecording) { mIsRecording = false; mCurrentSampleIndex = (mCurrentSampleIndex + 1) % mSamples.size(); } } } for (size_t sample = 0; sample < mSamples.size(); ++sample) { if (mSamples[sample].mPlaybackPos >= 0) { for (int i = 0; i < bufferSize; ++i) { for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { out->GetChannel(ch)[i] += mSamples[sample].mBuffer.GetChannel(ch)[mSamples[sample].mPlaybackPos]; gWorkChannelBuffer.GetChannel(ch)[i] += mSamples[sample].mBuffer.GetChannel(ch)[mSamples[sample].mPlaybackPos]; } ++mSamples[sample].mPlaybackPos; if (mSamples[sample].mPlaybackPos >= mSamples[sample].mRecordingLength) { mSamples[sample].mPlaybackPos = -1; break; } } } } for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) GetVizBuffer()->WriteChunk(gWorkChannelBuffer.GetChannel(ch), GetBuffer()->BufferSize(), ch); GetBuffer()->Reset(); } namespace { const int kBufferStartY = 20; const int kBufferHeight = 60; const int kBufferWidth = 200; const int kBufferSpacing = 5; } void SampleCapturer::DrawModule() { if (Minimized() || IsVisible() == false) return; int y = kBufferStartY; for (size_t i = 0; i < mSamples.size(); ++i) { if (mSamples[i].mRecordingLength > 0) { ofPushMatrix(); ofTranslate(5, y); DrawAudioBuffer(kBufferWidth, kBufferHeight, &mSamples[i].mBuffer, 0, mSamples[i].mBuffer.BufferSize(), mSamples[i].mPlaybackPos); ofPopMatrix(); } if (mCurrentSampleIndex == i) ofSetColor(ofColor::white); else ofSetColor(IDrawableModule::GetColor(kModuleCategory_Audio)); ofRect(5, y, kBufferWidth, kBufferHeight); if (i == mCurrentSampleIndex) { mPlayButton->SetPosition(10 + kBufferWidth, y); mSaveButton->PositionTo(mPlayButton, kAnchor_Below); mDeleteButton->PositionTo(mSaveButton, kAnchor_Below); } y += kBufferHeight + kBufferSpacing; } mWantRecordCheckbox->Draw(); mPlayButton->Draw(); mSaveButton->Draw(); mDeleteButton->Draw(); } void SampleCapturer::ButtonClicked(ClickButton* button, double time) { using namespace juce; if (button == mPlayButton) { mSamples[mCurrentSampleIndex].mPlaybackPos = 0; } if (button == mSaveButton) { FileChooser chooser("Save sample as...", File(ofToDataPath(ofGetTimestampString("samples/%Y-%m-%d_%H-%M-%S.wav"))), "*.wav", true, false, TheSynth->GetFileChooserParent()); if (chooser.browseForFileToSave(true)) Sample::WriteDataToFile(chooser.getResult().getFullPathName().toStdString(), &mSamples[mCurrentSampleIndex].mBuffer, mSamples[mCurrentSampleIndex].mRecordingLength); } if (button == mDeleteButton) { mSamples[mCurrentSampleIndex].mBuffer.Clear(); mSamples[mCurrentSampleIndex].mRecordingLength = 0; } } void SampleCapturer::GetModuleDimensions(float& w, float& h) { w = kBufferWidth + 60; h = (int)mSamples.size() * (kBufferHeight + kBufferSpacing) + kBufferStartY; } void SampleCapturer::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); if (right) return; for (int i = 0; i < (int)mSamples.size(); ++i) { if (y >= kBufferStartY + i * (kBufferHeight + kBufferSpacing) && y <= kBufferStartY + i * (kBufferHeight + kBufferSpacing) + kBufferHeight) { mCurrentSampleIndex = i; if (x < kBufferWidth + 10) { ChannelBuffer grab(mSamples[i].mRecordingLength); grab.SetNumActiveChannels(mSamples[i].mBuffer.NumActiveChannels()); for (int ch = 0; ch < grab.NumActiveChannels(); ++ch) BufferCopy(grab.GetChannel(ch), mSamples[i].mBuffer.GetChannel(ch), mSamples[i].mRecordingLength); TheSynth->GrabSample(&grab, "captured", false); } } } mIsDragging = true; } void SampleCapturer::MouseReleased() { IDrawableModule::MouseReleased(); mIsDragging = false; } bool SampleCapturer::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); if (mIsDragging) { } return false; } void SampleCapturer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void SampleCapturer::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); } void SampleCapturer::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); for (int i = 0; i < mSamples.size(); ++i) mSamples[i].mBuffer.Save(out, mSamples[i].mBuffer.BufferSize()); } void SampleCapturer::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); int readLength; for (int i = 0; i < mSamples.size(); ++i) mSamples[i].mBuffer.Load(in, readLength, ChannelBuffer::LoadMode::kSetBufferSize); } ```
/content/code_sandbox/Source/SampleCapturer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,208
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== UnstablePitch.h Created: 2 Mar 2021 7:48:14pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "Slider.h" #include "ModulationChain.h" #include "PerlinNoise.h" struct UnstablePerlinModulation { UnstablePerlinModulation(float amount, float warble, float noise) : mPerlinAmount(amount) , mPerlinWarble(warble) , mPerlinNoise(noise) { mPerlinSeed = gRandom() % 10000; } PerlinNoise mNoise; float mPerlinAmount; float mPerlinWarble; float mPerlinNoise; int mPerlinSeed; float GetValue(double time, float travel, float offset) { return mNoise.noise(travel * ofClamp(mPerlinWarble * 10, 0, 1), offset + time * mPerlinNoise / 5, time * mPerlinWarble / 100 + mPerlinSeed); } }; class UnstablePitch : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public IAudioPoller { public: UnstablePitch(); virtual ~UnstablePitch(); static IDrawableModule* Create() { return new UnstablePitch(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Init() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; //IAudioPoller void OnTransportAdvanced(float amount) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void LoadLayout(const ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } void FillModulationBuffer(double time, int voiceIdx); UnstablePerlinModulation mPerlin{ .2, .1, 0 }; FloatSlider* mAmountSlider{ nullptr }; FloatSlider* mWarbleSlider{ nullptr }; FloatSlider* mNoiseSlider{ nullptr }; float mWidth{ 200 }; float mHeight{ 20 }; std::array<bool, kNumVoices> mIsVoiceUsed{ false }; std::array<int, 128> mPitchToVoice{}; int mVoiceRoundRobin{ 0 }; Modulations mModulation{ false }; }; ```
/content/code_sandbox/Source/UnstablePitch.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
782
```objective-c /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== SampleLayerer.h Created: 2 Jun 2019 2:43:58pm Author: Ryan Challinor ============================================================================== */ #pragma once ```
/content/code_sandbox/Source/SampleLayerer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
138
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // EuclideanSequencer.cpp // Bespoke // // Created by Jack van Klaren on Mar 17 2024. // Based on CircleSequencer by Ryan Challinor // // #include "EuclideanSequencer.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Profiler.h" #include "DrumPlayer.h" #include "PatchCableSource.h" namespace { ofVec2f PolToCar(float pos, float radius) { return ofVec2f(radius * sin(pos * TWO_PI), radius * -cos(pos * TWO_PI)); } ofVec2f CarToPol(float x, float y) { float pos = FloatWrap(atan2(x, -y) / TWO_PI, 1); return ofVec2f(pos, sqrtf(x * x + y * y)); } } EuclideanSequencer::EuclideanSequencer() { for (int i = 0; i < 4; ++i) mEuclideanSequencerRings.push_back(new EuclideanSequencerRing(this, i)); } void EuclideanSequencer::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } void EuclideanSequencer::CreateUIControls() { IDrawableModule::CreateUIControls(); int x = 210; int y = 5; int xcolumn = 115; mRndLengthChanceSlider = new FloatSlider(this, "step chance", 0 * xcolumn + x, y, 110, 15, &mRndLengthChance, 0.00f, 1.00f, 2); mRndLengthLoSlider = new FloatSlider(this, "stp lo", 0 * xcolumn + x, y + 20, 55, 15, &mRndLengthLo, 0, EUCLIDEAN_SEQUENCER_MAX_STEPS, 0); mRndLengthHiSlider = new FloatSlider(this, "stp hi", 0 * xcolumn + x + 55, y + 20, 55, 15, &mRndLengthHi, 0, EUCLIDEAN_SEQUENCER_MAX_STEPS, 0); mRndOnsetChanceSlider = new FloatSlider(this, "onset chance", 1 * xcolumn + x, y, 110, 15, &mRndOnsetChance, 0.00f, 1.00f, 2); mRndOnsetLoSlider = new FloatSlider(this, "ons lo", 1 * xcolumn + x, y + 20, 55, 15, &mRndOnsetLo, 0, EUCLIDEAN_SEQUENCER_MAX_STEPS, 0); mRndOnsetHiSlider = new FloatSlider(this, "ons hi", 1 * xcolumn + x + 55, y + 20, 55, 15, &mRndOnsetHi, 0, EUCLIDEAN_SEQUENCER_MAX_STEPS, 0); mRndRotationChanceSlider = new FloatSlider(this, "rot chance", 2 * xcolumn + x, y, 110, 15, &mRndRotationChance, 0.00f, 1.00f, 2); mRndRotationLoSlider = new FloatSlider(this, "rot lo", 2 * xcolumn + x, y + 20, 55, 15, &mRndRotationLo, EUCLIDEAN_ROTATION_MIN, EUCLIDEAN_ROTATION_MAX, 0); mRndRotationHiSlider = new FloatSlider(this, "rot hi", 2 * xcolumn + x + 55, y + 20, 55, 15, &mRndRotationHi, EUCLIDEAN_ROTATION_MIN, EUCLIDEAN_ROTATION_MAX, 0); mRndOffsetChanceSlider = new FloatSlider(this, "offset chance", 3 * xcolumn + x, y, 110, 15, &mRndOffsetChance, 0.00f, 1.00f, 2); mRndOffsetLoSlider = new FloatSlider(this, "o lo", 3 * xcolumn + x, y + 20, 55, 15, &mRndOffsetLo, -0.25f, 0.25f, 2); mRndOffsetHiSlider = new FloatSlider(this, "o hi", 3 * xcolumn + x + 55, y + 20, 55, 15, &mRndOffsetHi, -0.25f, 0.25f, 2); mRndNoteChanceSlider = new FloatSlider(this, "note chance", 4 * xcolumn + x, y, 110, 15, &mRndNoteChance, 0.00f, 1.00f, 2); mRndOctaveLoSlider = new FloatSlider(this, "oct lo", 4 * xcolumn + x, y + 20, 55, 15, &mRndOctaveLo, 0.00f, 5.00f, 0); mRndOctaveHiSlider = new FloatSlider(this, "oct hi", 4 * xcolumn + x + 55, y + 20, 55, 15, &mRndOctaveHi, 0.00f, 5.00f, 0); x = 210; y = 65; xcolumn = 95; mRnd0Button = new ClickButton(this, "random0", 0 * xcolumn + x, y); mRnd1Button = new ClickButton(this, "random1", 1 * xcolumn + x, y); mRnd2Button = new ClickButton(this, "random2", 2 * xcolumn + x, y); mRnd3Button = new ClickButton(this, "random3", 3 * xcolumn + x, y); x = 595; mRandomizeButton = new ClickButton(this, "random", x, y); y = 45; mClearButton = new ClickButton(this, "clear", x, y); y = 90; mRndLengthButton = new ClickButton(this, "steps", x, y); mRndOnsetsButton = new ClickButton(this, "onsets", x, y + 20); mRndRotationButton = new ClickButton(this, "rotation", x, y + 40); mRndOffsetButton = new ClickButton(this, "offset", x, y + 60); mRndNoteButton = new ClickButton(this, "note", x, y + 80); int aInitState = (int)ofRandom(0, EUCLIDEAN_INITIALSTATE_MAX - 0.01); // select a random default state between 0 and max-1 for (int i = 0; i < mEuclideanSequencerRings.size(); ++i) { mEuclideanSequencerRings[i]->CreateUIControls(); mEuclideanSequencerRings[i]->InitialState(aInitState); RandomizeNote(i, true); } } EuclideanSequencer::~EuclideanSequencer() { TheTransport->RemoveAudioPoller(this); for (int i = 0; i < mEuclideanSequencerRings.size(); ++i) delete mEuclideanSequencerRings[i]; } void EuclideanSequencer::Resize(float w, float h) { mWidth = MAX(w, mWidthMin); // limit minimum width mWidth = MIN(mWidth, mWidthMax); // limit maximum width // mHeight = 200; // fixed height } void EuclideanSequencer::OnTransportAdvanced(float amount) { PROFILER(EuclideanSequencer); if (!mEnabled) return; ComputeSliders(0); for (int i = 0; i < mEuclideanSequencerRings.size(); ++i) mEuclideanSequencerRings[i]->OnTransportAdvanced(amount); } void EuclideanSequencer::DrawModule() { if (Minimized() || IsVisible() == false) return; mRandomizeButton->Draw(); mRndLengthButton->Draw(); mRndOnsetsButton->Draw(); mRndRotationButton->Draw(); mRndOffsetButton->Draw(); mRndNoteButton->Draw(); mRnd0Button->Draw(); mRnd1Button->Draw(); mRnd2Button->Draw(); mRnd3Button->Draw(); mClearButton->Draw(); mRndLengthChanceSlider->Draw(); mRndLengthLoSlider->Draw(); mRndLengthHiSlider->Draw(); mRndOnsetChanceSlider->Draw(); mRndOnsetLoSlider->Draw(); mRndOnsetHiSlider->Draw(); mRndRotationChanceSlider->Draw(); mRndRotationLoSlider->Draw(); mRndRotationHiSlider->Draw(); mRndOffsetChanceSlider->Draw(); mRndOffsetLoSlider->Draw(); mRndOffsetHiSlider->Draw(); mRndNoteChanceSlider->Draw(); mRndOctaveLoSlider->Draw(); mRndOctaveHiSlider->Draw(); for (int i = 0; i < mEuclideanSequencerRings.size(); ++i) mEuclideanSequencerRings[i]->Draw(); // Grey lines around circle sliders ofPushStyle(); ofSetColor(128, 128, 128); ofSetLineWidth(.1f); ofLine(210, 85, 590, 85); ofLine(590, 85, 590, 185); ofPopStyle(); // Rotating tranposrt line ofPushStyle(); ofSetColor(ofColor::lime); float pos = TheTransport->GetMeasurePos(gTime); ofVec2f end = PolToCar(pos, 100); ofLine(100, 100, 100 + end.x, 100 + end.y); ofPopStyle(); } void EuclideanSequencer::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); for (int i = 0; i < mEuclideanSequencerRings.size(); ++i) mEuclideanSequencerRings[i]->OnClicked(x, y, right); } void EuclideanSequencer::MouseReleased() { IDrawableModule::MouseReleased(); for (int i = 0; i < mEuclideanSequencerRings.size(); ++i) mEuclideanSequencerRings[i]->MouseReleased(); } bool EuclideanSequencer::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); for (int i = 0; i < mEuclideanSequencerRings.size(); ++i) mEuclideanSequencerRings[i]->MouseMoved(x, y); return false; } void EuclideanSequencer::CheckboxUpdated(Checkbox* checkbox, double time) { } void EuclideanSequencer::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { // Check if Lo > Hi or Hi < Lo if (slider == mRndLengthLoSlider) { mRndLengthLo = (int)mRndLengthLo; if (mRndLengthLo > mRndLengthHi) mRndLengthLo = mRndLengthHi; } if (slider == mRndLengthHiSlider) { mRndLengthHi = (int)mRndLengthHi; if (mRndLengthHi < mRndLengthLo) mRndLengthHi = mRndLengthLo; } if (slider == mRndOnsetLoSlider) { mRndOnsetLo = (int)mRndOnsetLo; if (mRndOnsetLo > mRndOnsetHi) mRndOnsetLo = mRndOnsetHi; } if (slider == mRndOnsetHiSlider) { mRndOnsetHi = (int)mRndOnsetHi; if (mRndOnsetHi < mRndOnsetLo) mRndOnsetHi = mRndOnsetLo; } if (slider == mRndRotationLoSlider) { mRndRotationLo = (int)mRndRotationLo; if (mRndRotationLo > mRndRotationHi) mRndRotationLo = mRndRotationHi; } if (slider == mRndRotationHiSlider) { mRndRotationHi = (int)mRndRotationHi; if (mRndRotationHi < mRndRotationLo) mRndRotationHi = mRndRotationLo; } if (slider == mRndOffsetLoSlider) { if (mRndOffsetLo > mRndOffsetHi) mRndOffsetLo = mRndOffsetHi; } if (slider == mRndOffsetHiSlider) { if (mRndOffsetHi < mRndOffsetLo) mRndOffsetHi = mRndOffsetLo; } if (slider == mRndOctaveLoSlider) { // no rounding to int to avoid stuck values when using mousewheel if (mRndOctaveLo > mRndOctaveHi) mRndOctaveLo = mRndOctaveHi; } if (slider == mRndOctaveHiSlider) { // no rounding to int to avoid stuck values when using mousewheel if (mRndOctaveHi < mRndOctaveLo) mRndOctaveHi = mRndOctaveLo; } // Handle slider updates of all ring sliders for (int i = 0; i < mEuclideanSequencerRings.size(); ++i) mEuclideanSequencerRings[i]->FloatSliderUpdated(slider, oldVal, time); } void EuclideanSequencer::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void EuclideanSequencer::DropdownUpdated(DropdownList* list, int oldVal, double time) { } void EuclideanSequencer::ButtonClicked(ClickButton* button, double time) { bool randomizeAll{ false }; if (button == mRandomizeButton) randomizeAll = true; if (button == mRndLengthButton || randomizeAll) RandomizeLength(-1); if (button == mRndOnsetsButton || randomizeAll) RandomizeOnset(-1); if (button == mRndRotationButton || randomizeAll) RandomizeRotation(-1); if (button == mRndOffsetButton || randomizeAll) RandomizeOffset(-1); if (button == mRndNoteButton || randomizeAll) RandomizeNote(-1, false); int ringIndex{ -1 }; if (button == mRnd0Button) ringIndex = 0; if (button == mRnd1Button) ringIndex = 1; if (button == mRnd2Button) ringIndex = 2; if (button == mRnd3Button) ringIndex = 3; if (ringIndex != -1) // update 1 ring only { RandomizeLength(ringIndex); RandomizeOnset(ringIndex); RandomizeRotation(ringIndex); RandomizeOffset(ringIndex); RandomizeNote(ringIndex, false); } if (button == mClearButton) { for (int i = 0; i < mEuclideanSequencerRings.size(); ++i) mEuclideanSequencerRings[i]->Clear(); } } void EuclideanSequencer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadBool("shortnotes", moduleInfo, false); SetUpFromSaveData(); } void EuclideanSequencer::SetUpFromSaveData() { mPlayShortNotes = mModuleSaveData.GetBool("shortnotes"); } void EuclideanSequencer::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); float width, height; GetModuleDimensions(width, height); out << width; out << height; out << (int)mEuclideanSequencerRings.size(); for (size_t i = 0; i < mEuclideanSequencerRings.size(); ++i) mEuclideanSequencerRings[i]->SaveState(out); out << mRndLengthChance; out << mRndLengthLo; out << mRndLengthHi; out << mRndOnsetChance; out << mRndOnsetLo; out << mRndOnsetHi; out << mRndRotationChance; out << mRndRotationLo; out << mRndRotationHi; out << mRndOffsetChance; out << mRndOffsetLo; out << mRndOffsetHi; out << mRndNoteChance; out << mRndOctaveLo; out << mRndOctaveHi; } void EuclideanSequencer::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (!ModuleContainer::DoesModuleHaveMoreSaveData(in)) return; //this was saved before we added versioning, bail out if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); float width, height; in >> width; in >> height; Resize(width, height); int numRings; in >> numRings; for (size_t i = 0; i < mEuclideanSequencerRings.size() && i < numRings; ++i) mEuclideanSequencerRings[i]->LoadState(in); if (rev >= 2) { in >> mRndLengthChance; in >> mRndLengthLo; in >> mRndLengthHi; in >> mRndOnsetChance; in >> mRndOnsetLo; in >> mRndOnsetHi; in >> mRndRotationChance; in >> mRndRotationLo; in >> mRndRotationHi; in >> mRndOffsetChance; in >> mRndOffsetLo; in >> mRndOffsetHi; in >> mRndNoteChance; in >> mRndOctaveLo; in >> mRndOctaveHi; } } void EuclideanSequencer::RandomizeLength(int ringIndex) { int iFrom{ 0 }; int iTo{ (int)mEuclideanSequencerRings.size() }; // Check if only 1 ring is updated if (ringIndex >= 0 && ringIndex < mEuclideanSequencerRings.size()) { iFrom = ringIndex; iTo = ringIndex + 1; } // Update all rings or only 1 ring, depending on iFrom and iTo for (int i = iFrom; i < iTo; ++i) { if (ofRandom(1) < mRndLengthChance) mEuclideanSequencerRings[i]->SetSteps((int)ofRandom(mRndLengthLo, mRndLengthHi + 0.9f)); } } void EuclideanSequencer::RandomizeOnset(int ringIndex) { int iFrom{ 0 }; int iTo{ (int)mEuclideanSequencerRings.size() }; // Check if only 1 ring is updated if (ringIndex >= 0 && ringIndex < mEuclideanSequencerRings.size()) { iFrom = ringIndex; iTo = ringIndex + 1; } // Update all rings or only 1 ring, depending on iFrom and iTo for (int i = iFrom; i < iTo; ++i) { if (ofRandom(1) < mRndOnsetChance) mEuclideanSequencerRings[i]->SetOnsets((int)ofRandom(mRndOnsetLo, mRndOnsetHi + 0.9f)); } } void EuclideanSequencer::RandomizeRotation(int ringIndex) { int iFrom{ 0 }; int iTo{ (int)mEuclideanSequencerRings.size() }; // Check if only 1 ring is updated if (ringIndex >= 0 && ringIndex < mEuclideanSequencerRings.size()) { iFrom = ringIndex; iTo = ringIndex + 1; } // Update all rings or only 1 ring, depending on iFrom and iTo for (int i = iFrom; i < iTo; ++i) { if (ofRandom(1) < mRndRotationChance) { // Limit max rotation to current Steps int maxRotation = mEuclideanSequencerRings[i]->GetSteps(); maxRotation = MIN(mRndRotationHi, maxRotation); mEuclideanSequencerRings[i]->SetRotation((int)ofRandom(mRndRotationLo, maxRotation + 0.9f)); } } } void EuclideanSequencer::RandomizeOffset(int ringIndex) { int iFrom{ 0 }; int iTo{ (int)mEuclideanSequencerRings.size() }; // Check if only 1 ring is updated if (ringIndex >= 0 && ringIndex < mEuclideanSequencerRings.size()) { iFrom = ringIndex; iTo = ringIndex + 1; } // Update all rings or only 1 ring, depending on iFrom and iTo for (int i = iFrom; i < iTo; ++i) { if (ofRandom(1) < mRndOffsetChance) { if (i == 0) mEuclideanSequencerRings[i]->SetOffset(ofRandom(0, MIN(0.04, mRndOffsetHi))); else mEuclideanSequencerRings[i]->SetOffset(ofRandom(mRndOffsetLo, mRndOffsetHi)); } } } void EuclideanSequencer::RandomizeNote(int ringIndex, bool force) { int iFrom{ 0 }; int iTo{ (int)mEuclideanSequencerRings.size() }; // Check if only 1 ring is updated if (ringIndex >= 0 && ringIndex < mEuclideanSequencerRings.size()) { iFrom = ringIndex; iTo = ringIndex + 1; } // Update all rings or only 1 ring, depending on iFrom and iTo for (int i = iFrom; i < iTo; ++i) { if (ofRandom(1) < mRndNoteChance || force) { // 0 = 0 1 2 3 if ((int)mRndOctaveLo == 0 && (int)mRndOctaveHi == 0) { mEuclideanSequencerRings[i]->SetPitch(i); } else { int numPitchesInScale = TheScale->NumTonesInScale(); // +2 to return octave 1 int noteFrom = numPitchesInScale * (mRndOctaveLo + 2) + TheScale->GetScaleDegree(); // hi - lo + 1 = range, plus noteFrom int noteTo = numPitchesInScale * (mRndOctaveHi - mRndOctaveLo + 1) + noteFrom; // Try 5 times to generate a unique random pitch. This prevents stuck notes on some synths float newPitch; bool isUnique; int attempts = 0; do { isUnique = true; newPitch = TheScale->GetPitchFromTone(ofRandom(noteFrom, noteTo)); for (int j = 0; j < mEuclideanSequencerRings.size(); ++j) { if (mEuclideanSequencerRings[j]->GetPitch() == newPitch && j != i) { isUnique = false; break; } } attempts++; } while (!isUnique && attempts < 5); if (isUnique) { mEuclideanSequencerRings[i]->SetPitch(newPitch); } } } } } EuclideanSequencerRing::EuclideanSequencerRing(EuclideanSequencer* owner, int index) : mPitch(index) , mOwner(owner) , mIndex(index) { mSteps.fill(0); } void EuclideanSequencerRing::CreateUIControls() { int x = mIndex * 95 + 210; int y = 90; mLengthSlider = new FloatSlider(mOwner, ("steps" + ofToString(mIndex)).c_str(), x, y, 90, 15, &mLength, 0, EUCLIDEAN_SEQUENCER_MAX_STEPS, 0); mOnsetSlider = new FloatSlider(mOwner, ("onsets" + ofToString(mIndex)).c_str(), x, y + 20, 90, 15, &mOnset, 0, EUCLIDEAN_SEQUENCER_MAX_STEPS, 0); mRotationSlider = new FloatSlider(mOwner, ("rotation" + ofToString(mIndex)).c_str(), x, y + 40, 90, 15, &mRotation, EUCLIDEAN_ROTATION_MIN, EUCLIDEAN_ROTATION_MAX, 0); mOffsetSlider = new FloatSlider(mOwner, ("offset" + ofToString(mIndex)).c_str(), x, y + 60, 90, 15, &mOffset, -.25f, .25f, 2); mNoteSelector = new TextEntry(mOwner, ("note" + ofToString(mIndex)).c_str(), x, y + 80, 4, &mPitch, 0, 127); mDestinationCable = new AdditionalNoteCable(); mDestinationCable->SetPatchCableSource(new PatchCableSource(mOwner, kConnectionType_Note)); mDestinationCable->GetPatchCableSource()->SetOverrideCableDir(ofVec2f(0, 1), PatchCableSource::Side::kBottom); mOwner->AddPatchCableSource(mDestinationCable->GetPatchCableSource()); mDestinationCable->GetPatchCableSource()->SetManualPosition(x + 50, y + 105); // Calculate Euclidean steps FloatSliderUpdated(mLengthSlider, 0, 0); } void EuclideanSequencerRing::InitialState(int state) { // 4 lines for 4 circles, values: mLength, mOnset, mRotation, mNote int defaultStates[EUCLIDEAN_INITIALSTATE_MAX][4][3] = { { { 4, 4, 0 }, { 12, 2, 3 }, { 8, 4, 1 }, { 10, 2, 2 }, }, { { 16, 4, 1 }, { 8, 6, 0 }, { 16, 2, 3 }, { 8, 2, 5 }, }, { { 16, 6, 0 }, { 16, 7, 3 }, { 8, 4, 1 }, { 10, 2, 2 }, }, { { 20, 4, 0 }, { 11, 3, 2 }, { 16, 2, -2 }, { 17, 2, -1 }, } }; state = MIN(state, EUCLIDEAN_INITIALSTATE_MAX - 1); state = MAX(state, 0); mLengthSlider->SetValue(defaultStates[state][mIndex][0], gTime, true); mOnsetSlider->SetValue(defaultStates[state][mIndex][1], gTime, true); mRotationSlider->SetValue(defaultStates[state][mIndex][2], gTime, true); } void EuclideanSequencerRing::Clear() { mLengthSlider->SetValue(0, gTime, true); mOnsetSlider->SetValue(0, gTime, true); mRotationSlider->SetValue(0, gTime, true); mOffsetSlider->SetValue(0, gTime, true); mNoteSelector->SetValue(mIndex, gTime, true); } void EuclideanSequencerRing::Draw() { ofPushStyle(); ofSetColor(128, 128, 128); DrawTextNormal(NoteName(mPitch, false, true), mIndex * 95 + 210 + 60, 182); ofPopStyle(); ofPushStyle(); switch (mIndex) { case 0: if (mLength == 0 || mOnset == 0) { ofSetColor(150, 100, 100); } else { ofSetColor(255, 150, 150); } break; case 1: if (mLength == 0 || mOnset == 0) { ofSetColor(150, 150, 100); } else { ofSetColor(255, 255, 150); } break; case 2: if (mLength == 0 || mOnset == 0) { ofSetColor(100, 150, 150); } else { ofSetColor(150, 255, 255); } break; case 3: if (mLength == 0 || mOnset == 0) { ofSetColor(100, 100, 150); } else { ofSetColor(150, 150, 255); } break; default: ofSetColor(255, 255, 255); break; } ofSetCircleResolution(40); ofNoFill(); ofCircle(100, 100, GetRadius()); ofFill(); for (int i = 0; i < (int)mLength; ++i) { float pos = float(i) / (int)mLength - mOffset; ofVec2f p1 = PolToCar(pos, GetRadius() - 3); ofVec2f p2 = PolToCar(pos, GetRadius() + 3); ofLine(p1.x + 100, p1.y + 100, p2.x + 100, p2.y + 100); ofVec2f point = PolToCar(pos, GetRadius()); if (mSteps[i] > 0) ofCircle(100 + point.x, 100 + point.y, 3 + 6 * mSteps[i]); if (i == mHighlightStepIdx) { ofPushStyle(); ofSetColor(255, 255, 255, 100); ofSetLineWidth(.5f); ofNoFill(); ofCircle(100 + point.x, 100 + point.y, 3 + 6); ofPopStyle(); } } ofPopStyle(); mLengthSlider->Draw(); mOnsetSlider->Draw(); mRotationSlider->Draw(); mOffsetSlider->Draw(); mNoteSelector->Draw(); } int EuclideanSequencerRing::GetStepIndex(int x, int y, float& radiusOut) { // use tempLength to avoid div by zero: mLength may change after check == 0 int tempLength = (int)mLength; if (tempLength == 0) { return -1; } ofVec2f polar = CarToPol(x - 100, y - 100); float pos = FloatWrap(polar.x + mOffset, 1); int idx = int(pos * mLength + .5f) % tempLength; ofVec2f stepPos = PolToCar(float(idx) / tempLength - mOffset, GetRadius()); if (ofDistSquared(x, y, stepPos.x + 100, stepPos.y + 100) < 7 * 7) { radiusOut = polar.y; return idx; } return -1; } void EuclideanSequencerRing::OnClicked(float x, float y, bool right) { if (right) return; mCurrentlyClickedStepIdx = GetStepIndex(x, y, mLastMouseRadius); if (mCurrentlyClickedStepIdx != -1) { if (mSteps[mCurrentlyClickedStepIdx]) mSteps[mCurrentlyClickedStepIdx] = 0; else mSteps[mCurrentlyClickedStepIdx] = .5f; } } void EuclideanSequencerRing::MouseReleased() { mCurrentlyClickedStepIdx = -1; } void EuclideanSequencerRing::MouseMoved(float x, float y) { if (mCurrentlyClickedStepIdx != -1) { ofVec2f polar = CarToPol(x - 100, y - 100); float change = (polar.y - mLastMouseRadius) / 50.0f; mSteps[mCurrentlyClickedStepIdx] = ofClamp(mSteps[mCurrentlyClickedStepIdx] + change, 0, 1); mLastMouseRadius = polar.y; } else { float radius; mHighlightStepIdx = GetStepIndex(x, y, radius); } } void EuclideanSequencerRing::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { bool forceUpdate{ false }; if (slider == mRotationSlider) { // Do not generate a new GetEuclideanRhythm, but rotate mSteps // This way, manually modified onsets will remain // check min and max value to handle manual slider value edits mRotation = MAX(mRotation, EUCLIDEAN_ROTATION_MIN); mRotation = MIN(mRotation, EUCLIDEAN_ROTATION_MAX); int tempLength = (int)mLength; // Nothing to rotate, return if (tempLength == 0 || mOnset == 0) return; // use tempLength to avoid divide by zero later for: % mLength std::array<float, EUCLIDEAN_SEQUENCER_MAX_STEPS> mTempSteps{}; int rotOffset = (int)(mRotation - oldVal) % tempLength; if (rotOffset == 0) { // This is a strange situation: // IntSliderUpdated event was triggered for mRotationSlider, // but no difference between newVal and oldVal. // This occurs when Randomize button is used to update the Rotation // So force a full recalculation: forceUpdate = true; } else { // Regular rotation, modified onsets keep their status // Save current mSteps mTempSteps = mSteps; // Fill mSteps with old data using rotOffset for (int i = 0; i < tempLength; i++) { mSteps[i] = mTempSteps[(int)(i + rotOffset + tempLength) % tempLength]; // + tempLength to avoid negative mod results } } } if (slider == mLengthSlider || slider == mOnsetSlider || forceUpdate) { // mLength = static_cast<int>(mLengthSlider->GetValue()); // mOnset = static_cast<int>(mOnsetSlider->GetValue()); // mRotation = static_cast<int>(mRotationSlider->GetValue()); // check min and max value to handle manual slider value edits mLength = CLAMP(mLength, 0, EUCLIDEAN_SEQUENCER_MAX_STEPS); mOnset = CLAMP(mOnset, 0, EUCLIDEAN_SEQUENCER_MAX_STEPS); mOnsetSlider->SetExtents(0, (int)mLength); // Clear all steps mSteps.fill(0); // Nothing to do, return empty mSteps if (mLength == 0 || mOnset == 0) { return; } // Get Euclidean Rhythm, returns a string of 1's and 0's std::string sEuclid = GetEuclideanRhythm(mOnset, mLength, mRotation); // Fill mSteps for (int i = 0; i < mLength; i++) { if (sEuclid[i] == '1') { mSteps[i] = .5f; } else { mSteps[i] = 0; } } } } void EuclideanSequencerRing::OnTransportAdvanced(float amount) { PROFILER(EuclideanSequencerRing); TransportListenerInfo info(nullptr, kInterval_CustomDivisor, OffsetInfo(mOffset, false), false); info.mCustomDivisor = mLength + (mLength == 1); // +1 if mLength(Steps) == 1: fixes not playing onset 1 when mLength = 1: force oldStep <> newStep double remainderMs; const int oldStep = TheTransport->GetQuantized(NextBufferTime(true) - gBufferSizeMs, &info); const int newStep = TheTransport->GetQuantized(NextBufferTime(true), &info, &remainderMs); if (oldStep != newStep && mSteps[newStep] > 0) { const double time = NextBufferTime(true) - remainderMs; mOwner->PlayNoteOutput(time, mPitch, mSteps[newStep] * 127, -1); if (mOwner->PlayShortNotes()) { mOwner->PlayNoteOutput(time + TheTransport->GetDuration(kInterval_16n), mPitch, 0, -1); } else { mOwner->PlayNoteOutput(time + 32.0 / mLength * TheTransport->GetDuration(kInterval_32n), mPitch, 0, -1); } mDestinationCable->PlayNoteOutput(time, mPitch, mSteps[newStep] * 127, -1); if (mOwner->PlayShortNotes()) { mDestinationCable->PlayNoteOutput(time + TheTransport->GetDuration(kInterval_16n), mPitch, 0, -1); } else { mDestinationCable->PlayNoteOutput(time + 32.0 / mLength * TheTransport->GetDuration(kInterval_32n), mPitch, 0, -1); } } } void EuclideanSequencerRing::SaveState(FileStreamOut& out) { out << (int)mSteps.size(); for (size_t i = 0; i < mSteps.size(); ++i) out << mSteps[i]; } void EuclideanSequencerRing::LoadState(FileStreamIn& in) { int numSteps; in >> numSteps; for (size_t i = 0; i < mSteps.size() && i < numSteps; ++i) in >> mSteps[i]; } void EuclideanSequencerRing::SetSteps(int steps) { mLength = steps; mLengthSlider->SetValue(mLength, gTime, true); } int EuclideanSequencerRing::GetSteps() { return mLength; } void EuclideanSequencerRing::SetOnsets(int onsets) { mOnset = onsets; mOnsetSlider->SetValue(mOnset, gTime, true); } void EuclideanSequencerRing::SetRotation(int rotation) { mRotation = rotation; mRotationSlider->SetValue(mRotation, gTime, true); } void EuclideanSequencerRing::SetOffset(float offset) { mOffset = offset; mOffsetSlider->SetValue(mOffset, gTime, true); } void EuclideanSequencerRing::SetPitch(int pitch) { mPitch = pitch; mNoteSelector->SetValue(pitch, gTime, true); } int EuclideanSequencerRing::GetPitch() { return mPitch; } std::string EuclideanSequencerRing::GetEuclideanRhythm(int pulses, int steps, int rotation) { std::vector<char> rhythm(steps, '0'); // Vector to store the rhythm int bucket = 0; // count steps until the next pulse bool hasPulse = false; // check if vector has a pulse // return rhythm filled with '0' if (pulses == 0 || steps == 0) { return std::string(rhythm.begin(), rhythm.end()); } // Fill Euclidean rhythm with steps using the Euclidean music algorithm based on // Computer Music Design Team // path_to_url // and // Boogie Automaticland - bohara2000 // path_to_url // for (int i = 0; i < steps; i++) { bucket += pulses; if (bucket >= steps) { bucket -= steps; rhythm[i] = '1'; hasPulse = true; } } // Rotate until pulse on first step while (hasPulse && rhythm[0] != '1') { std::rotate(rhythm.begin(), rhythm.begin() + 1, rhythm.end()); } // Rotate the rhythm according to rotation parameter // Rotate 1 char at a time, to avoid overflows if (rotation >= 0) { for (int i = 0; i < rotation; i++) { std::rotate(rhythm.begin(), rhythm.begin() + 1, rhythm.end()); } } else { for (int i = 0; i < -rotation; i++) { std::rotate(rhythm.rbegin(), rhythm.rbegin() + 1, rhythm.rend()); } } return std::string(rhythm.begin(), rhythm.end()); } ```
/content/code_sandbox/Source/EuclideanSequencer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
9,367
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== NotePanner.cpp Created: 24 Mar 2018 8:18:20pm Author: Ryan Challinor ============================================================================== */ #include "NotePanner.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" NotePanner::NotePanner() { } void NotePanner::CreateUIControls() { IDrawableModule::CreateUIControls(); mPanSlider = new FloatSlider(this, "pan", 4, 2, 100, 15, &mPan, -1, 1); } void NotePanner::DrawModule() { if (Minimized() || IsVisible() == false) return; mPanSlider->Draw(); } void NotePanner::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled && velocity > 0) { ComputeSliders(0); modulation.pan = mPan; } PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void NotePanner::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void NotePanner::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/NotePanner.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
394
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ // // DrumPlayer.cpp // modularSynth // // Created by Ryan Challinor on 11/25/12. // // #include "DrumPlayer.h" #include "OpenFrameworksPort.h" #include "SynthGlobals.h" #include "Transport.h" #include "ModularSynth.h" #include "MidiController.h" #include "Profiler.h" #include "UIControlMacros.h" #include "SamplePlayer.h" using namespace juce; DrumPlayer::DrumPlayer() : mOutputBuffer(gBufferSize) , mNoteInputBuffer(this) { ReadKits(); strcpy(mNewKitName, "new"); } void DrumPlayer::Init() { IDrawableModule::Init(); TheTransport->AddListener(this, mQuantizeInterval, OffsetInfo(0, true), false); } DrumPlayer::~DrumPlayer() { TheTransport->RemoveListener(this); for (int i = 0; i < mIndividualOutputs.size(); ++i) delete mIndividualOutputs[i]; } void DrumPlayer::CreateUIControls() { IDrawableModule::CreateUIControls(); mVolSlider = new FloatSlider(this, "vol", 4, 2, 100, 15, &mVolume, 0, 2); mSpeedSlider = new FloatSlider(this, "speed", 4, 18, 100, 15, &mSpeed, 0.2f, 3); mSpeedRandomizationSlider = new FloatSlider(this, "speed rnd", 4, 34, 100, 15, &mSpeedRandomization, 0, .2f); mKitSelector = new DropdownList(this, "kit", 4, 50, &mLoadedKit); mEditCheckbox = new Checkbox(this, "edit", 73, 52, &mEditMode); //mSaveButton = new ClickButton(this,"save current",200,22); //mNewKitButton = new ClickButton(this,"new kit", 200, 4); //mNewKitNameEntry = new TextEntry(this,"kitname",200, 40,7,mNewKitName); mAuditionSlider = new FloatSlider(this, "aud", 140, 50, 40, 15, &mAuditionInc, -1, 1, 0); mMonoCheckbox = new Checkbox(this, "mono", mVolSlider, kAnchor_Right_Padded, &mMonoOutput); mShuffleButton = new ClickButton(this, "shuffle", 140, 34); mGridControlTarget = new GridControlTarget(this, "grid", 4, 50); mQuantizeIntervalSelector = new DropdownList(this, "quantize", 200, 2, (int*)(&mQuantizeInterval)); mNoteRepeatCheckbox = new Checkbox(this, "repeat", mQuantizeIntervalSelector, kAnchor_Below, &mNoteRepeat); mFullVelocityCheckbox = new Checkbox(this, "full vel", mNoteRepeatCheckbox, kAnchor_Below, &mFullVelocity); mSingleVoiceCheckbox = new Checkbox(this, "single voice", mFullVelocityCheckbox, kAnchor_Below, &mSingleVoice); mKitSelector->SetShowing(false); //TODO(Ryan) replace "kits" concept with a better form of serialization mQuantizeIntervalSelector->AddLabel("none", kInterval_None); mQuantizeIntervalSelector->AddLabel("4n", kInterval_4n); mQuantizeIntervalSelector->AddLabel("4nt", kInterval_4nt); mQuantizeIntervalSelector->AddLabel("8n", kInterval_8n); mQuantizeIntervalSelector->AddLabel("8nt", kInterval_8nt); mQuantizeIntervalSelector->AddLabel("16n", kInterval_16n); mQuantizeIntervalSelector->AddLabel("16nt", kInterval_16nt); mQuantizeIntervalSelector->AddLabel("32n", kInterval_32n); mQuantizeIntervalSelector->AddLabel("64n", kInterval_64n); for (int i = 0; i < NUM_DRUM_HITS; ++i) mDrumHits[i].CreateUIControls(this, i); for (int i = 0; i < mKits.size(); ++i) mKitSelector->AddLabel(mKits[i].mName.c_str(), i); UpdateVisibleControls(); GetPatchCableSource()->SetManualSide(PatchCableSource::Side::kBottom); mSpeedRandomizationSlider->SetMode(FloatSlider::kSquare); } void DrumPlayer::DrumHit::CreateUIControls(DrumPlayer* owner, int index) { UIBLOCK(310, 37); #undef UIBLOCK_OWNER #define UIBLOCK_OWNER owner //change owner FLOATSLIDER_DIGITS(mVolSlider, ("vol " + ofToString(index)).c_str(), &mVol, 0, 2, 2); FLOATSLIDER_DIGITS(mSpeedSlider, ("speed " + ofToString(index)).c_str(), &mSpeed, .2f, 3, 2); FLOATSLIDER(mPanSlider, ("pan " + ofToString(index)).c_str(), &mPan, -1, 1); INTSLIDER(mWidenSlider, ("widen " + ofToString(index)).c_str(), &mWiden, -150, 150); FLOATSLIDER(mStartOffsetSlider, ("start " + ofToString(index)).c_str(), &mStartOffset, 0, 1); CHECKBOX(mIndividualOutputCheckbox, ("single out " + ofToString(index)).c_str(), &mHasIndividualOutput); INTSLIDER(mLinkIdSlider, ("linkid " + ofToString(index)).c_str(), &mLinkId, -1, 5); CHECKBOX(mUseEnvelopeCheckbox, ("envelope " + ofToString(index)).c_str(), &mUseEnvelope); FLOATSLIDER(mEnvelopeLengthSlider, ("view ms " + ofToString(index)).c_str(), &mEnvelopeLength, 10, 2000); DROPDOWN(mHitCategoryDropdown, ("hitcategory" + ofToString(index)).c_str(), &mHitCategoryIndex, 100); UICONTROL_CUSTOM(mEnvelopeDisplay, new ADSRDisplay(UICONTROL_BASICS(("envelopedisplay " + ofToString(index)).c_str()), 135, 100, &mEnvelope)); BUTTON_STYLE(mGrabSampleButton, ("grab " + ofToString(index)).c_str(), ButtonDisplayStyle::kGrabSample); ENDUIBLOCK0(); #undef UIBLOCK_OWNER #define UIBLOCK_OWNER this //reset int x = 5 + (index % 4) * 70; int y = 70 + (3 - (index / 4)) * 70; mTestButton = new ClickButton(owner, ("test " + ofToString(index)).c_str(), x + 5, y + 38, ButtonDisplayStyle::kPlay); mPrevButton = new ClickButton(owner, ("prev " + ofToString(index)).c_str(), x + 27, y + 38, ButtonDisplayStyle::kArrowLeft); mNextButton = new ClickButton(owner, ("next " + ofToString(index)).c_str(), x + 48, y + 38, ButtonDisplayStyle::kArrowRight); mRandomButton = new ClickButton(owner, ("random " + ofToString(index)).c_str(), x + 5, y + 53); UpdateHitDirectoryDropdown(); mOwner = owner; } namespace { static std::list<std::string> sHitDirectories; } //static void DrumPlayer::SetUpHitDirectories() { sHitDirectories.clear(); File parentDirectory(ofToDataPath("drums")); Array<File> hitDirs; parentDirectory.findChildFiles(hitDirs, File::findDirectories, true); for (auto dir : hitDirs) { Array<File> filesInDir; dir.findChildFiles(filesInDir, File::findFiles, false); if (filesInDir.size() > 0) sHitDirectories.push_back(dir.getRelativePathFrom(parentDirectory).replaceCharacter('\\', '/').toStdString()); } } void DrumPlayer::DrumHit::UpdateHitDirectoryDropdown() { mHitCategoryDropdown->Clear(); for (auto dir : sHitDirectories) mHitCategoryDropdown->AddLabel(dir, mHitCategoryDropdown->GetNumValues()); mHitCategoryIndex = -1; for (int i = 0; i < mHitCategoryDropdown->GetNumValues(); ++i) { if (mHitCategory == mHitCategoryDropdown->GetLabel(i)) mHitCategoryIndex = i; } } void DrumPlayer::Poll() { if (mNeedSetup) SetUpNewDrumPlayer(); UpdateLights(); } void DrumPlayer::SetUpNewDrumPlayer() { ofxJSONElement root; root.open(ofToDataPath("drums/drums.json")); std::array<std::string, NUM_DRUM_HITS> categories = { "808kit/Kick", "808kit/Snare", "808kit/HatClosed", "808kit/HatOpen", "808kit/Kick", "808kit/Clap", "808kit/HatClosed", "808kit/Perc", "808kit/Kick", "808kit/Snare", "808kit/HatClosed", "808kit/HatOpen", "808kit/Kick", "808kit/Clap", "808kit/HatClosed", "808kit/Perc" }; for (auto i = 0; i < root["directories"].size() && i < categories.size(); ++i) categories[i] = root["directories"][i].asString(); for (int i = 0; i < NUM_DRUM_HITS; ++i) { std::string category = categories[i % categories.size()]; File dir(ofToDataPath("drums/" + category)); if (dir.exists()) { mDrumHits[i].mHitCategory = category; mDrumHits[i].UpdateHitDirectoryDropdown(); } mDrumHits[i].LoadRandomSample(); if (i == 2 || i == 3) mDrumHits[i].mLinkId = 0; } mNeedSetup = false; } void DrumPlayer::UpdateVisibleControls() { for (int i = 0; i < NUM_DRUM_HITS; ++i) mDrumHits[i].SetUIControlsShowing(i == mSelectedHitIdx && mEditMode); } void DrumPlayer::DrumHit::SetUIControlsShowing(bool showing) { mVolSlider->SetShowing(showing); mSpeedSlider->SetShowing(showing); mUseEnvelopeCheckbox->SetShowing(showing); mEnvelopeDisplay->SetShowing(showing); mPanSlider->SetShowing(showing && mOwner->mMonoOutput == false); mWidenSlider->SetShowing(showing && mOwner->mMonoOutput == false); mStartOffsetSlider->SetShowing(showing); mIndividualOutputCheckbox->SetShowing(showing); mLinkIdSlider->SetShowing(showing); mEnvelopeLengthSlider->SetShowing(showing); mHitCategoryDropdown->SetShowing(showing); mGrabSampleButton->SetShowing(showing); } void DrumPlayer::LoadKit(int kit) { if (kit >= 0 && kit < mKits.size()) { // Maschine samples are in /Users/Shared/Maschine Library/Samples mLoadedKit = kit; LoadSampleLock(); for (int i = 0; i < NUM_DRUM_HITS; ++i) { mDrumHits[i].mSample.Read(mKits[kit].mSampleFiles[i].c_str()); mDrumHits[i].mLinkId = mKits[kit].mLinkIds[i]; mDrumHits[i].mVol = mKits[kit].mVols[i]; mDrumHits[i].mSpeed = mKits[kit].mSpeeds[i]; mDrumHits[i].mPan = mKits[kit].mPans[i]; mDrumHits[i].mEnvelopeLength = mDrumHits[i].mSample.LengthInSamples() * gInvSampleRateMs; } LoadSampleUnlock(); } } void DrumPlayer::LoadSampleLock() { mLoadSamplesAudioMutex.lock(); mLoadSamplesDrawMutex.lock(); mLoadingSamples = true; } void DrumPlayer::LoadSampleUnlock() { mLoadingSamples = false; mLoadSamplesDrawMutex.unlock(); mLoadSamplesAudioMutex.unlock(); } void DrumPlayer::Process(double time) { PROFILER(DrumPlayer); if (!mEnabled) return; mNoteInputBuffer.Process(time); int numChannels = mMonoOutput ? 1 : 2; ComputeSliders(0); SyncOutputBuffer(numChannels); for (auto output : mIndividualOutputs) output->mVizBuffer->SetNumChannels(numChannels); mOutputBuffer.SetNumActiveChannels(numChannels); int bufferSize = gBufferSize; float volSq = mVolume * mVolume * .5f; mOutputBuffer.Clear(); if (!mLoadingSamples) { mLoadSamplesAudioMutex.lock(); mLoadingSamples = true; for (int i = 0; i < NUM_DRUM_HITS; ++i) { int individualOutputIndex = GetIndividualOutputIndex(i); gWorkChannelBuffer.SetNumActiveChannels(numChannels); if (mDrumHits[i].Process(time, mSpeed, volSq, &gWorkChannelBuffer, bufferSize)) { for (int ch = 0; ch < numChannels; ++ch) { if (individualOutputIndex != -1) { int targetIndex = individualOutputIndex + 1; IAudioReceiver* targetOut = GetTarget(targetIndex); if (targetOut) Add(targetOut->GetBuffer()->GetChannel(ch), gWorkChannelBuffer.GetChannel(ch), bufferSize); mIndividualOutputs[individualOutputIndex]->mVizBuffer->WriteChunk(gWorkChannelBuffer.GetChannel(ch), bufferSize, ch); } else { Add(mOutputBuffer.GetChannel(ch), gWorkChannelBuffer.GetChannel(ch), bufferSize); } } } else { if (individualOutputIndex != -1) { for (int ch = 0; ch < numChannels; ++ch) mIndividualOutputs[individualOutputIndex]->mVizBuffer->WriteChunk(gZeroBuffer, bufferSize, ch); } } } mLoadingSamples = false; mLoadSamplesAudioMutex.unlock(); } IAudioReceiver* target = GetTarget(); for (int ch = 0; ch < numChannels; ++ch) { GetVizBuffer()->WriteChunk(mOutputBuffer.GetChannel(ch), bufferSize, ch); if (target) Add(target->GetBuffer()->GetChannel(ch), mOutputBuffer.GetChannel(ch), bufferSize); } } void DrumPlayer::DrumHit::StartPlayhead(double time, float startOffsetPercent, float velocity) { mCurrentPlayheadIndex = (mCurrentPlayheadIndex + 1) % mPlayheads.size(); for (size_t i = 0; i < mPlayheads.size(); ++i) { if (i == mCurrentPlayheadIndex) { mPlayheads[i].mStartTime = time; mPlayheads[i].mCutOffTime = -1; mPlayheads[i].mOffset = startOffsetPercent * mSample.LengthInSamples(); mPlayheads[i].mEnvelopeTime = 0; mPlayheads[i].mEnvelopeScale = ofLerp(.2f, 1, velocity); mPlayheads[i].mSpeedTweak = ofRandom(1 - mOwner->mSpeedRandomization, 1 + mOwner->mSpeedRandomization); } else { mPlayheads[i].mCutOffTime = time; } } } void DrumPlayer::DrumHit::StopLinked(double time) { for (size_t i = 0; i < mPlayheads.size(); ++i) { if (mPlayheads[i].mCutOffTime == -1) mPlayheads[i].mCutOffTime = time; } } float DrumPlayer::DrumHit::GetPlayProgress(double time) { int playheadIdx = -1; double startTime = -1; for (int i = 0; i < (int)mPlayheads.size(); ++i) { if (mPlayheads[i].mStartTime <= time && mPlayheads[i].mStartTime > startTime) { startTime = mPlayheads[i].mStartTime; playheadIdx = i; } } if (startTime != -1 && mSample.Data() != nullptr) return mPlayheads[playheadIdx].mOffset / mSample.LengthInSamples(); return 1; } bool DrumPlayer::DrumHit::Process(double time, float speed, float vol, ChannelBuffer* out, int bufferSize) { ChannelBuffer* sampleData = mSample.Data(); speed *= mSpeed; for (int i = 0; i < bufferSize; ++i) { float sampleSpeed = speed; if (mPitchBend != nullptr) sampleSpeed *= ofMap(mPitchBend->GetValue(i), -.5f, .5f, 0, 2); for (int ch = 0; ch < out->NumActiveChannels(); ++ch) gWorkBuffer[ch] = 0; for (size_t playhead = 0; playhead < mPlayheads.size(); ++playhead) { if (mPlayheads[playhead].mStartTime != -1 && time > mPlayheads[playhead].mStartTime && mPlayheads[playhead].mOffset < mSample.LengthInSamples()) { for (int ch = 0; ch < out->NumActiveChannels(); ++ch) { int dataChannel = MIN(ch, sampleData->NumActiveChannels() - 1); float sample = GetInterpolatedSample(mPlayheads[playhead].mOffset, sampleData->GetChannel(dataChannel), mSample.LengthInSamples()); sample *= mVelocity * vol * mVol * mVol; if (mUseEnvelope) sample *= mEnvelope.Value(mPlayheads[playhead].mEnvelopeTime); if (mPlayheads[playhead].mCutOffTime != -1 && time > mPlayheads[playhead].mCutOffTime) { float fade = ofMap(time - mPlayheads[playhead].mCutOffTime, 0, .25f, 1, 0, K(clamp)); sample *= fade; if (fade == 0) mPlayheads[playhead].mStartTime = -1; } gWorkBuffer[ch] += sample; } mPlayheads[playhead].mOffset += sampleSpeed * mPlayheads[playhead].mSpeedTweak * mSample.GetSampleRateRatio(); mPlayheads[playhead].mEnvelopeTime += gInvSampleRateMs / mPlayheads[playhead].mEnvelopeScale; mSamplesRemainingToProcess = bufferSize + abs(mWiden); } } int secondChannel = out->NumActiveChannels() == 1 ? 0 : 1; float left = gWorkBuffer[0]; float right = gWorkBuffer[secondChannel]; if (mPan + mPanInput != 0 && mOwner->mMonoOutput == false) { out->GetChannel(0)[i] = left * ofMap(mPan + mPanInput, 0, 1, 1, 0, true) + right * ofMap(mPan + mPanInput, -1, 0, 1, 0, true); out->GetChannel(secondChannel)[i] = right * ofMap(mPan + mPanInput, -1, 0, 0, 1, true) + left * ofMap(mPan + mPanInput, 0, 1, 0, 1, true); } else { out->GetChannel(0)[i] = left; if (secondChannel == 1) out->GetChannel(secondChannel)[i] = right; } time += gInvSampleRateMs; } if (mSamplesRemainingToProcess > 0) { if (abs(mWiden) > 0 && mOwner->mMonoOutput == false) { mWidenerBuffer.SetNumChannels(2); for (int ch = 0; ch < out->NumActiveChannels(); ++ch) mWidenerBuffer.WriteChunk(out->GetChannel(ch), bufferSize, ch); if (mWiden < 0) mWidenerBuffer.ReadChunk(out->GetChannel(1), bufferSize, abs(mWiden), 1); else mWidenerBuffer.ReadChunk(out->GetChannel(0), bufferSize, abs(mWiden), 0); } mSamplesRemainingToProcess -= bufferSize; return true; } return false; } int DrumPlayer::GetIndividualOutputIndex(int hitIndex) { for (int i = 0; i < mIndividualOutputs.size(); ++i) { if (mIndividualOutputs[i]->mHitIndex == hitIndex) return i; } return -1; } void DrumPlayer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (!mEnabled) return; if (!NoteInputBuffer::IsTimeWithinFrame(time)) { mNoteInputBuffer.QueueNote(time, pitch, velocity, voiceIdx, modulation); return; } if (velocity > 0 && mFullVelocity) velocity = 127; pitch %= 24; if (pitch >= 0 && pitch < NUM_DRUM_HITS) { if (velocity > 0) { //reset all linked drum hits int playingId = mDrumHits[pitch].mLinkId; if (playingId != -1 || mSingleVoice) { for (int i = 0; i < NUM_DRUM_HITS; ++i) { if (i != pitch && mDrumHits[i].mLinkId == playingId) mDrumHits[i].StopLinked(time); } } //play this one mDrumHits[pitch].mVelocity = velocity / 127.0f; mDrumHits[pitch].mPanInput = modulation.pan; mDrumHits[pitch].mPitchBend = modulation.pitchBend; float startOffsetPercent = mDrumHits[pitch].mStartOffset; if (modulation.modWheel != nullptr) startOffsetPercent += MAX((modulation.modWheel->GetValue(0) - ModulationParameters::kDefaultModWheel) * 2, 0); mDrumHits[pitch].StartPlayhead(time, startOffsetPercent, velocity / 127.0f); } } } bool DrumPlayer::OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue) { if (type == kMidiMessage_Note) { if (controlIndex >= 36 && controlIndex <= 99) { int gridIndex = controlIndex - 36; int x = gridIndex % 8; int y = gridIndex / 8; if (x < 4 && y < 4) { OnGridButton(x, 3 - y, midiValue / 127.0f, nullptr); } else if (x < 4 && midiValue > 0) { int index = x + (y - 4) * 4; if (index == mPush2SelectedHitIdx) { mPush2SelectedHitIdx = -1; } else { mPush2SelectedHitIdx = index; mSelectedHitIdx = index; UpdateVisibleControls(); } } return true; } } return false; } void DrumPlayer::UpdatePush2Leds(Push2Control* push2) { for (int x = 0; x < 8; ++x) { for (int y = 0; y < 8; ++y) { int pushColor = 0; int pushColorBlink = -1; if (x < 4 && y < 4) { int index = x + y * 4; if (mDrumHits[index].GetPlayProgress(gTime) < 1) pushColor = 2; else if (mDrumHits[index].mButtonHeldVelocity > 0) pushColor = 66; else pushColor = 1; } else if (x < 4) { int index = x + (y - 4) * 4; if (index == mPush2SelectedHitIdx) { pushColor = 126; pushColorBlink = 86; } else { pushColor = 86; } } push2->SetLed(kMidiMessage_Note, x + y * 8 + 36, pushColor, pushColorBlink); } } } void DrumPlayer::GetPush2OverrideControls(std::vector<IUIControl*>& controls) const { if (mPush2SelectedHitIdx != -1) { int i = mPush2SelectedHitIdx; controls.push_back(mDrumHits[i].mVolSlider); controls.push_back(mDrumHits[i].mSpeedSlider); if (mDrumHits[i].mUseEnvelope) { controls.push_back(mDrumHits[i].mEnvelopeDisplay); controls.push_back(mDrumHits[i].mEnvelopeDisplay->GetASlider()); controls.push_back(mDrumHits[i].mEnvelopeDisplay->GetDSlider()); controls.push_back(mDrumHits[i].mEnvelopeDisplay->GetSSlider()); controls.push_back(mDrumHits[i].mEnvelopeDisplay->GetRSlider()); } controls.push_back(mDrumHits[i].mTestButton); controls.push_back(mDrumHits[i].mPrevButton); controls.push_back(mDrumHits[i].mNextButton); controls.push_back(mDrumHits[i].mRandomButton); controls.push_back(mDrumHits[i].mUseEnvelopeCheckbox); controls.push_back(mDrumHits[i].mPanSlider); controls.push_back(mDrumHits[i].mWidenSlider); controls.push_back(mDrumHits[i].mLinkIdSlider); controls.push_back(mDrumHits[i].mHitCategoryDropdown); controls.push_back(mDrumHits[i].mStartOffsetSlider); } } void DrumPlayer::FilesDropped(std::vector<std::string> files, int x, int y) { x -= 5; y -= 70; if (x < 0 || y < 0) return; x /= 70; y /= 70; File auditionDir(files[0]); if (auditionDir.isDirectory()) { mAuditionDir = files[0]; if (x < 4 && y < 4) mSelectedHitIdx = GetAssociatedSampleIndex(x, y); mAuditionSampleIdx = -1; } else { auditionDir = ""; if (x < 4 && y < 4) { for (int i = 0; i < files.size(); ++i) { int sampleIdx = GetAssociatedSampleIndex(x + i % 4, y + i / 4); if (sampleIdx != -1) { LoadSampleLock(); mDrumHits[sampleIdx].mSample.Read(files[i].c_str()); LoadSampleUnlock(); mDrumHits[sampleIdx].mLinkId = -1; mDrumHits[sampleIdx].mVol = 1; mDrumHits[sampleIdx].mSpeed = 1; mDrumHits[sampleIdx].mPan = 0; mDrumHits[sampleIdx].mEnvelopeLength = mDrumHits[sampleIdx].mSample.LengthInSamples() * gInvSampleRateMs; mSelectedHitIdx = sampleIdx; UpdateVisibleControls(); } } } } } void DrumPlayer::SampleDropped(int x, int y, Sample* sample) { assert(sample); int numSamples = sample->LengthInSamples(); if (numSamples <= 0) return; x -= 5; y -= 70; if (x < 0 || y < 0) return; x /= 70; y /= 70; mAuditionDir = ""; if (x < 4 && y < 4) { int sampleIdx = GetAssociatedSampleIndex(x, y); if (sampleIdx != -1) { SetHitSample(sampleIdx, sample); mSelectedHitIdx = sampleIdx; UpdateVisibleControls(); } } } void DrumPlayer::ImportSampleCuePoint(SamplePlayer* player, int sourceCueIndex, int destHitIndex) { if (player != nullptr) { ChannelBuffer* data = player->GetCueSampleData(sourceCueIndex); Sample sample; sample.Create(data); SetHitSample(destHitIndex, &sample); delete data; } } void DrumPlayer::SetHitSample(int sampleIndex, Sample* sample) { LoadSampleLock(); mDrumHits[sampleIndex].mSample.CopyFrom(sample); LoadSampleUnlock(); mDrumHits[sampleIndex].mLinkId = -1; mDrumHits[sampleIndex].mVol = 1; mDrumHits[sampleIndex].mSpeed = 1; mDrumHits[sampleIndex].mPan = 0; mDrumHits[sampleIndex].mEnvelopeLength = mDrumHits[sampleIndex].mSample.LengthInSamples() * gInvSampleRateMs; } void DrumPlayer::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); if (right) return; if (!mEditMode) return; x -= 5; y -= 70; if (x < 0 || y < 0) return; x /= 70; y /= 70; if (x < 4 && y < 4) { int sampleIdx = GetAssociatedSampleIndex(x, y); if (sampleIdx != -1) { mSelectedHitIdx = sampleIdx; mAuditionDir = ofToDataPath("drums/" + mDrumHits[sampleIdx].mHitCategory); UpdateVisibleControls(); } } } void DrumPlayer::OnGridButton(int x, int y, float velocity, IGridController* grid) { int sampleIdx = GetAssociatedSampleIndex(x, y); if (sampleIdx >= 0) { if (velocity > 0 && mQuantizeInterval == kInterval_None) { PlayNote(NextBufferTime(false), sampleIdx, velocity * 127); } else { if (sampleIdx < mDrumHits.size()) { if (velocity > 0) mDrumHits[sampleIdx].mButtonHeldVelocity = velocity * 127; else if (mNoteRepeat) mDrumHits[sampleIdx].mButtonHeldVelocity = 0; } } } } void DrumPlayer::OnTimeEvent(double time) { for (int i = 0; i < (int)mDrumHits.size(); ++i) { if (mDrumHits[i].mButtonHeldVelocity > 0) { PlayNote(time, i, mDrumHits[i].mButtonHeldVelocity); if (!mNoteRepeat) mDrumHits[i].mButtonHeldVelocity = 0; } } } void DrumPlayer::DrawModule() { if (Minimized() || IsVisible() == false) return; mVolSlider->Draw(); mSpeedSlider->Draw(); mSpeedRandomizationSlider->Draw(); mKitSelector->Draw(); mEditCheckbox->Draw(); mGridControlTarget->Draw(); if (mEditMode) { ofPushStyle(); ofFill(); ofSetColor(50, 50, 50, gModuleDrawAlpha); ofRect(300, 5, 145, 360); ofPopStyle(); mMonoCheckbox->Draw(); //mSaveButton->Draw(); //mNewKitButton->Draw(); //mNewKitNameEntry->Draw(); mAuditionSlider->Draw(); mShuffleButton->Draw(); mQuantizeIntervalSelector->Draw(); mNoteRepeatCheckbox->Draw(); mFullVelocityCheckbox->Draw(); mSingleVoiceCheckbox->Draw(); ofPushMatrix(); ofPushStyle(); ofTranslate(5, 70); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { int sampleIdx = GetAssociatedSampleIndex(i, j); ofSetColor(200, 100, 0, gModuleDrawAlpha); ofNoFill(); ofRect(i * 70, j * 70, 70, 70); float alpha = sqrt(1 - mDrumHits[sampleIdx].GetPlayProgress(gTime)); ofSetColor(200, 100, 0, gModuleDrawAlpha * alpha); ofFill(); ofRect(i * 70, j * 70, 70, 70); if (sampleIdx == mSelectedHitIdx) { ofSetColor(0, 200, 255, gModuleDrawAlpha); ofNoFill(); ofRect(i * 70 + 1, j * 70 + 1, 68, 68); } ofSetColor(255, 255, 255, gModuleDrawAlpha); gFont.DrawStringWrap(mDrumHits[sampleIdx].mSample.Name(), 10, i * 70 + 5, j * 70 + 10, 60); } } ofPopStyle(); ofPopMatrix(); for (size_t i = 0; i < mDrumHits.size(); ++i) { mDrumHits[i].mTestButton->Draw(); mDrumHits[i].mPrevButton->Draw(); mDrumHits[i].mNextButton->Draw(); mDrumHits[i].mRandomButton->Draw(); } if (mSelectedHitIdx != -1) mDrumHits[mSelectedHitIdx].DrawUIControls(); } float moduleW, moduleH; GetDimensions(moduleW, moduleH); for (int i = 0; i < mIndividualOutputs.size(); ++i) { DrawTextNormal(ofToString(mIndividualOutputs[i]->mHitIndex), moduleW - 20, 10 + i * 12); mIndividualOutputs[i]->UpdatePosition(i); } } void DrumPlayer::UpdateLights() { const int kCols = 4; const int kRows = 4; for (int x = 0; x < kCols; ++x) { for (int y = 0; y < kRows; ++y) { int sampleIdx = GetAssociatedSampleIndex(x, y); Sample* sample = nullptr; if (sampleIdx != -1) sample = &(mDrumHits[sampleIdx].mSample); if (mGridControlTarget->GetGridController()) { if (mDrumHits[sampleIdx].GetPlayProgress(gTime) < .75f) mGridControlTarget->GetGridController()->SetLight(x, y, kGridColor3Bright); else if (sample) mGridControlTarget->GetGridController()->SetLight(x, y, kGridColor3Dim); else mGridControlTarget->GetGridController()->SetLight(x, y, kGridColorOff); } } } } void DrumPlayer::OnControllerPageSelected() { UpdateLights(); } void DrumPlayer::DrumHit::DrawUIControls() { float displayLength = mSample.LengthInSamples(); if (mUseEnvelope) displayLength = MIN(mEnvelopeLength * gSampleRateMs, displayLength); ofPushMatrix(); ofTranslate(mEnvelopeDisplay->GetPosition(true).x, mEnvelopeDisplay->GetPosition(true).y); if (!mOwner->mLoadingSamples) { mOwner->mLoadSamplesDrawMutex.lock(); DrawAudioBuffer(135, 100, mSample.Data(), mStartOffset * displayLength, displayLength, mSample.GetPlayPosition()); mOwner->mLoadSamplesDrawMutex.unlock(); } ofPopMatrix(); mVolSlider->Draw(); mSpeedSlider->Draw(); mLinkIdSlider->Draw(); mHitCategoryDropdown->Draw(); mPanSlider->Draw(); mWidenSlider->Draw(); mStartOffsetSlider->Draw(); mIndividualOutputCheckbox->Draw(); mUseEnvelopeCheckbox->Draw(); if (mUseEnvelope) { mEnvelopeLengthSlider->SetExtents(10, mSample.LengthInSamples() * gInvSampleRateMs); mEnvelopeLengthSlider->Draw(); mEnvelopeDisplay->SetMaxTime(mEnvelopeLength); mEnvelopeDisplay->SetOverrideDrawTime(mPlayheads[mCurrentPlayheadIndex].mEnvelopeTime); mEnvelopeDisplay->Draw(); } mGrabSampleButton->Draw(); } int DrumPlayer::GetAssociatedSampleIndex(int x, int y) { if (x > 3) { // For long rows, overflow the x value vertically // This makes e.g. 8 pads on a single row usable for // two drumplayer rows y = y + (x / 4); x = x % 4; } int pos = x + (3 - y) * 4; if (pos < 16) return pos; return -1; } void DrumPlayer::SaveKits() { ofxJSONElement root; Json::Value& kits = root["kits"]; for (int i = 0; i < mKits.size(); ++i) { Json::Value& kit = kits[i]; if (i == mLoadedKit) { for (int j = 0; j < NUM_DRUM_HITS; ++j) { //get relative path if it's in our data dir std::string path = mDrumHits[j].mSample.GetReadPath(); ofStringReplace(path, File(ofToDataPath("")).getFullPathName().toStdString(), ""); mKits[i].mSampleFiles[j] = path; mKits[i].mLinkIds[j] = mDrumHits[j].mLinkId; mKits[i].mVols[j] = mDrumHits[j].mVol; mKits[i].mSpeeds[j] = mDrumHits[j].mSpeed; mKits[i].mPans[j] = mDrumHits[j].mPan; } } for (int j = 0; j < NUM_DRUM_HITS; ++j) { kit["samples"][j]["sample"] = mKits[i].mSampleFiles[j]; kit["samples"][j]["linkid"] = mKits[i].mLinkIds[j]; kit["samples"][j]["vol"] = mKits[i].mVols[j]; kit["samples"][j]["speed"] = mKits[i].mSpeeds[j]; kit["samples"][j]["pan"] = mKits[i].mPans[j]; } kit["name"] = mKits[i].mName; } root.save(ofToDataPath("drums/drumkits.json"), true); } void DrumPlayer::ReadKits() { ofxJSONElement root; root.open(ofToDataPath("drums/drumkits.json")); Json::Value& kits = root["kits"]; mKits.resize(kits.size()); for (int i = 0; i < kits.size(); ++i) { try { Json::Value& kit = kits[i]; int numHitsInFile = kit["samples"].size(); for (int j = 0; j < NUM_DRUM_HITS && j < numHitsInFile; ++j) { mKits[i].mSampleFiles[j] = kit["samples"][j]["sample"].asString(); mKits[i].mLinkIds[j] = kit["samples"][j]["linkid"].asInt(); if (kit["samples"][j]["vol"].isNull() == false) mKits[i].mVols[j] = kit["samples"][j]["vol"].asDouble(); else mKits[i].mVols[j] = 1; if (kit["samples"][j]["speed"].isNull() == false) mKits[i].mSpeeds[j] = kit["samples"][j]["speed"].asDouble(); else mKits[i].mSpeeds[j] = 1; if (kit["samples"][j]["pan"].isNull() == false) mKits[i].mPans[j] = kit["samples"][j]["pan"].asDouble(); else mKits[i].mPans[j] = 0; } mKits[i].mName = kit["name"].asString(); } catch (Json::LogicError& e) { TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } } } void DrumPlayer::CreateKit() { StoredDrumKit kit; kit.mName = mNewKitName; for (int i = 0; i < NUM_DRUM_HITS; ++i) { kit.mSampleFiles[i] = mDrumHits[i].mSample.GetReadPath(); kit.mLinkIds[i] = mDrumHits[i].mLinkId; } mKits.push_back(kit); mLoadedKit = (int)mKits.size() - 1; mKitSelector->AddLabel(kit.mName.c_str(), mLoadedKit); } void DrumPlayer::ShuffleKit() { for (int j = 0; j < NUM_DRUM_HITS; ++j) { mDrumHits[j].LoadRandomSample(); mDrumHits[j].mVol *= ofRandom(.9f, 1.1f); mDrumHits[j].mSpeed *= ofRandom(.9f, 1.1f); mDrumHits[j].mPan = ofRandom(-1.0f, 1.0f); } } void DrumPlayer::GetModuleDimensions(float& width, float& height) { if (mEditMode) { width = 450; height = 370; } else { if (mIndividualOutputs.size() > 0) width = 150; else width = 110; height = 70; } } void DrumPlayer::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mAuditionSlider) { mAuditionSampleIdx += mAuditionInc > 0 ? -1 : 1; mAuditionInc = 0; File dir(mAuditionDir); Array<File> files; dir.findChildFiles(files, File::findFiles, false); if (files.size() > 0) { mAuditionSampleIdx = ofClamp(mAuditionSampleIdx, 0, files.size() - 1); std::string file = files[mAuditionSampleIdx].getFullPathName().toStdString(); if (mSelectedHitIdx >= 0 && mSelectedHitIdx < NUM_DRUM_HITS) { LoadSampleLock(); mDrumHits[mSelectedHitIdx].mSample.Read(file.c_str()); LoadSampleUnlock(); mDrumHits[mSelectedHitIdx].StartPlayhead(time, 0, 1); mDrumHits[mSelectedHitIdx].mVelocity = .5f; mDrumHits[mSelectedHitIdx].mEnvelopeLength = mDrumHits[mSelectedHitIdx].mSample.LengthInSamples() * gInvSampleRateMs; } } } } void DrumPlayer::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void DrumPlayer::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mKitSelector) LoadKit(mLoadedKit); for (int i = 0; i < NUM_DRUM_HITS; ++i) { if (list == mDrumHits[i].mHitCategoryDropdown) mDrumHits[i].mHitCategory = mDrumHits[i].mHitCategoryDropdown->GetLabel(mDrumHits[i].mHitCategoryIndex); } if (list == mQuantizeIntervalSelector) { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) transportListenerInfo->mInterval = mQuantizeInterval; } } void DrumPlayer::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEditCheckbox) UpdateVisibleControls(); for (int i = 0; i < NUM_DRUM_HITS; ++i) { if (checkbox == mDrumHits[i].mIndividualOutputCheckbox) { int outputIndex = GetIndividualOutputIndex(i); if (mDrumHits[i].mHasIndividualOutput) { if (outputIndex == -1) mIndividualOutputs.push_back(new IndividualOutput(this, i)); } else { if (outputIndex != -1) { RemovePatchCableSource(mIndividualOutputs[outputIndex]->mPatchCableSource); delete mIndividualOutputs[outputIndex]; mIndividualOutputs.erase(mIndividualOutputs.begin() + outputIndex); } } } } } void DrumPlayer::ButtonClicked(ClickButton* button, double time) { /*if (button == mSaveButton) SaveKits(); if (button == mNewKitButton) CreateKit();*/ if (button == mShuffleButton) ShuffleKit(); for (int i = 0; i < NUM_DRUM_HITS; ++i) { if (button == mDrumHits[i].mTestButton) PlayNote(time, i, 127); if (button == mDrumHits[i].mRandomButton) mDrumHits[i].LoadRandomSample(); if (button == mDrumHits[i].mGrabSampleButton) mDrumHits[i].GrabSample(); if (button == mDrumHits[i].mNextButton) mDrumHits[i].LoadNextSample(1); if (button == mDrumHits[i].mPrevButton) mDrumHits[i].LoadNextSample(-1); } } void DrumPlayer::DrumHit::LoadSample(std::string path) { mOwner->LoadSampleLock(); mSample.Read(path.c_str()); mOwner->LoadSampleUnlock(); //mSample.Play(gTime, mSpeed, 0); //mVelocity = .5f; mEnvelopeLength = mSample.LengthInSamples() * gInvSampleRateMs; for (size_t i = 0; i < mPlayheads.size(); ++i) mPlayheads[i].mStartTime = -1; } void DrumPlayer::DrumHit::LoadRandomSample() { File dir(ofToDataPath("drums/" + mHitCategory)); Array<File> files; for (auto file : dir.findChildFiles(File::findFiles, false)) { if (file.getFileName()[0] != '.') files.add(file); } if (files.size() > 0) LoadSample(files[gRandom() % files.size()].getFullPathName().toStdString()); } void DrumPlayer::DrumHit::LoadNextSample(int direction) { File dir(ofToDataPath("drums/" + mHitCategory)); Array<File> files; int currentIndex = -1; int i = 0; auto dirContents = dir.findChildFiles(File::findFiles, false); dirContents.sort(); for (auto file : dirContents) { if (file.getFileName()[0] != '.') { files.add(file); if (mSample.GetReadPath() == file.getFullPathName().replace(GetPathSeparator(), "/")) currentIndex = i; ++i; } } if (files.size() > 0) { int newIndex; if (currentIndex == -1) newIndex = 0; else newIndex = ofClamp(currentIndex + direction, 0, (int)files.size() - 1); LoadSample(files[newIndex].getFullPathName().toStdString()); } } void DrumPlayer::DrumHit::GrabSample() { TheSynth->GrabSample(mSample.Data(), mSample.Name()); } void DrumPlayer::TextEntryComplete(TextEntry* entry) { } std::vector<IUIControl*> DrumPlayer::ControlsToNotSetDuringLoadState() const { std::vector<IUIControl*> ignore; ignore.push_back(mKitSelector); for (int i = 0; i < NUM_DRUM_HITS; ++i) ignore.push_back(mDrumHits[i].mHitCategoryDropdown); return ignore; } void DrumPlayer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void DrumPlayer::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); //LoadKit(0); } void DrumPlayer::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); for (int i = 0; i < NUM_DRUM_HITS; ++i) { mDrumHits[i].mSample.SaveState(out); out << mDrumHits[i].mLinkId; out << mDrumHits[i].mVol; out << mDrumHits[i].mSpeed; out << mDrumHits[i].mHitCategory; } } void DrumPlayer::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); for (int i = 0; i < NUM_DRUM_HITS; ++i) { mDrumHits[i].mSample.LoadState(in); in >> mDrumHits[i].mLinkId; in >> mDrumHits[i].mVol; in >> mDrumHits[i].mSpeed; if (rev >= 1) { in >> mDrumHits[i].mHitCategory; mDrumHits[i].UpdateHitDirectoryDropdown(); } } mNeedSetup = false; } ```
/content/code_sandbox/Source/DrumPlayer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
11,429
```c++ /** bespoke synth, a software modular synthesizer This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see <path_to_url **/ /* ============================================================================== PulseFlag.cpp Created: 24 Jan 2023 Author: Ryan Challinor ============================================================================== */ #include "PulseFlag.h" #include "SynthGlobals.h" #include "UIControlMacros.h" #include "Transport.h" PulseFlag::PulseFlag() { } PulseFlag::~PulseFlag() { } void PulseFlag::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); DROPDOWN(mFlagValueSelector, "flag", &mFlagValue, 70); CHECKBOX(mReplaceFlagsCheckbox, "replace", &mReplaceFlags); ENDUIBLOCK(mWidth, mHeight); mFlagValueSelector->AddLabel("none", kPulseFlag_None); mFlagValueSelector->AddLabel("reset", kPulseFlag_Reset); mFlagValueSelector->AddLabel("random", kPulseFlag_Random); mFlagValueSelector->AddLabel("sync", kPulseFlag_SyncToTransport); mFlagValueSelector->AddLabel("backward", kPulseFlag_Backward); mFlagValueSelector->AddLabel("align", kPulseFlag_Align); mFlagValueSelector->AddLabel("repeat", kPulseFlag_Repeat); } void PulseFlag::DrawModule() { if (Minimized() || IsVisible() == false) return; mFlagValueSelector->Draw(); mReplaceFlagsCheckbox->Draw(); } void PulseFlag::OnPulse(double time, float velocity, int flags) { ComputeSliders(0); if (mEnabled) { if (mReplaceFlags) flags = 0; flags |= mFlagValue; } DispatchPulse(GetPatchCableSource(), time, velocity, flags); } void PulseFlag::GetModuleDimensions(float& width, float& height) { width = mWidth; height = mHeight; } void PulseFlag::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void PulseFlag::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/PulseFlag.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
571
```objective-c /* ============================================================================== LockFreeQueue.h Created: 1 Apr 2014 6:27:32pm Author: Tom Maisey ============================================================================== */ #pragma once /** * A simple single producer & consumer lock free queue, based on Herb Sutter's code: * path_to_url * * This is a linked list, which can expand arbitrarily without losing old data, * but which has poor cache locality (I plan to write a ring buffer version soon). */ template <typename T> class LockFreeQueue { public: LockFreeQueue() { first = new Node(T()); // Dummy seperator. last.set(first); divider.set(first); } ~LockFreeQueue() { while (first != nullptr) { Node* toDel = first; first = toDel->next; delete toDel; } } /** * Add an item to the queue. Obviously, should only be called from producer's thread. */ void produce(const T& t) { last.get()->next = new Node(t); last.set(last.get()->next); while (first != divider.get()) { // trim unused nodes Node* tmp = first; first = first->next; delete tmp; } } /** * Consume an item in the queue. Returns false if no items left to consume. */ bool consume(T& result) { Node* div = divider.get(); if (div != last.get()) { // if queue is nonempty result = div->next->value; // copy requested value divider.set(div->next); // publish that we took it return true; } return false; } private: struct Node { Node(const T& val) : value(val) {} T value; Node* next{ nullptr }; }; Node* first{ nullptr }; Atomic<Node*> divider, last; }; ```
/content/code_sandbox/Source/LockFreeQueue.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
430