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
```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.cpp // Bespoke // // Created by Ryan Challinor on 2/25/15. // // #include "StutterControl.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Profiler.h" StutterControl::StutterControl() : IAudioProcessor(gBufferSize) { for (int i = 0; i < kNumStutterTypes; ++i) mStutter[i] = false; } void StutterControl::CreateUIControls() { IDrawableModule::CreateUIControls(); mGridControlTarget = new GridControlTarget(this, "grid", 5, 145); mStutterCheckboxes[kHalf] = new Checkbox(this, "half note", 4, 3, &mStutter[kHalf]); mStutterCheckboxes[kQuarter] = new Checkbox(this, "quarter", mStutterCheckboxes[kHalf], kAnchor_Below, &mStutter[kQuarter]); mStutterCheckboxes[k8th] = new Checkbox(this, "8th", mStutterCheckboxes[kQuarter], kAnchor_Below, &mStutter[k8th]); mStutterCheckboxes[k16th] = new Checkbox(this, "16th", mStutterCheckboxes[k8th], kAnchor_Below, &mStutter[k16th]); mStutterCheckboxes[k32nd] = new Checkbox(this, "32nd", mStutterCheckboxes[k16th], kAnchor_Below, &mStutter[k32nd]); mStutterCheckboxes[k64th] = new Checkbox(this, "64th", mStutterCheckboxes[k32nd], kAnchor_Below, &mStutter[k64th]); mStutterCheckboxes[kReverse] = new Checkbox(this, "reverse", mStutterCheckboxes[k64th], kAnchor_Below, &mStutter[kReverse]); mStutterCheckboxes[kRampIn] = new Checkbox(this, "ramp in", mStutterCheckboxes[kReverse], kAnchor_Below, &mStutter[kRampIn]); mStutterCheckboxes[kRampOut] = new Checkbox(this, "ramp out", mStutterCheckboxes[kHalf], kAnchor_Right, &mStutter[kRampOut]); mStutterCheckboxes[kTumbleUp] = new Checkbox(this, "tumble up", mStutterCheckboxes[kRampOut], kAnchor_Below, &mStutter[kTumbleUp]); mStutterCheckboxes[kTumbleDown] = new Checkbox(this, "tumble down", mStutterCheckboxes[kTumbleUp], kAnchor_Below, &mStutter[kTumbleDown]); mStutterCheckboxes[kHalfSpeed] = new Checkbox(this, "half speed", mStutterCheckboxes[kTumbleDown], kAnchor_Below, &mStutter[kHalfSpeed]); mStutterCheckboxes[kDoubleSpeed] = new Checkbox(this, "double speed", mStutterCheckboxes[kHalfSpeed], kAnchor_Below, &mStutter[kDoubleSpeed]); mStutterCheckboxes[kDotted8th] = new Checkbox(this, "dotted eighth", mStutterCheckboxes[kDoubleSpeed], kAnchor_Below, &mStutter[kDotted8th]); mStutterCheckboxes[kQuarterTriplets] = new Checkbox(this, "triplets", mStutterCheckboxes[kDotted8th], kAnchor_Below, &mStutter[kQuarterTriplets]); mStutterCheckboxes[kFree] = new Checkbox(this, "free", mStutterCheckboxes[kQuarterTriplets], kAnchor_Below, &mStutter[kFree]); mFreeLengthSlider = new FloatSlider(this, "free length", mStutterCheckboxes[kFree], kAnchor_Below, 102, 15, &mStutterProcessor.mFreeStutterLength, .005f, .25f); mFreeSpeedSlider = new FloatSlider(this, "free speed", mFreeLengthSlider, kAnchor_Below, 102, 15, &mStutterProcessor.mFreeStutterSpeed, 0, 2); } void StutterControl::Init() { IDrawableModule::Init(); mStutterProcessor.Init(); } StutterControl::~StutterControl() { } void StutterControl::Process(double time) { PROFILER(StutterControl); if (!mEnabled) return; ComputeSliders(0); SyncBuffers(); IAudioReceiver* target = GetTarget(); if (target) { mStutterProcessor.ProcessAudio(time, GetBuffer()); 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 StutterControl::DrawModule() { if (Minimized() || IsVisible() == false) return; mStutterProcessor.DrawStutterBuffer(4, 3, 90, 35); for (int i = 0; i < kNumStutterTypes; ++i) mStutterCheckboxes[i]->Draw(); mFreeLengthSlider->Draw(); mFreeSpeedSlider->Draw(); mGridControlTarget->Draw(); } void StutterControl::SendStutter(double time, StutterParams stutter, bool on) { if (on) mStutterProcessor.StartStutter(time, stutter); else mStutterProcessor.EndStutter(time, stutter); UpdateGridLights(); } StutterControl::StutterType StutterControl::GetStutterFromKey(int key) { if (key == 'q') return kHalf; if (key == 'w') return kQuarter; if (key == 'e') return k8th; if (key == 'r') return k16th; if (key == 't') return k32nd; if (key == 'y') return k64th; if (key == 'u') return kReverse; if (key == 'a') return kRampIn; if (key == 's') return kRampOut; if (key == 'd') return kTumbleUp; if (key == 'f') return kTumbleDown; if (key == 'g') return kHalfSpeed; if (key == 'h') return kDoubleSpeed; if (key == 'j') return kDotted8th; if (key == 'k') return kQuarterTriplets; if (key == 'l') return kFree; return kNumStutterTypes; } void StutterControl::GetModuleDimensions(float& width, float& height) { width = 175; height = 172; } StutterParams StutterControl::GetStutter(StutterControl::StutterType type) { switch (type) { case kHalf: return StutterParams(kInterval_2n, 1); case kQuarter: return StutterParams(kInterval_4n, 1); case k8th: return StutterParams(kInterval_8n, 1); case k16th: return StutterParams(kInterval_16n, 1); case k32nd: return StutterParams(kInterval_32n, 1); case k64th: return StutterParams(kInterval_64n, 1); case kReverse: return StutterParams(kInterval_2n, -1); case kRampIn: return StutterParams(kInterval_8n, 0, 1, 500); case kRampOut: return StutterParams(kInterval_2n, 1, 0, 700); case kTumbleUp: return StutterParams(kInterval_8n, 1, 10, 10000); case kTumbleDown: return StutterParams(kInterval_32n, 1, 0, 2000); case kHalfSpeed: return StutterParams(kInterval_8n, .5f); case kDoubleSpeed: return StutterParams(kInterval_8n, 2); case kDotted8th: return StutterParams(kInterval_8nd, 1); case kQuarterTriplets: return StutterParams(kInterval_4nt, 1); case kFree: return StutterParams(kInterval_None, 1); case kNumStutterTypes: break; } assert(false); return StutterParams(kInterval_None, 1); } void StutterControl::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) mStutterProcessor.SetEnabled(time, IsEnabled()); for (int i = 0; i < kNumStutterTypes; ++i) { if (checkbox == mStutterCheckboxes[i]) { SendStutter(time, GetStutter((StutterType)i), mStutter[i]); } } } void StutterControl::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void StutterControl::OnControllerPageSelected() { UpdateGridLights(); } void StutterControl::OnGridButton(int x, int y, float velocity, IGridController* grid) { int index = x + y * grid->NumCols(); double time = NextBufferTime(false); if (index < kNumStutterTypes) { mStutter[index] = velocity > 0; SendStutter(time, GetStutter((StutterType)index), mStutter[index]); } } void StutterControl::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { int index = pitch % kNumStutterTypes; mStutter[index] = velocity > 0; SendStutter(time, GetStutter((StutterType)index), mStutter[index]); } void StutterControl::UpdateGridLights() { if (mGridControlTarget == nullptr || mGridControlTarget->GetGridController() == nullptr) return; for (int i = 0; i < kNumStutterTypes; ++i) { mGridControlTarget->GetGridController()->SetLight(i % mGridControlTarget->GetGridController()->NumCols(), i / mGridControlTarget->GetGridController()->NumCols(), mStutter[i] ? kGridColor1Bright : kGridColor1Dim); } } bool StutterControl::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 = 7 - gridIndex / 8; if (y < 2) { int index = x + y * 8; mStutter[index] = midiValue > 0; SendStutter(gTime, GetStutter((StutterType)index), mStutter[index]); } return true; } } return false; } void StutterControl::UpdatePush2Leds(Push2Control* push2) { for (int x = 0; x < 8; ++x) { for (int y = 0; y < 8; ++y) { int pushColor; if (y < 2) { int index = x + y * 8; if (mStutter[index]) pushColor = 2; else pushColor = 1; } else { pushColor = 0; } push2->SetLed(kMidiMessage_Note, x + (7 - y) * 8 + 36, pushColor); } } } void StutterControl::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void StutterControl::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); } ```
/content/code_sandbox/Source/StutterControl.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,848
```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 **/ // // NoteFilter.cpp // Bespoke // // Created by Ryan Challinor on 11/28/15. // // #include "NoteFilter.h" #include "SynthGlobals.h" NoteFilter::NoteFilter() { for (int i = 0; i < 128; ++i) { mGate[i] = true; mLastPlayTime[i] = -999; } } NoteFilter::~NoteFilter() { } void NoteFilter::CreateUIControls() { IDrawableModule::CreateUIControls(); } void NoteFilter::DrawModule() { if (Minimized() || IsVisible() == false) return; int pitch = mMinPitch; for (auto* checkbox : mGateCheckboxes) { checkbox->Draw(); ofPushStyle(); ofFill(); ofSetColor(0, 255, 0, (1 - ofClamp((gTime - mLastPlayTime[pitch]) / 250, 0, 1)) * 255); ofRect(75, checkbox->GetPosition(true).y + 4, 8, 8); ofPopStyle(); ++pitch; } } void NoteFilter::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled) { if (pitch >= 0 && pitch < 128) { if (velocity > 0) mLastPlayTime[pitch] = time; if ((pitch >= mMinPitch && pitch <= mMaxPitch && mGate[pitch]) || velocity == 0) PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } } else { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } } void NoteFilter::GetModuleDimensions(float& width, float& height) { width = 80; height = 3 + (mMaxPitch - mMinPitch + 1) * 18; } void NoteFilter::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadInt("min pitch", moduleInfo, 0, 0, 127, K(isTextField)); mModuleSaveData.LoadInt("max pitch", moduleInfo, 7, 0, 127, K(isTextField)); SetUpFromSaveData(); } void NoteFilter::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); mMinPitch = mModuleSaveData.GetInt("min pitch"); mMaxPitch = mModuleSaveData.GetInt("max pitch"); for (auto* checkbox : mGateCheckboxes) RemoveUIControl(checkbox); mGateCheckboxes.clear(); int numCheckboxes = (mMaxPitch - mMinPitch + 1); for (int i = 0; i < numCheckboxes; ++i) { int pitch = i + mMinPitch; Checkbox* checkbox = new Checkbox(this, (NoteName(pitch) + ofToString(pitch / 12 - 2) + " (" + ofToString(pitch) + ")").c_str(), 3, 3 + i * 18, &mGate[pitch]); mGateCheckboxes.push_back(checkbox); } } ```
/content/code_sandbox/Source/NoteFilter.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
818
```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 **/ // // PitchShiftEffect.h // Bespoke // // Created by Ryan Challinor on 3/21/15. // // #pragma once #include <iostream> #include "IAudioEffect.h" #include "Slider.h" #include "PitchShifter.h" #include "RadioButton.h" class PitchShiftEffect : public IAudioEffect, public IIntSliderListener, public IFloatSliderListener, public IRadioButtonListener { public: PitchShiftEffect(); ~PitchShiftEffect(); static IAudioEffect* Create() { return new PitchShiftEffect(); } 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 "pitchshift"; } void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; float mRatio{ 1 }; FloatSlider* mRatioSlider{ nullptr }; int mRatioSelection{ 10 }; RadioButton* mRatioSelector{ nullptr }; PitchShifter* mPitchShifter[ChannelBuffer::kMaxNumChannels]; }; ```
/content/code_sandbox/Source/PitchShiftEffect.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
434
```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 **/ // // Looper.h // modularSynth // // Created by Ryan Challinor on 11/25/12. // // #pragma once #include <iostream> #include "IAudioProcessor.h" #include "IDrawableModule.h" #include "RollingBuffer.h" #include "ClickButton.h" #include "RadioButton.h" #include "Slider.h" #include "DropdownList.h" #include "Checkbox.h" #include "Ramp.h" #include "JumpBlender.h" #include "PitchShifter.h" #include "INoteReceiver.h" #include "SwitchAndRamp.h" class LooperRecorder; class Rewriter; class Sample; class LooperGranulator; #define LOOPER_COMMIT_FADE_SAMPLES 200 class Looper : public IAudioProcessor, public IDrawableModule, public IDropdownListener, public IButtonListener, public IFloatSliderListener, public IRadioButtonListener, public INoteReceiver { public: Looper(); ~Looper(); static IDrawableModule* Create() { return new Looper(); } static bool AcceptsAudio() { return true; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void SetRecorder(LooperRecorder* recorder); void Clear(); void Commit(RollingBuffer* commitBuffer, bool replaceOnCommit, float offsetMs); void Fill(ChannelBuffer* buffer, int length); void ResampleForSpeed(float speed); int GetNumBars() const { return mNumBars; } int GetRecorderNumBars() const; void SetNumBars(int numBars); void RecalcLoopLength() { UpdateNumBars(mNumBars); } void DoubleNumBars() { mNumBars *= 2; } void HalveNumBars(); void ShiftMeasure() { mWantShiftMeasure = true; } void HalfShift() { mWantHalfShift = true; } void ShiftDownbeat() { mWantShiftDownbeat = true; } ChannelBuffer* GetLoopBuffer(int& loopLength); void SetLoopBuffer(ChannelBuffer* buffer); void LockBufferMutex() { mBufferMutex.lock(); } void UnlockBufferMutex() { mBufferMutex.unlock(); } void SampleDropped(int x, int y, Sample* sample) override; bool CanDropSample() const override { return true; } float* GetLoopPosVar() { return &mLoopPos; } int GetLoopLength() { return mLoopLength; } void SetGranulator(LooperGranulator* granulator) { mGranulator = granulator; } double GetPlaybackSpeed() const; void Poll() override; void Exit() override; //IAudioSource void Process(double time) 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 SendCC(int control, int value, int voiceIdx = -1) override {} //IDrawableModule void FilesDropped(std::vector<std::string> files, int x, int y) override; bool DrawToPush2Screen() override; void MergeIn(Looper* otherLooper); void SwapBuffers(Looper* otherLooper); void CopyBuffer(Looper* sourceLooper); void SetLoopLength(int length); void SetRewriter(Rewriter* rewriter) { mRewriter = rewriter; } void Rewrite(); bool GetMute() const { return mMute; } void SetMute(double time, bool mute); bool CheckNeedsDraw() override { return true; } //IButtonListener void ButtonClicked(ClickButton* button, double time) override; //IFloatSliderListener void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; //IRadioButtonListener void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; //IDropdownListener 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; int GetModuleSaveStateRev() const override { return 1; } bool IsEnabled() const override { return mEnabled; } private: void DoShiftMeasure(); void DoHalfShift(); void DoShiftDownbeat(); void DoShiftOffset(); void DoCommit(double time); void UpdateNumBars(int oldNumBars); void BakeVolume(); void DoUndo(); void ProcessFourTet(double time, int sampleIdx); void ProcessScratch(); void ProcessBeatwheel(double time, int sampleIdx); int GetMeasureSliceIndex(double time, int sampleIdx, int slicesPerBar); void DrawBeatwheel(); float GetActualLoopPos(int samplesIn) const; int GetBeatwheelDepthLevel() const; //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; void OnClicked(float x, float y, bool right) override; ChannelBuffer* mBuffer{ nullptr }; ChannelBuffer mWorkBuffer; int mLoopLength{ -1 }; float mLoopPos{ 0 }; int mNumBars{ 1 }; ClickButton* mClearButton{ nullptr }; DropdownList* mNumBarsSelector{ nullptr }; float mVol{ 1 }; float mSmoothedVol{ 1 }; FloatSlider* mVolSlider{ nullptr }; float mSpeed{ 1 }; LooperRecorder* mRecorder{ nullptr }; ClickButton* mMergeButton{ nullptr }; ClickButton* mSwapButton{ nullptr }; ClickButton* mCopyButton{ nullptr }; RollingBuffer* mCommitBuffer{ nullptr }; //if this is set, a commit happens next audio frame ClickButton* mVolumeBakeButton{ nullptr }; bool mWantBakeVolume{ false }; int mLastCommit{ 0 }; ClickButton* mSaveButton{ nullptr }; bool mWantShiftMeasure{ false }; bool mWantHalfShift{ false }; bool mWantShiftDownbeat{ false }; bool mWantShiftOffset{ false }; bool mMute{ false }; Checkbox* mMuteCheckbox{ nullptr }; bool mPassthrough{ true }; Checkbox* mPassthroughCheckbox{ nullptr }; ClickButton* mCommitButton{ nullptr }; ClickButton* mDoubleSpeedButton{ nullptr }; ClickButton* mHalveSpeedButton{ nullptr }; ClickButton* mExtendButton{ nullptr }; ChannelBuffer* mUndoBuffer{ nullptr }; ClickButton* mUndoButton{ nullptr }; bool mWantUndo{ false }; bool mReplaceOnCommit{ false }; float mCommitMsOffset{ 0 }; float mLoopPosOffset{ 0 }; FloatSlider* mLoopPosOffsetSlider{ nullptr }; ClickButton* mWriteOffsetButton{ nullptr }; float mScratchSpeed{ 1 }; bool mAllowScratch{ false }; FloatSlider* mScratchSpeedSlider{ nullptr }; Checkbox* mAllowScratchCheckbox{ nullptr }; double mLastCommitTime{ 0 }; float mFourTet{ 0 }; FloatSlider* mFourTetSlider{ nullptr }; int mFourTetSlices{ 4 }; DropdownList* mFourTetSlicesDropdown{ nullptr }; ofMutex mBufferMutex; Ramp mMuteRamp; JumpBlender mJumpBlender[ChannelBuffer::kMaxNumChannels]; bool mClearCommitBuffer{ false }; Rewriter* mRewriter{ nullptr }; bool mWantRewrite{ false }; int mLoopCount{ 0 }; ChannelBuffer* mQueuedNewBuffer{ nullptr }; float mDecay{ 0 }; FloatSlider* mDecaySlider{ nullptr }; bool mWriteInput{ false }; Checkbox* mWriteInputCheckbox{ nullptr }; ClickButton* mQueueCaptureButton{ nullptr }; bool mCaptureQueued{ false }; Ramp mWriteInputRamp; float mLastInputSample[ChannelBuffer::kMaxNumChannels]; float mBufferTempo{ -1 }; ClickButton* mResampleButton{ nullptr }; //beatwheel bool mBeatwheel{ false }; static float mBeatwheelPosRight; static float mBeatwheelDepthRight; static float mBeatwheelPosLeft; static float mBeatwheelDepthLeft; Checkbox* mBeatwheelCheckbox{ nullptr }; FloatSlider* mBeatwheelPosRightSlider{ nullptr }; FloatSlider* mBeatwheelDepthRightSlider{ nullptr }; FloatSlider* mBeatwheelPosLeftSlider{ nullptr }; FloatSlider* mBeatwheelDepthLeftSlider{ nullptr }; bool mBeatwheelControlFlip{ false }; static bool mBeatwheelSingleMeasure; Checkbox* mBeatwheelSingleMeasureCheckbox{ nullptr }; //pitch shifter PitchShifter* mPitchShifter[ChannelBuffer::kMaxNumChannels]; float mPitchShift{ 1 }; FloatSlider* mPitchShiftSlider{ nullptr }; bool mKeepPitch{ false }; Checkbox* mKeepPitchCheckbox{ nullptr }; LooperGranulator* mGranulator{ nullptr }; SwitchAndRamp mSwitchAndRamp; }; ```
/content/code_sandbox/Source/Looper.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,171
```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 **/ /* ============================================================================== GlobalControls.cpp Created: 26 Sep 2020 11:34:18am Author: Ryan Challinor ============================================================================== */ #include "GlobalControls.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "UIControlMacros.h" GlobalControls::GlobalControls() { } GlobalControls::~GlobalControls() { } void GlobalControls::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); FLOATSLIDER(mZoomSlider, "zoom", &gDrawScale, .1f, 8.0f); FLOATSLIDER(mXSlider, "x pos", &(TheSynth->GetDrawOffset().x), -10000, 10000); FLOATSLIDER(mYSlider, "y pos", &(TheSynth->GetDrawOffset().y), -10000, 10000); FLOATSLIDER(mMouseScrollXSlider, "scroll x", &mMouseScrollX, -100, 100); FLOATSLIDER(mMouseScrollYSlider, "scroll y", &mMouseScrollY, -100, 100); FLOATSLIDER(mBackgroundLissajousRSlider, "lissajous r", &ModularSynth::sBackgroundLissajousR, 0, 1); FLOATSLIDER(mBackgroundLissajousGSlider, "lissajous g", &ModularSynth::sBackgroundLissajousG, 0, 1); FLOATSLIDER(mBackgroundLissajousBSlider, "lissajous b", &ModularSynth::sBackgroundLissajousB, 0, 1); FLOATSLIDER(mBackgroundRSlider, "background r", &ModularSynth::sBackgroundR, 0, 1); FLOATSLIDER(mBackgroundGSlider, "background g", &ModularSynth::sBackgroundG, 0, 1); FLOATSLIDER(mBackgroundBSlider, "background b", &ModularSynth::sBackgroundB, 0, 1); FLOATSLIDER(mCornerRadiusSlider, "corner radius", &gCornerRoundness, 0, 2); FLOATSLIDER(mCableAlphaSlider, "cable alpha", &ModularSynth::sCableAlpha, 0.05, 1); ENDUIBLOCK(mWidth, mHeight); } void GlobalControls::Poll() { ComputeSliders(0); } void GlobalControls::DrawModule() { if (Minimized() || IsVisible() == false) return; mZoomSlider->Draw(); mXSlider->Draw(); mYSlider->Draw(); mMouseScrollXSlider->Draw(); mMouseScrollYSlider->Draw(); mBackgroundLissajousRSlider->Draw(); mBackgroundLissajousGSlider->Draw(); mBackgroundLissajousBSlider->Draw(); mBackgroundRSlider->Draw(); mBackgroundGSlider->Draw(); mBackgroundBSlider->Draw(); mCornerRadiusSlider->Draw(); mCableAlphaSlider->Draw(); } void GlobalControls::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mZoomSlider && gHoveredUIControl != mZoomSlider) //avoid bad behavior when adjusting these via mouse { //zoom in on center of screen float zoomAmount = (gDrawScale - oldVal) / oldVal; ofVec2f zoomCenter = ofVec2f(TheSynth->GetMouseX(GetOwningContainer()), TheSynth->GetMouseY(GetOwningContainer())) + TheSynth->GetDrawOffset(); TheSynth->GetDrawOffset() -= zoomCenter * zoomAmount; } if (slider == mMouseScrollXSlider && gHoveredUIControl != mMouseScrollXSlider) //avoid bad behavior when adjusting these via mouse { float delta = mMouseScrollX - oldVal; TheSynth->MouseScrolled(-delta, 0, false, false, false); mMouseScrollX = 0; } if (slider == mMouseScrollYSlider && gHoveredUIControl != mMouseScrollYSlider) //avoid bad behavior when adjusting these via mouse { float delta = mMouseScrollY - oldVal; TheSynth->MouseScrolled(0, -delta, false, false, false); mMouseScrollY = 0; } } void GlobalControls::GetModuleDimensions(float& w, float& h) { w = mWidth; h = mHeight; } void GlobalControls::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void GlobalControls::SetUpFromSaveData() { } void GlobalControls::SaveLayout(ofxJSONElement& moduleInfo) { } std::vector<IUIControl*> GlobalControls::ControlsToNotSetDuringLoadState() const { std::vector<IUIControl*> ignore; ignore.push_back(mZoomSlider); ignore.push_back(mXSlider); ignore.push_back(mYSlider); ignore.push_back(mMouseScrollXSlider); ignore.push_back(mMouseScrollYSlider); return ignore; } void GlobalControls::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); } void GlobalControls::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); } ```
/content/code_sandbox/Source/GlobalControls.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,332
```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 **/ // // ClickButton.cpp // modularSynth // // Created by Ryan Challinor on 12/4/12. // // #include "ClickButton.h" #include "IDrawableModule.h" #include "SynthGlobals.h" #include <cstring> #include "PatchCableSource.h" ClickButton::ClickButton(IButtonListener* owner, const char* label, int x, int y, ButtonDisplayStyle displayStyle /*= ButtonDisplayStyle::kText*/) : mOwner(owner) , mDisplayStyle(displayStyle) { assert(owner); SetLabel(label); SetPosition(x, y); (dynamic_cast<IDrawableModule*>(owner))->AddUIControl(this); SetParent(dynamic_cast<IClickable*>(owner)); SetShouldSaveState(false); } ClickButton::ClickButton(IButtonListener* owner, const char* label, IUIControl* anchor, AnchorDirection anchorDirection, ButtonDisplayStyle displayStyle /*= ButtonDisplayStyle::kText*/) : ClickButton(owner, label, -1, -1, displayStyle) { PositionTo(anchor, anchorDirection); } ClickButton::~ClickButton() { } void ClickButton::SetLabel(const char* label) { SetName(label); UpdateWidth(); } void ClickButton::UpdateWidth() { if (mDisplayStyle == ButtonDisplayStyle::kText || mDisplayStyle == ButtonDisplayStyle::kSampleIcon || mDisplayStyle == ButtonDisplayStyle::kFolderIcon) { mWidth = GetStringWidth(GetDisplayName()) + 3 + .25f * strnlen(GetDisplayName().c_str(), 50); if (mDisplayStyle == ButtonDisplayStyle::kSampleIcon || mDisplayStyle == ButtonDisplayStyle::kFolderIcon) mWidth += 20; } } void ClickButton::Render() { ofPushStyle(); float w, h; GetDimensions(w, h); ofColor color, textColor; IUIControl::GetColors(color, textColor); ofFill(); ofSetColor(0, 0, 0, gModuleDrawAlpha * .5f); ofRect(mX + 1, mY + 1, w, h); DrawBeacon(mX + w / 2, mY + h / 2); float press = ofClamp((1 - (gTime - mClickTime) / 200), 0, 1); color.r = ofLerp(color.r, 0, press); color.g = ofLerp(color.g, 0, press); color.b = ofLerp(color.b, 0, press); ofSetColor(color); ofRect(mX, mY, w, h); if (mDisplayStyle == ButtonDisplayStyle::kText) { ofSetColor(textColor); DrawTextNormal(GetDisplayName(), mX + 2, mY + 12); } else if (mDisplayStyle == ButtonDisplayStyle::kPlay) { ofSetColor(textColor); ofFill(); ofTriangle(mX + 5, mY + 2, mX + 5, mY + 12, mX + 15, mY + 7); } else if (mDisplayStyle == ButtonDisplayStyle::kPause) { ofSetColor(textColor); ofFill(); ofRect(mX + 5, mY + 2, 4, 10, 0); ofRect(mX + 11, mY + 2, 4, 10, 0); } else if (mDisplayStyle == ButtonDisplayStyle::kStop) { ofSetColor(textColor); ofFill(); ofRect(mX + 5, mY + 2, 10, 10, 0); } else if (mDisplayStyle == ButtonDisplayStyle::kGrabSample) { ofSetColor(textColor); for (int i = 0; i < 5; ++i) { float height = (i % 2 == 0) ? 6 : 10; float x = mX + 4 + i * 3; ofLine(x, mY + 7 - height / 2, x, mY + 7 + height / 2); } } else if (mDisplayStyle == ButtonDisplayStyle::kSampleIcon) { ofSetColor(textColor); for (int i = 0; i < 5; ++i) { float height = (i % 2 == 0) ? 6 : 10; float x = mX + 4 + i * 3; ofLine(x, mY + 7 - height / 2, x, mY + 7 + height / 2); } DrawTextNormal(GetDisplayName(), mX + 22, mY + 12); } else if (mDisplayStyle == ButtonDisplayStyle::kFolderIcon) { ofSetColor(textColor); ofFill(); ofRect(mX + 2, mY + 2, 7, 5, 2); ofRect(mX + 2, mY + 4, 16, 9, 2); DrawTextNormal(GetDisplayName(), mX + 22, mY + 12); } else if (mDisplayStyle == ButtonDisplayStyle::kArrowRight) { ofSetColor(textColor); ofLine(mX + 6, mY + 3, mX + 14, mY + 7); ofLine(mX + 6, mY + 11, mX + 14, mY + 7); } else if (mDisplayStyle == ButtonDisplayStyle::kArrowLeft) { ofSetColor(textColor); ofLine(mX + 14, mY + 3, mX + 6, mY + 7); ofLine(mX + 14, mY + 11, mX + 6, mY + 7); } else if (mDisplayStyle == ButtonDisplayStyle::kPlus) { ofSetColor(textColor); ofSetLineWidth(1.5f); ofLine(mX + 10, mY + 3, mX + 10, mY + 12); ofLine(mX + 6, mY + 7.5f, mX + 14, mY + 7.5f); } else if (mDisplayStyle == ButtonDisplayStyle::kMinus) { ofSetColor(textColor); ofSetLineWidth(1.5f); ofLine(mX + 6, mY + 7.5f, mX + 14, mY + 7.5f); } else if (mDisplayStyle == ButtonDisplayStyle::kHamburger) { ofSetColor(textColor); ofSetLineWidth(1.0f); ofLine(mX + 6, mY + 4.5f, mX + 14, mY + 4.5f); ofLine(mX + 6, mY + 7.5f, mX + 14, mY + 7.5f); ofLine(mX + 6, mY + 10.5f, mX + 14, mY + 10.5f); } ofPopStyle(); DrawHover(mX, mY, w, h); } bool ClickButton::ButtonLit() const { return mClickTime + 200 > gTime; } bool ClickButton::CanBeTargetedBy(PatchCableSource* source) const { if (source->GetConnectionType() == kConnectionType_Pulse) return true; return IUIControl::CanBeTargetedBy(source); } void ClickButton::OnPulse(double time, float velocity, int flags) { if (velocity > 0) DoClick(time); } void ClickButton::OnClicked(float x, float y, bool right) { if (right) return; DoClick(NextBufferTime(false)); } void ClickButton::DoClick(double time) { mClickTime = time; mOwner->ButtonClicked(this, time); } void ClickButton::MouseReleased() { mClickTime = 0; } bool ClickButton::MouseMoved(float x, float y) { CheckHover(x, y); return false; } void ClickButton::SetFromMidiCC(float slider, double time, bool setViaModulator) { if (slider > 0) DoClick(time); else MouseReleased(); } void ClickButton::SetValue(float value, double time, bool forceUpdate /*= false*/) { if (value > 0) DoClick(time); else MouseReleased(); } float ClickButton::GetMidiValue() const { if (ButtonLit()) return 1; return 0; } std::string ClickButton::GetDisplayValue(float val) const { if (val > 0) return "click"; return "_"; } void ClickButton::Increment(float amount) { DoClick(NextBufferTime(false)); } ```
/content/code_sandbox/Source/ClickButton.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,058
```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 **/ // // Sample.h // modularSynth // // Created by Ryan Challinor on 11/25/12. // // #pragma once #include "OpenFrameworksPort.h" #include "ChannelBuffer.h" #include <limits> #include "juce_events/juce_events.h" class FileStreamOut; class FileStreamIn; namespace juce { class AudioFormatReader; template <typename T> class AudioBuffer; using AudioSampleBuffer = AudioBuffer<float>; } class Sample : public juce::Timer { public: enum class ReadType { Sync, Async }; Sample(); ~Sample(); bool Read(const char* path, bool mono = false, ReadType readType = ReadType::Sync); bool Write(const char* path = nullptr); //no path = use read filename bool ConsumeData(double time, ChannelBuffer* out, int size, bool replace); void Play(double time, float rate, int offset, int stopPoint = -1); void SetRate(float rate) { mRate = rate; } std::string Name() const { return mName; } void SetName(std::string name) { mName = name; } int LengthInSamples() const { return mNumSamples; } int NumChannels() const { return mData.NumActiveChannels(); } ChannelBuffer* Data() { return &mData; } double GetPlayPosition() const { return mOffset; } void SetPlayPosition(double sample) { mOffset = sample; } float GetSampleRateRatio() const { return mSampleRateRatio; } void Reset() { mOffset = mNumSamples; } void SetStopPoint(int stopPoint) { mStopPoint = stopPoint; } void ClearStopPoint() { mStopPoint = -1; } void PadBack(int amount); void ClipTo(int start, int end); void ShiftWrap(int numSamples); std::string GetReadPath() const { return mReadPath; } static bool WriteDataToFile(const std::string& path, float** data, int numSamples, int channels = 1); static bool WriteDataToFile(const std::string& path, ChannelBuffer* data, int numSamples); bool IsPlaying() { return mOffset < mNumSamples; } void LockDataMutex(bool lock) { lock ? mDataMutex.lock() : mDataMutex.unlock(); } void Create(int length); void Create(ChannelBuffer* data); void SetLooping(bool looping) { mLooping = looping; } void SetNumBars(int numBars) { mNumBars = numBars; } int GetNumBars() const { return mNumBars; } void SetVolume(float vol) { mVolume = vol; } void CopyFrom(Sample* sample); bool IsSampleLoading() { return mSamplesLeftToRead > 0; } float GetSampleLoadProgress() { return (mNumSamples > 0) ? (1 - (float(mSamplesLeftToRead) / mNumSamples)) : 1; } void SaveState(FileStreamOut& out); void LoadState(FileStreamIn& in); private: void Setup(int length); void FinishRead(); //juce::Timer void timerCallback(); ChannelBuffer mData{ 0 }; int mNumSamples{ 0 }; double mStartTime{ 0 }; double mOffset{ std::numeric_limits<double>::max() }; float mRate{ 1 }; int mOriginalSampleRate{ gSampleRate }; float mSampleRateRatio{ 1 }; int mStopPoint{ -1 }; std::string mName{ "" }; std::string mReadPath{ "" }; ofMutex mDataMutex; ofMutex mPlayMutex; bool mLooping{ false }; int mNumBars{ -1 }; float mVolume{ 1 }; juce::AudioFormatReader* mReader{}; std::unique_ptr<juce::AudioSampleBuffer> mReadBuffer; int mSamplesLeftToRead{ 0 }; }; ```
/content/code_sandbox/Source/Sample.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
968
```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 **/ // // IDrawableModule.cpp // modularSynth // // Created by Ryan Challinor on 11/26/12. // // #include "IDrawableModule.h" #include "RollingBuffer.h" #include "IAudioSource.h" #include "INoteSource.h" #include "INoteReceiver.h" #include "IAudioReceiver.h" #include "IAudioEffect.h" #include "IUIControl.h" #include "Slider.h" #include "ofxJSONElement.h" #include "ModularSynth.h" #include "SynthGlobals.h" #include "TitleBar.h" #include "ModuleSaveDataPanel.h" #include "GridController.h" #include "ControlSequencer.h" #include "PatchCableSource.h" #include "nanovg/nanovg.h" #include "IPulseReceiver.h" #include "Push2Control.h" #include "UIGrid.h" #include "UserPrefs.h" #include "Prefab.h" float IDrawableModule::sHueNote = 27; float IDrawableModule::sHueAudio = 135; float IDrawableModule::sHueInstrument = 79; float IDrawableModule::sHueNoteSource = 240; float IDrawableModule::sSaturation = 145; float IDrawableModule::sBrightness = 220; IDrawableModule::IDrawableModule() { } IDrawableModule::~IDrawableModule() { for (int i = 0; i < mUIControls.size(); ++i) mUIControls[i]->Delete(); for (auto source : mPatchCableSources) delete source; } void IDrawableModule::CreateUIControls() { assert(mUIControlsCreated == false); mUIControlsCreated = true; mEnabledCheckbox = new Checkbox(this, "enabled", 3, -TitleBarHeight() - 2, &mEnabled); ConnectionType type = kConnectionType_Special; if (dynamic_cast<IAudioSource*>(this)) type = kConnectionType_Audio; else if (dynamic_cast<INoteSource*>(this)) type = kConnectionType_Note; else if (dynamic_cast<IGridController*>(this)) type = kConnectionType_Grid; else if (dynamic_cast<IPulseSource*>(this)) type = kConnectionType_Pulse; if (type != kConnectionType_Special && !ShouldSuppressAutomaticOutputCable()) { mPatchCableSources.push_back(new PatchCableSource(this, type)); } GetMinimizedWidth(); //update cached width } void IDrawableModule::Init() { assert(mUIControlsCreated); //did you not call CreateUIControls() for this module? assert(!mInitialized); mInitialized = true; ModuleFactory::ModuleInfo moduleInfo = TheSynth->GetModuleFactory()->GetModuleInfo(mTypeName); mModuleCategory = moduleInfo.mCategory; if (mModuleCategory == kModuleCategory_Unknown) { if (dynamic_cast<IAudioEffect*>(this)) mModuleCategory = kModuleCategory_Processor; } mCanReceiveAudio = moduleInfo.mCanReceiveAudio; mCanReceiveNotes = moduleInfo.mCanReceiveNotes; mCanReceivePulses = moduleInfo.mCanReceivePulses; // if you hit these asserts, it means that, for example, your module's // AcceptsPulses() returns false, but it inherits IPulseReceiver. // the fix is to make AcceptsPulses() (or the appropriate method) match the // list of inherited classes. assert(mCanReceiveAudio == (dynamic_cast<IAudioReceiver*>(this) != nullptr)); assert(mCanReceiveNotes == (dynamic_cast<INoteReceiver*>(this) != nullptr)); assert(mCanReceivePulses == (dynamic_cast<IPulseReceiver*>(this) != nullptr)); bool wasEnabled = IsEnabled(); bool showEnableToggle = false; SetEnabled(!wasEnabled); if (IsEnabled() == wasEnabled) //nothing changed showEnableToggle = false; //so don't show toggle, this module doesn't support it else showEnableToggle = true; SetEnabled(wasEnabled); if (showEnableToggle) { mEnabledCheckbox->SetDisplayText(false); mEnabledCheckbox->UseCircleLook(GetColor(mModuleCategory)); } else { RemoveUIControl(mEnabledCheckbox, false); mEnabledCheckbox->Delete(); mEnabledCheckbox = nullptr; } for (int i = 0; i < mUIControls.size(); ++i) mUIControls[i]->Init(); for (int i = 0; i < mChildren.size(); ++i) { ModuleContainer* container = GetContainer(); if (container != nullptr && VectorContains(mChildren[i], container->GetModules())) continue; //stuff in module containers was already initialized mChildren[i]->Init(); } mKeyboardFocusListener = dynamic_cast<IKeyboardFocusListener*>(this); } void IDrawableModule::BasePoll() { Poll(); for (int i = 0; i < mUIControls.size(); ++i) mUIControls[i]->Poll(); for (int i = 0; i < mChildren.size(); ++i) mChildren[i]->BasePoll(); } bool IDrawableModule::IsWithinRect(const ofRectangle& rect) { float x, y; GetPosition(x, y); float w, h; GetDimensions(w, h); float titleBarHeight = mTitleBarHeight; if (!HasTitleBar()) titleBarHeight = 0; return rect.intersects(ofRectangle(x, y - titleBarHeight, w, h + titleBarHeight)); } bool IDrawableModule::IsVisible() { return IsWithinRect(TheSynth->GetDrawRect()); } void IDrawableModule::DrawFrame(float w, float h, bool drawModule, float& titleBarHeight, float& highlight) { titleBarHeight = mTitleBarHeight; if (!HasTitleBar()) titleBarHeight = 0; ofTranslate(mX, mY, 0); ofColor color = GetColor(mModuleCategory); highlight = 0; if (IsEnabled()) { IAudioSource* audioSource = dynamic_cast<IAudioSource*>(this); if (audioSource) { RollingBuffer* vizBuff = audioSource->GetVizBuffer(); int numSamples = std::min(500, vizBuff->Size()); float sample; float mag = 0; for (int ch = 0; ch < vizBuff->NumChannels(); ++ch) { for (int i = 0; i < numSamples; ++i) { sample = vizBuff->GetSample(i, ch); mag += sample * sample; } } mag /= numSamples * vizBuff->NumChannels(); mag = sqrtf(mag); mag = sqrtf(mag); mag *= 3; mag = ofClamp(mag, 0, 1); if (UserPrefs.draw_module_highlights.Get()) highlight = mag * .15f; } if (GetPatchCableSource() != nullptr) { float elapsed = float(gTime - GetPatchCableSource()->GetHistory().GetLastOnEventTime()) / NOTE_HISTORY_LENGTH; if (UserPrefs.draw_module_highlights.Get()) highlight = MAX(highlight, .15f * ofClamp(1 - elapsed, 0, 1)); } } const bool kUseDropshadow = false; if (kUseDropshadow && GetParent() == nullptr && GetModuleCategory() != kModuleCategory_Other) { const float shadowSize = 20; float shadowStrength = .2f + highlight; NVGpaint shadowPaint = nvgBoxGradient(gNanoVG, -shadowSize / 2, -titleBarHeight - shadowSize / 2, w + shadowSize, h + titleBarHeight + shadowSize, gCornerRoundness * shadowSize * .5f, shadowSize, nvgRGBA(color.r * shadowStrength, color.g * shadowStrength, color.b * shadowStrength, 128), nvgRGBA(0, 0, 0, 0)); nvgBeginPath(gNanoVG); nvgRect(gNanoVG, -shadowSize, -shadowSize - titleBarHeight, w + shadowSize * 2, h + titleBarHeight + shadowSize * 2); nvgFillPaint(gNanoVG, shadowPaint); nvgFill(gNanoVG); } ofFill(); float backgroundAlpha = IsEnabled() ? 180 : 120; if (dynamic_cast<Prefab*>(this) != nullptr) backgroundAlpha = 60; if (IsEnabled()) ofSetColor(color.r * (.25f + highlight), color.g * (.25f + highlight), color.b * (.25f + highlight), backgroundAlpha); else ofSetColor(color.r * .2f, color.g * .2f, color.b * .2f, backgroundAlpha); //gModuleShader.begin(); const float kHighlightGrowAmount = 40; ofRect(0 - highlight * kHighlightGrowAmount, -titleBarHeight - highlight * kHighlightGrowAmount, w + highlight * kHighlightGrowAmount * 2, h + titleBarHeight + highlight * kHighlightGrowAmount * 2, 3 + highlight * kHighlightGrowAmount); //gModuleShader.end(); ofNoFill(); if (IsEnabled()) gModuleDrawAlpha = 255; else gModuleDrawAlpha = 100; bool dimModule = TheSynth->ShouldDimModule(this); if (dimModule) gModuleDrawAlpha *= .2f; float enableToggleOffset = 0; if (HasTitleBar()) { ofPushStyle(); ofSetColor(color, 50); ofFill(); ofPushMatrix(); ofClipWindow(0, -titleBarHeight, w, titleBarHeight, true); ofRect(0, -titleBarHeight, w, titleBarHeight * 2); ofPopMatrix(); if (mEnabledCheckbox) { enableToggleOffset = TitleBarHeight(); mEnabledCheckbox->Draw(); } if (mKeyboardFocusListener != nullptr && mKeyboardFocusListener->CanTakeFocus()) { if ((gHoveredModule == this && IKeyboardFocusListener::GetActiveKeyboardFocus() == nullptr) || IKeyboardFocusListener::GetActiveKeyboardFocus() == mKeyboardFocusListener) ofSetColor(255, 255, 255, gModuleDrawAlpha); else ofSetColor(color.r, color.g, color.b, gModuleDrawAlpha); float squareSize = titleBarHeight / 2 - 1; ofRect(w - 25, -titleBarHeight + 1, squareSize, squareSize, 1); ofRect(w - 25, -titleBarHeight / 2 + 1, squareSize, squareSize, 1); ofRect(w - 25 - squareSize - 1, -titleBarHeight / 2 + 1, squareSize, squareSize, 1); ofRect(w - 25 + squareSize + 1, -titleBarHeight / 2 + 1, squareSize, squareSize, 1); if (IKeyboardFocusListener::GetActiveKeyboardFocus() == mKeyboardFocusListener) { ofPushStyle(); ofSetLineWidth(.5f); ofNoFill(); ofRect(w - 25 - squareSize - 2 - 1, -titleBarHeight, 2 + squareSize + 1 + squareSize + 1 + squareSize + 2, titleBarHeight, 2); ofPopStyle(); } } if (IsSaveable() && !Minimized()) { ofSetColor(color.r, color.g, color.b, gModuleDrawAlpha); if (TheSaveDataPanel->GetModule() == this) { ofTriangle(w - 9, -titleBarHeight + 2, w - 9, -2, w - 2, -titleBarHeight / 2); } else { ofTriangle(w - 10, -titleBarHeight + 3, w - 2, -titleBarHeight + 3, w - 6, -2); } } ofPopStyle(); } const bool kDrawInnerFade = true; if (kDrawInnerFade && !Push2Control::sDrawingPush2Display) { float fadeRoundness = 100; float fadeLength = w / 3; const float kFadeStrength = .9f; NVGpaint shadowPaint = nvgBoxGradient(gNanoVG, 0, -titleBarHeight, w, h + titleBarHeight, fadeRoundness, fadeLength, nvgRGBA(color.r * .2f, color.g * .2f, color.b * .2f, backgroundAlpha * kFadeStrength), nvgRGBA(0, 0, 0, 0)); nvgBeginPath(gNanoVG); nvgRect(gNanoVG, 0, -titleBarHeight, w, h + titleBarHeight); nvgFillPaint(gNanoVG, shadowPaint); nvgFill(gNanoVG); } if (drawModule) { ofSetColor(color, gModuleDrawAlpha); ofPushMatrix(); if (ShouldClipContents()) ofClipWindow(0, 0, w, h, true); else ofResetClipWindow(); DrawModule(); ofPopMatrix(); } if (HasTitleBar()) { ofSetColor(color * (1 - GetBeaconAmount()) + ofColor::yellow * GetBeaconAmount(), gModuleDrawAlpha); DrawTextBold(GetTitleLabel(), 5 + enableToggleOffset, 10 - titleBarHeight, 14); } bool groupSelected = !TheSynth->GetGroupSelectedModules().empty() && VectorContains(this, TheSynth->GetGroupSelectedModules()); if ((IsEnabled() || groupSelected || TheSynth->GetMoveModule() == this) && mShouldDrawOutline) { ofPushStyle(); ofNoFill(); if (groupSelected) { float pulse = ofMap(sin(gTime / 500 * PI * 2), -1, 1, .2f, 1); ofSetColor(ofLerp(color.r, 255, pulse), ofLerp(color.g, 255, pulse), ofLerp(color.b, 255, pulse), 255); ofSetLineWidth(1.5f); } else if (TheSynth->GetMoveModule() == this) { ofSetColor(255, 255, 255); ofSetLineWidth(.5f); } else { ofSetColor(color.r * (.5f + highlight), color.g * (.5f + highlight), color.b * (.5f + highlight), 200); ofSetLineWidth(.5f); } ofRect(-.5f, -titleBarHeight - .5f, w + 1, h + titleBarHeight + 1, 4); ofPopStyle(); } } void IDrawableModule::Render() { if (!mShowing) return; PreDrawModule(); if (mMinimized) mMinimizeAnimation += ofGetLastFrameTime() * 5; else mMinimizeAnimation -= ofGetLastFrameTime() * 5; mMinimizeAnimation = ofClamp(mMinimizeAnimation, 0, 1); float w, h; GetDimensions(w, h); ofPushMatrix(); ofPushStyle(); float titleBarHeight; float highlight; DrawFrame(w, h, true, titleBarHeight, highlight); if (Minimized() || IsVisible() == false) DrawBeacon(30, -titleBarHeight / 2); ofPushStyle(); const float kPipWidth = 8; const float kPipSpacing = 2; float receiveIndicatorX = w - (kPipWidth + kPipSpacing); ofFill(); if (CanReceiveAudio()) { ofSetColor(GetColor(kModuleCategory_Audio)); ofRect(receiveIndicatorX, -titleBarHeight - 2, kPipWidth, 3, 1.0f); receiveIndicatorX -= kPipWidth + kPipSpacing; } if (CanReceiveNotes()) { ofSetColor(GetColor(kModuleCategory_Note)); ofRect(receiveIndicatorX, -titleBarHeight - 2, kPipWidth, 3, 1.0f); receiveIndicatorX -= kPipWidth + kPipSpacing; } if (CanReceivePulses()) { ofSetColor(GetColor(kModuleCategory_Pulse)); ofRect(receiveIndicatorX, -titleBarHeight - 2, kPipWidth, 3, 1.0f); receiveIndicatorX -= kPipWidth + kPipSpacing; } ofPopStyle(); if (IsResizable() && !Minimized()) { ofColor color = GetColor(mModuleCategory); ofSetColor(color, 255); if (mHoveringOverResizeHandle) ofSetLineWidth(4); else ofSetLineWidth(2); ofLine(w - sResizeCornerSize, h, w, h); ofLine(w, h - sResizeCornerSize, w, h); } gModuleDrawAlpha = 255; ofFill(); if (TheSynth->ShouldAccentuateActiveModules() && GetParent() == nullptr) { ofSetColor(0, 0, 0, ofMap(highlight, 0, .1f, 200, 0, K(clamp))); ofRect(0, -titleBarHeight, w, h + titleBarHeight); } ofPopMatrix(); ofPopStyle(); if (!Push2Control::sDrawingPush2Display) { for (auto source : mPatchCableSources) { source->UpdatePosition(false); source->DrawSource(); } } } void IDrawableModule::RenderUnclipped() { if (!mShowing) return; ofPushMatrix(); ofPushStyle(); ofTranslate(mX, mY, 0); ofColor color = GetColor(mModuleCategory); ofSetColor(color); DrawModuleUnclipped(); ofPopMatrix(); ofPopStyle(); } void IDrawableModule::DrawPatchCables(bool parentMinimized, bool inFront) { for (auto source : mPatchCableSources) { ConnectionType type = source->GetConnectionType(); bool isHeld = false; if (PatchCable::sActivePatchCable != nullptr) isHeld = (PatchCable::sActivePatchCable->GetOwner() == source); bool shouldDrawInFront = isHeld || (type != kConnectionType_Note && type != kConnectionType_Pulse && type != kConnectionType_Audio); if (type == kConnectionType_Pulse) { for (auto const cable : source->GetPatchCables()) { if (cable->GetTarget() != nullptr && dynamic_cast<IUIControl*>(cable->GetTarget()) != nullptr) { shouldDrawInFront = true; break; } } } if ((inFront && !shouldDrawInFront) || (!inFront && shouldDrawInFront)) continue; source->UpdatePosition(parentMinimized); source->DrawCables(parentMinimized); } } //static ofColor IDrawableModule::GetColor(ModuleCategory type) { ofColor color; color.setHsb(0, 0, sBrightness); if (type == kModuleCategory_Note) color.setHsb(sHueNote, sSaturation, sBrightness); if (type == kModuleCategory_Synth) color.setHsb(sHueInstrument, sSaturation, sBrightness); if (type == kModuleCategory_Audio) color.setHsb(sHueAudio, sSaturation, sBrightness); if (type == kModuleCategory_Instrument) color.setHsb(sHueNoteSource, sSaturation, sBrightness); if (type == kModuleCategory_Processor) color.setHsb(170, 100, 255); if (type == kModuleCategory_Modulator) color.setHsb(200, 100, 255); if (type == kModuleCategory_Pulse) color.setHsb(43, sSaturation, sBrightness); return color; } void IDrawableModule::DrawConnection(IClickable* target) { float lineWidth = 1; float plugWidth = 4; int lineAlpha = 100; IDrawableModule* targetModule = dynamic_cast<IDrawableModule*>(target); bool fatCable = false; if (TheSynth->GetLastClickedModule() == this || TheSynth->GetLastClickedModule() == targetModule) fatCable = true; if (fatCable) { lineWidth = 3; plugWidth = 8; lineAlpha = 255; } ofPushMatrix(); ofPushStyle(); PatchCableOld cable = GetPatchCableOld(target); ofColor lineColor = GetColor(kModuleCategory_Other); lineColor.setBrightness(lineColor.getBrightness() * .8f); ofColor lineColorAlphaed = lineColor; lineColorAlphaed.a = lineAlpha; float wThis, hThis, xThis, yThis; GetDimensions(wThis, hThis); GetPosition(xThis, yThis); ofSetLineWidth(plugWidth); ofSetColor(lineColor); ofLine(cable.plug.x, cable.plug.y, cable.end.x, cable.end.y); ofSetLineWidth(lineWidth); ofSetColor(lineColorAlphaed); ofLine(cable.start.x, cable.start.y, cable.plug.x, cable.plug.y); ofPopStyle(); ofPopMatrix(); } void IDrawableModule::SetTarget(IClickable* target) { if (!mPatchCableSources.empty()) mPatchCableSources[0]->SetTarget(target); } void IDrawableModule::SetUpPatchCables(std::string targets) { PatchCableSource* source = GetPatchCableSource(); assert(source != nullptr); std::vector<std::string> targetVec = ofSplitString(targets, ","); if (targetVec.empty() || targets == "") { source->Clear(); } else { for (int i = 0; i < targetVec.size(); ++i) { IClickable* target = dynamic_cast<IClickable*>(TheSynth->FindModule(targetVec[i])); if (target) source->AddPatchCable(target); } } } void IDrawableModule::AddPatchCableSource(PatchCableSource* source) { mPatchCableSources.push_back(source); } void IDrawableModule::RemovePatchCableSource(PatchCableSource* source) { RemoveFromVector(source, mPatchCableSources); delete source; } void IDrawableModule::Exit() { for (auto source : mPatchCableSources) { source->Clear(); } } bool IDrawableModule::TestClick(float x, float y, bool right, bool testOnly /*=false*/) { if (IsResizable() && mHoveringOverResizeHandle) { if (!testOnly) TheSynth->SetResizeModule(this); return true; } for (auto source : mPatchCableSources) { if (source->TestClick(x, y, right, testOnly)) return true; } if (IClickable::TestClick(x, y, right, testOnly)) return true; return false; } void IDrawableModule::OnClicked(float x, float y, bool right) { float w, h; GetModuleDimensions(w, h); if (IsResizable() && mHoveringOverResizeHandle) { TheSynth->SetResizeModule(this); return; } if (y < 0) { if (mEnabledCheckbox && x < 20) { //"enabled" area } else if (x < GetMinimizedWidth() && CanMinimize()) { mWasMinimizeAreaClicked = true; return; } else if (!Minimized() && IsSaveable()) { if (x > w - 10) { if (TheSaveDataPanel->GetModule() == this) TheSaveDataPanel->SetModule(nullptr); else TheSaveDataPanel->SetModule(this); } else if (x > w - 30 && mKeyboardFocusListener != nullptr && mKeyboardFocusListener->CanTakeFocus()) { IKeyboardFocusListener::SetActiveKeyboardFocus(mKeyboardFocusListener); } } } for (int i = 0; i < mUIControls.size(); ++i) { if (mUIControls[i]->TestClick(x, y, right)) break; } for (int i = 0; i < mChildren.size(); ++i) { if (mChildren[i]->TestClick(x, y, right)) break; } for (auto* seq : ControlSequencer::sControlSequencers) { for (int i = 0; i < mUIControls.size(); ++i) { if (mUIControls[i] == seq->GetUIControl()) TheSynth->MoveToFront(seq); } } TheSynth->MoveToFront(this); } bool IDrawableModule::MouseMoved(float x, float y) { float w, h; GetModuleDimensions(w, h); if (mShowing && !Minimized() && IsResizable() && x > w - sResizeCornerSize && y > h - sResizeCornerSize && x <= w && y <= h) mHoveringOverResizeHandle = true; else mHoveringOverResizeHandle = false; if (!mShowing) return false; for (auto source : mPatchCableSources) source->NotifyMouseMoved(x, y); if (Minimized()) return false; for (int i = 0; i < mUIControls.size(); ++i) mUIControls[i]->NotifyMouseMoved(x, y); for (int i = 0; i < mChildren.size(); ++i) mChildren[i]->NotifyMouseMoved(x, y); return false; } void IDrawableModule::MouseReleased() { mWasMinimizeAreaClicked = false; for (int i = 0; i < mUIControls.size(); ++i) mUIControls[i]->MouseReleased(); for (int i = 0; i < mChildren.size(); ++i) mChildren[i]->MouseReleased(); auto sources = mPatchCableSources; for (auto source : sources) source->MouseReleased(); } IUIControl* IDrawableModule::FindUIControl(const char* name, bool fail /*=true*/) const { if (name != 0) { for (int i = 0; i < mUIControls.size(); ++i) { if (strcmp(mUIControls[i]->Name(), name) == 0) return mUIControls[i]; } for (int i = 0; i < mUIGrids.size(); ++i) { if (strcmp(mUIGrids[i]->Name(), name) == 0) return mUIGrids[i]; } } if (fail) throw UnknownUIControlException(); return nullptr; } IDrawableModule* IDrawableModule::FindChild(const char* name, bool fail) const { for (int i = 0; i < mChildren.size(); ++i) { if (strcmp(mChildren[i]->Name(), name) == 0) return mChildren[i]; } if (fail) throw UnknownModuleException(name); return nullptr; } void IDrawableModule::AddChild(IDrawableModule* child) { if (dynamic_cast<IDrawableModule*>(child->GetParent())) dynamic_cast<IDrawableModule*>(child->GetParent())->RemoveChild(child); child->SetParent(this); if (child->Name()[0] == 0) child->SetName(("child" + ofToString(mChildren.size())).c_str()); for (int i = 0; i < mChildren.size(); ++i) { if (strcmp(mChildren[i]->Name(), child->Name()) == 0) { child->SetName(GetUniqueName(child->Name(), mChildren).c_str()); break; } } mChildren.push_back(child); } void IDrawableModule::RemoveChild(IDrawableModule* child) { child->SetParent(nullptr); RemoveFromVector(child, mChildren); } std::vector<IUIControl*> IDrawableModule::GetUIControls() const { std::vector<IUIControl*> controls = mUIControls; for (int i = 0; i < mChildren.size(); ++i) { std::vector<IUIControl*> childControls = mChildren[i]->GetUIControls(); controls.insert(controls.end(), childControls.begin(), childControls.end()); } return controls; } std::vector<UIGrid*> IDrawableModule::GetUIGrids() const { std::vector<UIGrid*> grids = mUIGrids; for (int i = 0; i < mChildren.size(); ++i) { std::vector<UIGrid*> childGrids = mChildren[i]->GetUIGrids(); grids.insert(grids.end(), childGrids.begin(), childGrids.end()); } return grids; } void IDrawableModule::GetDimensions(float& width, float& height) { int minimizedWidth = GetMinimizedWidth(); int minimizedHeight = 0; float moduleWidth, moduleHeight; GetModuleDimensions(moduleWidth, moduleHeight); if (moduleWidth == 1 && moduleHeight == 1) { width = 1; height = 1; return; //special case for repatch stub, let it be 1 pixel } ofVec2f minimumDimensions = GetMinimumDimensions(); moduleWidth = MAX(moduleWidth, minimumDimensions.x); moduleHeight = MAX(moduleHeight, minimumDimensions.y); width = EaseIn(moduleWidth, minimizedWidth, mMinimizeAnimation); height = EaseOut(moduleHeight, minimizedHeight, mMinimizeAnimation); } float IDrawableModule::GetMinimizedWidth() { std::string titleLabel = GetTitleLabel(); if (titleLabel != mLastTitleLabel) { mLastTitleLabel = titleLabel; mTitleLabelWidth = gFont.GetStringWidth(GetTitleLabel(), 14); } float width = mTitleLabelWidth; width += 10; //padding if (mEnabledCheckbox) width += TitleBarHeight(); return MAX(width, 50); } ofVec2f IDrawableModule::GetMinimumDimensions() { return ofVec2f(GetMinimizedWidth() + 10, 10); } void IDrawableModule::KeyPressed(int key, bool isRepeat) { for (auto source : mPatchCableSources) source->KeyPressed(key, isRepeat); for (auto control : mUIControls) control->KeyPressed(key, isRepeat); } void IDrawableModule::KeyReleased(int key) { } void IDrawableModule::AddUIControl(IUIControl* control) { try { std::string name = control->Name(); if (CanModuleTypeSaveState() && name.empty() == false) { IUIControl* dupe = FindUIControl(name.c_str(), false); if (dupe != nullptr) { if (dynamic_cast<ClickButton*>(control) != nullptr && dynamic_cast<ClickButton*>(dupe) != nullptr) { //they're both just buttons, this is fine } else if (!dupe->GetShouldSaveState()) { //we're duplicating the name of a non-saving ui control, assume that we are also not saving (hopefully that's true), and this is fine } else { assert(false); //can't have multiple ui controls with the same name! } } } } catch (UnknownUIControlException& e) { } mUIControls.push_back(control); FloatSlider* slider = dynamic_cast<FloatSlider*>(control); if (slider) { mSliderMutex.lock(); mFloatSliders.push_back(slider); mSliderMutex.unlock(); } } void IDrawableModule::RemoveUIControl(IUIControl* control, bool cleanUpReferences /* = true */) { if (cleanUpReferences) IUIControl::DestroyCablesTargetingControls(std::vector<IUIControl*>{ control }); RemoveFromVector(control, mUIControls, K(fail)); FloatSlider* slider = dynamic_cast<FloatSlider*>(control); if (slider) { mSliderMutex.lock(); RemoveFromVector(slider, mFloatSliders, K(fail)); mSliderMutex.unlock(); } } void IDrawableModule::AddUIGrid(UIGrid* grid) { mUIGrids.push_back(grid); } void IDrawableModule::ComputeSliders(int samplesIn) { //mSliderMutex.lock(); TODO(Ryan) mutex acquisition is slow, how can I do this faster? for (int i = 0; i < mFloatSliders.size(); ++i) mFloatSliders[i]->Compute(samplesIn); //mSliderMutex.unlock(); } PatchCableOld IDrawableModule::GetPatchCableOld(IClickable* target) { float wThis, hThis, xThis, yThis, wThat, hThat, xThat, yThat; GetDimensions(wThis, hThis); GetPosition(xThis, yThis); if (target) { target->GetDimensions(wThat, hThat); target->GetPosition(xThat, yThat); } else { wThat = 0; hThat = 0; xThat = xThis + wThis / 2; yThat = yThis + hThis + 20; } ofTranslate(-xThis, -yThis); if (HasTitleBar()) { yThis -= mTitleBarHeight; hThis += mTitleBarHeight; } IDrawableModule* targetModule = dynamic_cast<IDrawableModule*>(target); if (targetModule && targetModule->HasTitleBar()) { yThat -= mTitleBarHeight; hThat += mTitleBarHeight; } float startX, startY, endX, endY; FindClosestSides(xThis, yThis, wThis, hThis, xThat, yThat, wThat, hThat, startX, startY, endX, endY); float diffX = endX - startX; float diffY = endY - startY; float length = sqrtf(diffX * diffX + diffY * diffY); float endCap = MIN(.5f, 20 / length); int plugX = int((startX - endX) * endCap) + endX; int plugY = int((startY - endY) * endCap) + endY; PatchCableOld cable; cable.start.x = startX; cable.start.y = startY; cable.end.x = endX; cable.end.y = endY; cable.plug.x = plugX; cable.plug.y = plugY; return cable; } void IDrawableModule::FindClosestSides(float xThis, float yThis, float wThis, float hThis, float xThat, float yThat, float wThat, float hThat, float& startX, float& startY, float& endX, float& endY, bool sidesOnly /*= false*/) { ofVec2f vDirs[4]; vDirs[0].set(-1, 0); vDirs[1].set(1, 0); vDirs[2].set(0, -1); vDirs[3].set(0, 1); ofVec2f vThis[4]; vThis[0].set(xThis, yThis + hThis / 2); //left vThis[1].set(xThis + wThis, yThis + hThis / 2); //right vThis[2].set(xThis + wThis / 2, yThis); //top vThis[3].set(xThis + wThis / 2, yThis + hThis); //bottom ofVec2f vThat[4]; vThat[0].set(xThat, yThat + hThat / 2); vThat[1].set(xThat + wThat, yThat + hThat / 2); vThat[2].set(xThat + wThat / 2, yThat); vThat[3].set(xThat + wThat / 2, yThat + hThat); float closest = FLT_MAX; int closestPair = 0; for (int i = 0; i < 4; ++i) { if (i == 2) //skip top continue; if (sidesOnly && i == 3) continue; //skip bottom for (int j = 0; j < 4; ++j) { ofVec2f vDiff = vThat[j] - vThis[i]; float distSq = vDiff.lengthSquared(); if (distSq < closest && //i/2 == j/2 && //only connect horizontal-horizontal, vertical-vertical //((i/2 == 0 && fabs(vDiff.x) > 10) || // (i/2 == 1 && fabs(vDiff.y) > 10) //) && vDiff.dot(vDirs[i]) > 0 && vDiff.dot(vDirs[j]) < 0) { closest = distSq; closestPair = i + j * 4; } } } startX = vThis[closestPair % 4].x; startY = vThis[closestPair % 4].y; endX = vThat[closestPair / 4].x; endY = vThat[closestPair / 4].y; if (endY > vThis[3].y && !sidesOnly) { startX = vThis[3].x; startY = vThis[3].y; } } void IDrawableModule::ToggleMinimized() { mMinimized = !mMinimized; if (mMinimized) { if (TheSaveDataPanel->GetModule() == this) TheSaveDataPanel->SetModule(nullptr); } } bool IDrawableModule::CheckNeedsDraw() { if (IClickable::CheckNeedsDraw()) return true; for (int i = 0; i < mUIControls.size(); ++i) { if (mUIControls[i]->CheckNeedsDraw()) return true; } for (int i = 0; i < mChildren.size(); ++i) { if (mChildren[i]->CheckNeedsDraw()) return true; } return false; } void IDrawableModule::AddDebugLine(std::string text, int maxLines) { std::vector<std::string> lines = ofSplitString(mDebugDisplayText, "\n"); mDebugDisplayText = ""; for (int i = 0; i < maxLines - 1; ++i) { int lineIndex = (int)lines.size() - (maxLines - 1) + i; if (lineIndex >= 0) mDebugDisplayText += lines[lineIndex] + "\n"; } mDebugDisplayText += text; ofLog() << text; } void IDrawableModule::LoadBasics(const ofxJSONElement& moduleInfo, std::string typeName) { int x = 0; int y = 0; std::string name = "error"; bool start_minimized = false; bool draw_lissajous = false; try { x = moduleInfo["position"][0u].asInt(); y = moduleInfo["position"][1u].asInt(); name = moduleInfo["name"].asString(); start_minimized = moduleInfo["start_minimized"].asBool(); draw_lissajous = moduleInfo["draw_lissajous"].asBool(); } catch (Json::LogicError& e) { TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } SetPosition(x, y); SetName(name.c_str()); SetMinimized(start_minimized, false); if (draw_lissajous) TheSynth->AddLissajousDrawer(this); mTypeName = typeName; } void IDrawableModule::LoadLayoutBase(const ofxJSONElement& moduleInfo) { LoadLayout(moduleInfo); ITimeListener* timeListener = dynamic_cast<ITimeListener*>(this); if (timeListener) { mModuleSaveData.LoadInt("transport_priority", moduleInfo, timeListener->mTransportPriority, -9999, 9999, K(isTextField)); timeListener->mTransportPriority = mModuleSaveData.GetInt("transport_priority"); } } void IDrawableModule::SaveLayoutBase(ofxJSONElement& moduleInfo) { moduleInfo["position"][0u] = mX; moduleInfo["position"][1u] = mY; moduleInfo["name"] = Name(); moduleInfo["type"] = mTypeName; if (mMinimized) moduleInfo["start_minimized"] = true; if (TheSynth->IsLissajousDrawer(this)) moduleInfo["draw_lissajous"] = true; mModuleSaveData.Save(moduleInfo); SaveLayout(moduleInfo); } void IDrawableModule::SetUpFromSaveDataBase() { ITimeListener* timeListener = dynamic_cast<ITimeListener*>(this); if (timeListener) timeListener->mTransportPriority = mModuleSaveData.GetInt("transport_priority"); SetUpFromSaveData(); } namespace { const int kBaseSaveStateRev = 2; const int kControlSeparatorLength = 16; const char kControlSeparator[kControlSeparatorLength + 1] = "controlseparator"; } void IDrawableModule::SaveState(FileStreamOut& out) { if (!CanModuleTypeSaveState()) return; out << GetModuleSaveStateRev(); out << kBaseSaveStateRev; std::vector<IUIControl*> controlsToSave; for (auto* control : mUIControls) { if (!VectorContains(control, ControlsToIgnoreInSaveState()) && control->GetShouldSaveState()) controlsToSave.push_back(control); } out << (int)controlsToSave.size(); for (auto* control : controlsToSave) { //ofLog() << "Saving control " << control->Name(); out << std::string(control->Name()); out << control->GetValue(); //save raw value to make it easier to port old values when we change versions control->SaveState(out); for (int i = 0; i < kControlSeparatorLength; ++i) out << kControlSeparator[i]; } if (GetContainer()) { GetContainer()->SaveState(out); } else { out << (int)mChildren.size(); for (auto* child : mChildren) { out << std::string(child->Name()); child->SaveState(out); } } if (ShouldSavePatchCableSources()) { out << (int)mPatchCableSources.size(); for (auto* cable : mPatchCableSources) cable->SaveState(out); } else { out << 0; //no patch cable sources } } int IDrawableModule::LoadModuleSaveStateRev(FileStreamIn& in) { int rev = -1; if (CanModuleTypeSaveState() && ModularSynth::sLoadingFileSaveStateRev >= 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); return rev; } void IDrawableModule::LoadState(FileStreamIn& in, int rev) { if (!CanModuleTypeSaveState()) return; if (rev != -1 && ModularSynth::sLoadingFileSaveStateRev >= 423) { int moduleRev; in >> moduleRev; LoadStateValidate(moduleRev == rev); } int baseRev; in >> baseRev; int numUIControls; in >> numUIControls; for (int i = 0; i < numUIControls; ++i) { std::string uicontrolname; in >> uicontrolname; if (baseRev >= 2) { float rawValue; in >> rawValue; //we don't use this here, but it'll likely be useful in the future if an option is renamed/removed and we need to port the old data } UpdateOldControlName(uicontrolname); bool threwException = false; try { if (LoadOldControl(in, uicontrolname)) { //old data loaded, we're good now! } else { //ofLog() << "loading control " << uicontrolname; auto* control = FindUIControl(uicontrolname.c_str(), false); if (control == nullptr) throw UnknownUIControlException(); bool setValue = true; if (VectorContains(control, ControlsToNotSetDuringLoadState())) setValue = false; control->LoadState(in, setValue); } for (int j = 0; j < kControlSeparatorLength; ++j) { char separatorChar; in >> separatorChar; if (separatorChar != kControlSeparator[j]) { ofLog() << "Error loading state for " << uicontrolname; //something went wrong, let's print some info to try to figure it out ofLog() << "Read char " + ofToString(separatorChar) + " but expected " + kControlSeparator[j] + "!"; ofLog() << "Save state file position is " + ofToString(in.GetFilePosition()) + ", EoF is " + (in.Eof() ? "true" : "false"); std::string nextFewChars = "Next 10 characters are:"; for (int c = 0; c < 10; ++c) { char ch; in >> ch; nextFewChars += ofToString(ch); } ofLog() << nextFewChars; } assert(separatorChar == kControlSeparator[j]); } } catch (UnknownUIControlException& e) { threwException = true; } catch (LoadStateException& e) { threwException = true; } if (threwException) { TheSynth->LogEvent("Error in module \"" + std::string(Name()) + "\" loading state for control \"" + uicontrolname + "\"", kLogEventType_Error); //read through the rest of the module until we find the spacer, so we can continue loading the next module int separatorProgress = 0; while (!in.Eof()) { char val; in >> val; if (val == kControlSeparator[separatorProgress]) ++separatorProgress; else separatorProgress = 0; if (separatorProgress == kControlSeparatorLength) break; //we did it! } } } if (GetContainer()) GetContainer()->LoadState(in); if (!GetContainer() || ModularSynth::sLoadingFileSaveStateRev < 425) { int numChildren; in >> numChildren; LoadStateValidate(numChildren <= mChildren.size()); for (int i = 0; i < numChildren; ++i) { std::string childName; in >> childName; //ofLog() << "Loading " << childName; IDrawableModule* child = FindChild(childName.c_str(), true); LoadStateValidate(child); child->LoadState(in, child->LoadModuleSaveStateRev(in)); } } if (baseRev >= 1) { int numPatchCableSources; in >> numPatchCableSources; PatchCableSource* dummy = nullptr; for (int i = 0; i < numPatchCableSources; ++i) { PatchCableSource* readIn; if (i < mPatchCableSources.size()) { readIn = mPatchCableSources[i]; } else { if (dummy == nullptr) dummy = new PatchCableSource(this, kConnectionType_Special); readIn = dummy; } readIn->LoadState(in); } } } std::vector<IUIControl*> IDrawableModule::ControlsToNotSetDuringLoadState() const { return std::vector<IUIControl*>(); //empty } std::vector<IUIControl*> IDrawableModule::ControlsToIgnoreInSaveState() const { return std::vector<IUIControl*>(); //empty } bool IDrawableModule::IsSpawningOnTheFly(const ofxJSONElement& moduleInfo) { if (moduleInfo["onthefly"].isNull()) return false; return moduleInfo["onthefly"].asBool(); } ```
/content/code_sandbox/Source/IDrawableModule.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
11,097
```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 **/ // // Polyrhythms.cpp // modularSynth // // Created by Ryan Challinor on 3/12/13. // // #include "Polyrhythms.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Profiler.h" #include "DrumPlayer.h" Polyrhythms::Polyrhythms() { mHeight = mRhythmLines.size() * 17 + 5; } void Polyrhythms::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } void Polyrhythms::CreateUIControls() { IDrawableModule::CreateUIControls(); for (int i = 0; i < (int)mRhythmLines.size(); ++i) { mRhythmLines[i] = new RhythmLine(this, i); mRhythmLines[i]->CreateUIControls(); } } Polyrhythms::~Polyrhythms() { TheTransport->RemoveAudioPoller(this); for (int i = 0; i < mRhythmLines.size(); ++i) delete mRhythmLines[i]; } void Polyrhythms::OnTransportAdvanced(float amount) { PROFILER(Polyrhythms); if (!mEnabled) return; double time = NextBufferTime(true); for (int i = 0; i < mRhythmLines.size(); ++i) { int beats = mRhythmLines[i]->mGrid->GetCols(); TransportListenerInfo info(nullptr, kInterval_CustomDivisor, OffsetInfo(0, false), false); info.mCustomDivisor = beats; double remainderMs; int oldStep = TheTransport->GetQuantized(NextBufferTime(true) - gBufferSizeMs, &info); int newStep = TheTransport->GetQuantized(NextBufferTime(true), &info, &remainderMs); float val = mRhythmLines[i]->mGrid->GetVal(newStep, 0); if (newStep != oldStep && val > 0) PlayNoteOutput(time - remainderMs, mRhythmLines[i]->mPitch, val * 127, -1); mRhythmLines[i]->mGrid->SetHighlightCol(time, newStep); } } void Polyrhythms::DrawModule() { if (Minimized() || IsVisible() == false) return; for (int i = 0; i < mRhythmLines.size(); ++i) mRhythmLines[i]->Draw(); } void Polyrhythms::Resize(float w, float h) { mWidth = MAX(150, w); mHeight = mRhythmLines.size() * 17 + 5; for (int i = 0; i < mRhythmLines.size(); ++i) mRhythmLines[i]->OnResize(); } void Polyrhythms::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); for (int i = 0; i < mRhythmLines.size(); ++i) mRhythmLines[i]->OnClicked(x, y, right); } void Polyrhythms::MouseReleased() { IDrawableModule::MouseReleased(); for (int i = 0; i < mRhythmLines.size(); ++i) mRhythmLines[i]->MouseReleased(); } bool Polyrhythms::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); for (int i = 0; i < mRhythmLines.size(); ++i) mRhythmLines[i]->MouseMoved(x, y); return false; } void Polyrhythms::DropdownUpdated(DropdownList* list, int oldVal, double time) { for (int i = 0; i < mRhythmLines.size(); ++i) { if (list == mRhythmLines[i]->mLengthSelector) mRhythmLines[i]->UpdateGrid(); } } void Polyrhythms::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void Polyrhythms::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } void Polyrhythms::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); out << (int)mRhythmLines.size(); for (size_t i = 0; i < mRhythmLines.size(); ++i) mRhythmLines[i]->mGrid->SaveState(out); } void Polyrhythms::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); int size; in >> size; LoadStateValidate(size == (int)mRhythmLines.size()); for (size_t i = 0; i < mRhythmLines.size(); ++i) mRhythmLines[i]->mGrid->LoadState(in); } RhythmLine::RhythmLine(Polyrhythms* owner, int index) : mIndex(index) , mPitch(index) , mOwner(owner) { } void RhythmLine::CreateUIControls() { mGrid = new UIGrid("uigrid", 4, 4 + mIndex * 17, 100, 15, 4, 1, mOwner); mLengthSelector = new DropdownList(mOwner, ("length" + ofToString(mIndex)).c_str(), -1, -1, &mLength); mNoteSelector = new TextEntry(mOwner, ("note" + ofToString(mIndex)).c_str(), -1, -1, 4, &mPitch, 0, 127); mLengthSelector->AddLabel("3", 3); mLengthSelector->AddLabel("4", 4); mLengthSelector->AddLabel("5", 5); mLengthSelector->AddLabel("6", 6); mLengthSelector->AddLabel("7", 7); mLengthSelector->AddLabel("8", 8); mLengthSelector->AddLabel("9", 9); mLengthSelector->AddLabel("3x4", 12); mLengthSelector->AddLabel("4x4", 16); mLengthSelector->AddLabel("5x4", 20); mLengthSelector->AddLabel("6x4", 24); mLengthSelector->AddLabel("7x4", 28); mLengthSelector->AddLabel("8x4", 32); mLengthSelector->AddLabel("9x4", 36); mGrid->SetGridMode(UIGrid::kMultisliderBipolar); mGrid->SetRequireShiftForMultislider(true); OnResize(); } void RhythmLine::OnResize() { mGrid->SetDimensions(mOwner->IClickable::GetDimensions().x - 100, 15); mLengthSelector->PositionTo(mGrid, kAnchor_Right); mNoteSelector->PositionTo(mLengthSelector, kAnchor_Right); } void RhythmLine::UpdateGrid() { mGrid->SetGrid(mLength, 1); if (mLength % 4 == 0) mGrid->SetMajorColSize(mLength / 4); else mGrid->SetMajorColSize(-1); } void RhythmLine::Draw() { mGrid->Draw(); mLengthSelector->Draw(); mNoteSelector->Draw(); } void RhythmLine::OnClicked(float x, float y, bool right) { if (right) return; mGrid->TestClick(x, y, right); } void RhythmLine::MouseReleased() { mGrid->MouseReleased(); } void RhythmLine::MouseMoved(float x, float y) { mGrid->NotifyMouseMoved(x, y); } ```
/content/code_sandbox/Source/Polyrhythms.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,870
```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 **/ // // EnvOscillator.h // additiveSynth // // Created by Ryan Challinor on 11/20/12. // // #pragma once #include "SynthGlobals.h" #include "ADSR.h" #include "Oscillator.h" class EnvOscillator { public: EnvOscillator(OscillatorType type) : mOsc(type) {} void SetType(OscillatorType type) { mOsc.SetType(type); } void SetADSR(float a, float d, float s, float r) { mAdsr.Set(a, d, s, r); } void Start(double time, float target) { mAdsr.Start(time, target); } void Start(double time, float target, float a, float d, float s, float r) { mAdsr.Start(time, target, a, d, s, r); } void Start(double time, float target, ::ADSR adsr) { mAdsr.Set(adsr); mAdsr.Start(time, target); } void Stop(double time) { mAdsr.Stop(time); } float Audio(double time, float phase); ::ADSR* GetADSR() { return &mAdsr; } void SetPulseWidth(float width) { mOsc.SetPulseWidth(width); } Oscillator mOsc{ OscillatorType::kOsc_Sin }; private: ::ADSR mAdsr; float mPulseWidth{ .5 }; }; ```
/content/code_sandbox/Source/EnvOscillator.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
423
```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 **/ // // Looper.cpp // modularSynth // // Created by Ryan Challinor on 11/25/12. // // #include "Looper.h" #include "SynthGlobals.h" #include "Transport.h" #include "OpenFrameworksPort.h" #include "LooperRecorder.h" #include "Sample.h" #include "MidiController.h" #include "ModularSynth.h" #include "Profiler.h" #include "Rewriter.h" #include "LooperGranulator.h" float Looper::mBeatwheelPosRight = 0; float Looper::mBeatwheelDepthRight = 0; float Looper::mBeatwheelPosLeft = 0; float Looper::mBeatwheelDepthLeft = 0; bool Looper::mBeatwheelSingleMeasure = 0; namespace { const int kMaxNumBars = 16; } Looper::Looper() : IAudioProcessor(gBufferSize) , mWorkBuffer(gBufferSize) { //TODO(Ryan) buffer sizes mBuffer = new ChannelBuffer(MAX_BUFFER_SIZE); mUndoBuffer = new ChannelBuffer(MAX_BUFFER_SIZE); Clear(); mMuteRamp.SetValue(1); for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i) { mPitchShifter[i] = new PitchShifter(1024); mLastInputSample[i] = 0; } SetLoopLength(4 * 60.0f / TheTransport->GetTempo() * gSampleRate); } void Looper::CreateUIControls() { IDrawableModule::CreateUIControls(); mNumBarsSelector = new DropdownList(this, "num bars", 3, 3, &mNumBars); mClearButton = new ClickButton(this, "clear", -1, -1); mVolSlider = new FloatSlider(this, "volume", 3, 98, 130, 15, &mVol, 0, 2); mWriteInputCheckbox = new Checkbox(this, "write", 80, 3, &mWriteInput); mCommitButton = new ClickButton(this, "commit", 126, 3); mQueueCaptureButton = new ClickButton(this, "capture", 126, 3); mMuteCheckbox = new Checkbox(this, "mute", -1, -1, &mMute); mPassthroughCheckbox = new Checkbox(this, "passthrough", -1, -1, &mPassthrough); mUndoButton = new ClickButton(this, "undo", -1, -1); mAllowScratchCheckbox = new Checkbox(this, "scr", -1, -1, &mAllowScratch); mVolumeBakeButton = new ClickButton(this, "b", -1, -1); mMergeButton = new ClickButton(this, " m ", -1, -1); mDecaySlider = new FloatSlider(this, "decay", -1, -1, 65, 15, &mDecay, 0, 1, 2); mSaveButton = new ClickButton(this, "save", -1, -1); mSwapButton = new ClickButton(this, "swap", 137, 81); mCopyButton = new ClickButton(this, "copy", 140, 65); mDoubleSpeedButton = new ClickButton(this, "2x", 127, 19); mHalveSpeedButton = new ClickButton(this, ".5x", 149, 19); mExtendButton = new ClickButton(this, "extend", 127, 34); mLoopPosOffsetSlider = new FloatSlider(this, "offset", -1, -1, 130, 15, &mLoopPosOffset, 0, mLoopLength); mWriteOffsetButton = new ClickButton(this, "apply", -1, -1); mScratchSpeedSlider = new FloatSlider(this, "scrspd", -1, -1, 130, 15, &mScratchSpeed, -2, 2); mFourTetSlider = new FloatSlider(this, "fourtet", 4, 65, 65, 15, &mFourTet, 0, 1, 1); mFourTetSlicesDropdown = new DropdownList(this, "fourtetslices", -1, -1, &mFourTetSlices); mPitchShiftSlider = new FloatSlider(this, "pitch", -1, -1, 130, 15, &mPitchShift, .5f, 2); mBeatwheelCheckbox = new Checkbox(this, "beatwheel on", HIDDEN_UICONTROL, HIDDEN_UICONTROL, &mBeatwheel); mBeatwheelPosRightSlider = new FloatSlider(this, "beatwheel pos right", HIDDEN_UICONTROL, HIDDEN_UICONTROL, 1, 1, &mBeatwheelPosRight, 0, 1); mBeatwheelDepthRightSlider = new FloatSlider(this, "beatwheel depth right", HIDDEN_UICONTROL, HIDDEN_UICONTROL, 1, 1, &mBeatwheelDepthRight, 0, 1); mBeatwheelPosLeftSlider = new FloatSlider(this, "beatwheel pos left", HIDDEN_UICONTROL, HIDDEN_UICONTROL, 1, 1, &mBeatwheelPosLeft, 0, 1); mBeatwheelDepthLeftSlider = new FloatSlider(this, "beatwheel depth left", HIDDEN_UICONTROL, HIDDEN_UICONTROL, 1, 1, &mBeatwheelDepthLeft, 0, 1); mBeatwheelSingleMeasureCheckbox = new Checkbox(this, "beatwheel single measure", HIDDEN_UICONTROL, HIDDEN_UICONTROL, &mBeatwheelSingleMeasure); mKeepPitchCheckbox = new Checkbox(this, "auto", -1, -1, &mKeepPitch); mResampleButton = new ClickButton(this, "resample for tempo", 15, 40); mNumBarsSelector->AddLabel(" 1 ", 1); mNumBarsSelector->AddLabel(" 2 ", 2); mNumBarsSelector->AddLabel(" 3 ", 3); mNumBarsSelector->AddLabel(" 4 ", 4); mNumBarsSelector->AddLabel(" 6 ", 6); mNumBarsSelector->AddLabel(" 8 ", 8); mNumBarsSelector->AddLabel("12 ", 12); mNumBarsSelector->AddLabel("16 ", 16); static_assert(kMaxNumBars == 16); mFourTetSlicesDropdown->AddLabel(" 1", 1); mFourTetSlicesDropdown->AddLabel(" 2", 2); mFourTetSlicesDropdown->AddLabel(" 4", 4); mFourTetSlicesDropdown->AddLabel(" 8", 8); mFourTetSlicesDropdown->AddLabel("16", 16); mBeatwheelPosLeftSlider->SetClamped(false); mBeatwheelPosRightSlider->SetClamped(false); mDecaySlider->SetMode(FloatSlider::kSquare); mClearButton->PositionTo(mNumBarsSelector, kAnchor_Right); mVolumeBakeButton->PositionTo(mVolSlider, kAnchor_Right); mMergeButton->PositionTo(mVolumeBakeButton, kAnchor_Right); mDecaySlider->PositionTo(mNumBarsSelector, kAnchor_Below); mFourTetSlicesDropdown->PositionTo(mFourTetSlider, kAnchor_Right); mMuteCheckbox->PositionTo(mFourTetSlider, kAnchor_Below); mSaveButton->PositionTo(mMuteCheckbox, kAnchor_Right); mUndoButton->PositionTo(mSaveButton, kAnchor_Right); mPitchShiftSlider->PositionTo(mVolSlider, kAnchor_Below); mKeepPitchCheckbox->PositionTo(mPitchShiftSlider, kAnchor_Right); mLoopPosOffsetSlider->PositionTo(mPitchShiftSlider, kAnchor_Below); mWriteOffsetButton->PositionTo(mLoopPosOffsetSlider, kAnchor_Right); mScratchSpeedSlider->PositionTo(mLoopPosOffsetSlider, kAnchor_Below); mAllowScratchCheckbox->PositionTo(mScratchSpeedSlider, kAnchor_Right); mPassthroughCheckbox->PositionTo(mScratchSpeedSlider, kAnchor_Below); } Looper::~Looper() { delete mBuffer; delete mUndoBuffer; for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i) delete mPitchShifter[i]; } void Looper::Exit() { IDrawableModule::Exit(); if (mRecorder) mRecorder->RemoveLooper(this); } void Looper::SetRecorder(LooperRecorder* recorder) { mRecorder = recorder; if (recorder) GetBuffer()->SetNumActiveChannels(recorder->GetRecordBuffer()->NumChannels()); } ChannelBuffer* Looper::GetLoopBuffer(int& loopLength) { loopLength = mLoopLength; return mBuffer; } void Looper::SetLoopBuffer(ChannelBuffer* buffer) { mQueuedNewBuffer = buffer; } void Looper::Poll() { if (mClearCommitBuffer) { if (mRecorder == nullptr) mCommitBuffer->ClearBuffer(); mCommitBuffer = nullptr; mClearCommitBuffer = false; } mCommitButton->SetShowing(mRecorder != nullptr); mSwapButton->SetShowing(mRecorder != nullptr); mCopyButton->SetShowing(mRecorder != nullptr); mMergeButton->SetShowing(mRecorder != nullptr); mWriteInputCheckbox->SetShowing(mRecorder == nullptr); mQueueCaptureButton->SetShowing(mRecorder == nullptr); if (mGranulator && mGranulator->IsDeleted()) mGranulator = nullptr; } void Looper::Process(double time) { PROFILER(Looper); IAudioReceiver* target = GetTarget(); if (target == nullptr) return; if (!mEnabled) { SyncBuffers(); 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; } ComputeSliders(0); int numChannels = MAX(GetBuffer()->NumActiveChannels(), mBuffer->NumActiveChannels()); if (mRecorder) numChannels = MAX(numChannels, mRecorder->GetRecordBuffer()->NumChannels()); GetBuffer()->SetNumActiveChannels(numChannels); SyncBuffers(); mBuffer->SetNumActiveChannels(GetBuffer()->NumActiveChannels()); mWorkBuffer.SetNumActiveChannels(GetBuffer()->NumActiveChannels()); mUndoBuffer->SetNumActiveChannels(GetBuffer()->NumActiveChannels()); bool doGranular = mGranulator != nullptr && mGranulator->IsActive(); if (mWantBakeVolume) BakeVolume(); if (mWantShiftDownbeat) DoShiftDownbeat(); int bufferSize = GetBuffer()->BufferSize(); float oldLoopPos = mLoopPos; int sampsPerBar = mLoopLength / mNumBars; if (!doGranular || !mGranulator->ShouldFreeze()) mLoopPos = sampsPerBar * ((TheTransport->GetMeasure(time) % mNumBars) + TheTransport->GetMeasurePos(time)); double speed = GetPlaybackSpeed(); if (oldLoopPos > mLoopLength - bufferSize * speed - 1 && mLoopPos < oldLoopPos) { ++mLoopCount; /*if (mLoopCount > 6 && mMute == false && mDecay) mVol *= ofMap(TheTransport->GetTempo(), 80.0f, 160.0f, .95f, .99f, true);*/ if (mMute == false) mVol *= 1 - mDecay; if (mCaptureQueued && !mWriteInput) { mWriteInputRamp.Start(time, 1, time + 10); mWriteInput = true; } else if (mWriteInput && mCaptureQueued) { mCaptureQueued = false; mWriteInputRamp.Start(time, 0, time + 10); mWriteInput = false; } } if (speed == 1) { //TODO(Ryan) reevaluate //mLoopPos = int(mLoopPos); //fix in-between sample error } else { mAllowScratch = false; } if (mQueuedNewBuffer) { mBufferMutex.lock(); for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) mJumpBlender[ch].CaptureForJump(mLoopPos, mBuffer->GetChannel(ch), mLoopLength, 0); mBuffer = mQueuedNewBuffer; mBufferMutex.unlock(); mQueuedNewBuffer = nullptr; } if (mKeepPitch) mPitchShift = 1 / speed; int latencyOffset = 0; if (mPitchShift != 1) latencyOffset = mPitchShifter[0]->GetLatency(); double processStartTime = time; for (int i = 0; i < bufferSize; ++i) { float smooth = .001f; mSmoothedVol = mSmoothedVol * (1 - smooth) + mVol * smooth; float volSq = mSmoothedVol * mSmoothedVol; mLoopPosOffsetSlider->Compute(i); if (mAllowScratch) ProcessScratch(); if (mFourTet > 0) ProcessFourTet(processStartTime, i); if (mBeatwheel) ProcessBeatwheel(processStartTime, i); float offset = mLoopPos + i * speed + mLoopPosOffset + latencyOffset; float output[ChannelBuffer::kMaxNumChannels]; ::Clear(output, ChannelBuffer::kMaxNumChannels); if (doGranular) mGranulator->ProcessFrame(time, offset, output); for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) { if (!doGranular) { output[ch] = GetInterpolatedSample(offset, mBuffer->GetChannel(ch), mLoopLength); output[ch] = mJumpBlender[ch].Process(output[ch], i); } if (mFourTet > 0 && mFourTet < 1) //fourtet wet/dry { output[ch] *= mFourTet; float normalOffset = mLoopPos + i * speed; output[ch] += GetInterpolatedSample(normalOffset, mBuffer->GetChannel(ch), mLoopLength) * (1 - mFourTet); } //write one sample the past so we don't end up feeding into the next output float writeAmount = mWriteInputRamp.Value(time); if (writeAmount > 0) WriteInterpolatedSample(offset - 1, mBuffer->GetChannel(ch), mLoopLength, mLastInputSample[ch] * writeAmount); mLastInputSample[ch] = GetBuffer()->GetChannel(ch)[i]; output[ch] = mSwitchAndRamp.Process(ch, output[ch] * volSq); mWorkBuffer.GetChannel(ch)[i] = output[ch] * mMuteRamp.Value(time); if (mPassthrough) GetVizBuffer()->Write(mWorkBuffer.GetChannel(ch)[i] + GetBuffer()->GetChannel(ch)[i], ch); else GetVizBuffer()->Write(mWorkBuffer.GetChannel(ch)[i], ch); } time += gInvSampleRateMs; } if (mPitchShift != 1) { for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) { mPitchShifter[ch]->SetRatio(mPitchShift); mPitchShifter[ch]->Process(mWorkBuffer.GetChannel(ch), bufferSize); } } for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) { if (mPassthrough) Add(target->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), bufferSize); Add(target->GetBuffer()->GetChannel(ch), mWorkBuffer.GetChannel(ch), bufferSize); GetVizBuffer()->WriteChunk(target->GetBuffer()->GetChannel(ch), bufferSize, ch); } GetBuffer()->Reset(); if (mCommitBuffer && !mClearCommitBuffer && !mWantRewrite) DoCommit(time); if (mWantShiftMeasure) DoShiftMeasure(); if (mWantHalfShift) DoHalfShift(); if (mWantShiftOffset) DoShiftOffset(); if (mWantUndo) DoUndo(); if (mWantRewrite) { mWantRewrite = false; if (mRewriter) mRewriter->Go(time); } } void Looper::DoCommit(double time) { PROFILER(LooperDoCommit); assert(mCommitBuffer); { PROFILER(Looper_DoCommit_undo); mUndoBuffer->CopyFrom(mBuffer, mLoopLength); } if (mReplaceOnCommit) Clear(); if (mMute) { Clear(); mMute = false; mMuteRamp.Start(time, mMute ? 0 : 1, time + 1); } { PROFILER(LooperDoCommit_commit); int commitSamplesBack = mCommitMsOffset / gInvSampleRateMs; int commitLength = mLoopLength + LOOPER_COMMIT_FADE_SAMPLES; for (int i = 0; i < commitLength; ++i) { int idx = i - LOOPER_COMMIT_FADE_SAMPLES; int pos = int(mLoopPos + (idx * GetPlaybackSpeed()) + mLoopLength) % mLoopLength; float fade = 1; if (idx < 0) fade = float(LOOPER_COMMIT_FADE_SAMPLES + idx) / LOOPER_COMMIT_FADE_SAMPLES; if (idx >= mLoopLength - LOOPER_COMMIT_FADE_SAMPLES) fade = 1 - (float(idx - (mLoopLength - LOOPER_COMMIT_FADE_SAMPLES)) / LOOPER_COMMIT_FADE_SAMPLES); for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) { mBuffer->GetChannel(ch)[pos] += mCommitBuffer->GetSample(ofClamp(commitLength - i - commitSamplesBack, 0, MAX_BUFFER_SIZE - 1), ch) * fade; } } } mClearCommitBuffer = true; } void Looper::Fill(ChannelBuffer* buffer, int length) { mBuffer->CopyFrom(buffer, length); } void Looper::DoUndo() { ChannelBuffer* swap = mUndoBuffer; mUndoBuffer = mBuffer; mBuffer = swap; mWantUndo = false; } int Looper::GetRecorderNumBars() const { if (mRecorder) return mRecorder->GetNumBars(); return GetNumBars(); } double Looper::GetPlaybackSpeed() const { return mSpeed * TheTransport->GetTempo() / mBufferTempo; } void Looper::ProcessScratch() { mLoopPosOffset = FloatWrap(mLoopPosOffset - GetPlaybackSpeed() + mScratchSpeed, mLoopLength); } void Looper::ProcessFourTet(double time, int sampleIdx) { float measurePos = TheTransport->GetMeasurePos(time) + sampleIdx / (TheTransport->MsPerBar() / gInvSampleRateMs); measurePos += TheTransport->GetMeasure(time) % mNumBars; measurePos /= mNumBars; int numSlices = mFourTetSlices * 2 * mNumBars; measurePos *= numSlices; int slice = (int)measurePos; float sliceProgress = measurePos - slice; float oldOffset = mLoopPosOffset; if (slice % 2 == 0) mLoopPosOffset = (sliceProgress + slice / 2) * (mLoopLength / float(numSlices) * 2); else mLoopPosOffset = (1 - sliceProgress + slice / 2) * (mLoopLength / float(numSlices) * 2); //offset regular movement mLoopPosOffset = FloatWrap(mLoopPosOffset - (mLoopPos + sampleIdx * GetPlaybackSpeed()), mLoopLength); //smooth discontinuity if (oldOffset >= mLoopLength * .5f && mLoopPosOffset < mLoopLength * .5f) mSwitchAndRamp.StartSwitch(); } void Looper::ProcessBeatwheel(double time, int sampleIdx) { bool bothHeld = false; bool noneHeld = false; float clockPos = 0; if (mBeatwheelDepthRight > 0 && mBeatwheelDepthLeft > 0 && mBeatwheelPosRight >= 0 && mBeatwheelPosLeft >= 0) { if (mBeatwheelControlFlip) clockPos = mBeatwheelPosRight; else clockPos = mBeatwheelPosLeft; bothHeld = true; } else if (mBeatwheelDepthRight > 0 && mBeatwheelPosRight >= 0) { clockPos = mBeatwheelPosRight; } else if (mBeatwheelDepthLeft > 0 && mBeatwheelPosLeft >= 0) { clockPos = mBeatwheelPosLeft; } else { noneHeld = true; } int depthLevel = GetBeatwheelDepthLevel(); if (noneHeld) depthLevel = 2; int slicesPerBar = TheTransport->GetTimeSigTop() * (1 << depthLevel); int lastSlice = GetMeasureSliceIndex(time, sampleIdx - 1, slicesPerBar); int slice = GetMeasureSliceIndex(time, sampleIdx, slicesPerBar); int numSlices = slicesPerBar * mNumBars; int loopLength = mLoopLength; if (mBeatwheelSingleMeasure) { numSlices = slicesPerBar; loopLength = mLoopLength / mNumBars; } if (lastSlice != slice) //on new slices { for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) mJumpBlender[ch].CaptureForJump(int(GetActualLoopPos(sampleIdx)) % loopLength, mBuffer->GetChannel(ch), loopLength, sampleIdx); if (noneHeld) { mLoopPosOffset = 0; } else { if (bothHeld) //we should pingpong mBeatwheelControlFlip = !mBeatwheelControlFlip; int playSlice = int(clockPos * numSlices); mLoopPosOffset = playSlice * (loopLength / numSlices); //offset regular movement mLoopPosOffset = FloatWrap(mLoopPosOffset - (mLoopPos + sampleIdx * GetPlaybackSpeed()), mLoopLength); } } } int Looper::GetBeatwheelDepthLevel() const { float depth = MAX(mBeatwheelDepthLeft, mBeatwheelDepthRight); if (depth == 0) return 0; if (depth < 1) return 1; return 2; } float Looper::GetActualLoopPos(int samplesIn) const { float pos = FloatWrap(mLoopPos + mLoopPosOffset + samplesIn, mLoopLength); return pos; } int Looper::GetMeasureSliceIndex(double time, int sampleIdx, int slicesPerBar) { float measurePos = TheTransport->GetMeasurePos(time) + sampleIdx / (TheTransport->MsPerBar() / gInvSampleRateMs); measurePos += TheTransport->GetMeasure(time) % mNumBars; measurePos /= mNumBars; int numSlices = slicesPerBar * mNumBars; measurePos *= numSlices; int slice = (int)measurePos; return slice; } void Looper::ResampleForSpeed(float speed) { int oldLoopLength = mLoopLength; SetLoopLength(MIN(int(abs(mLoopLength / speed)), MAX_BUFFER_SIZE - 1)); mLoopPos /= speed; while (mLoopPos < 0) mLoopPos += mLoopLength; for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) { float* oldBuffer = new float[oldLoopLength]; BufferCopy(oldBuffer, mBuffer->GetChannel(ch), oldLoopLength); for (int i = 0; i < mLoopLength; ++i) { float offset = i * speed; mBuffer->GetChannel(ch)[i] = GetInterpolatedSample(offset, oldBuffer, oldLoopLength); } delete[] oldBuffer; } if (mKeepPitch) { mKeepPitch = false; mPitchShift = 1 / speed; } mSpeed = 1; mBufferTempo = TheTransport->GetTempo(); } namespace { const float kBufferX = 3; const float kBufferY = 3; const float kBufferWidth = 170; const float kBufferHeight = 93; } void Looper::DrawModule() { if (Minimized() || IsVisible() == false) return; ofPushMatrix(); ofTranslate(kBufferX, kBufferY); assert(mLoopLength > 0); float displayPos = GetActualLoopPos(0); mBufferMutex.lock(); DrawAudioBuffer(kBufferWidth, kBufferHeight, mBuffer, 0, mLoopLength, displayPos, mVol); mBufferMutex.unlock(); ofSetColor(255, 255, 0, gModuleDrawAlpha); for (int i = 1; i < mNumBars; ++i) { float x = kBufferWidth / mNumBars * i; ofLine(x, kBufferHeight / 2 - 5, x, kBufferHeight / 2 + 5); } ofSetColor(255, 255, 255, gModuleDrawAlpha); ofPopMatrix(); mClearButton->Draw(); mNumBarsSelector->Draw(); mVolSlider->Draw(); mVolumeBakeButton->Draw(); mDecaySlider->Draw(); mDoubleSpeedButton->Draw(); mHalveSpeedButton->Draw(); mExtendButton->Draw(); mUndoButton->Draw(); mLoopPosOffsetSlider->Draw(); mWriteOffsetButton->Draw(); mScratchSpeedSlider->Draw(); mAllowScratchCheckbox->Draw(); mFourTetSlider->Draw(); mFourTetSlicesDropdown->Draw(); mPitchShiftSlider->Draw(); mKeepPitchCheckbox->Draw(); mWriteInputCheckbox->Draw(); mQueueCaptureButton->Draw(); mResampleButton->SetShowing(mBufferTempo != TheTransport->GetTempo()); mResampleButton->Draw(); if (mCaptureQueued) { ofPushStyle(); ofFill(); if (mWriteInput) ofSetColor(255, 0, 0, 150); else ofSetColor(255, 100, 0, 100 + 50 * (cosf(TheTransport->GetMeasurePos(gTime) * 4 * FTWO_PI))); ofRect(mQueueCaptureButton->GetRect(true)); ofPopStyle(); } mMergeButton->Draw(); if (mRecorder && mRecorder->GetMergeSource() == this) { ofPushStyle(); ofFill(); ofSetColor(255, 0, 0, 100); ofRect(mMergeButton->GetRect(true)); ofPopStyle(); } mSwapButton->Draw(); if (mRecorder && mRecorder->GetSwapSource() == this) { ofPushStyle(); ofFill(); ofSetColor(0, 0, 255, 100); ofRect(mSwapButton->GetRect(true)); ofPopStyle(); } mCopyButton->Draw(); if (mRecorder && mRecorder->GetCopySource() == this) { ofPushStyle(); ofFill(); ofSetColor(0, 0, 255, 100); ofRect(mCopyButton->GetRect(true)); ofPopStyle(); } mSaveButton->Draw(); mMuteCheckbox->Draw(); mPassthroughCheckbox->Draw(); mCommitButton->Draw(); if (mGranulator) mGranulator->DrawOverlay(ofRectangle(4, 35, 155, 32), mLoopLength); if (mBeatwheel) DrawBeatwheel(); if (mRecorder != nullptr && mRecorder->GetNextCommitTarget() == this) { ofPushStyle(); float w, h; GetDimensions(w, h); ofSetColor(255, 255, 255, 200); ofSetLineWidth(3); ofRect(0, 0, w, h); ofPopStyle(); } } void Looper::DrawBeatwheel() { ofPushMatrix(); ofPushStyle(); float size = 197; ofTranslate(0, -size); ofFill(); ofSetColor(50, 50, 50, gModuleDrawAlpha * .65f); ofRect(0, 0, size, size); float centerX = size / 2; float centerY = size / 2; float innerRad = size * .2f; float outerRad = size * .45f; float waveformCenter = (innerRad + outerRad) / 2; float waveformHeight = (outerRad - innerRad) / 2; ofSetCircleResolution(100); ofSetColor(100, 100, 100, gModuleDrawAlpha * .8f); ofCircle(size / 2, size / 2, outerRad); ofSetColor(50, 50, 50, gModuleDrawAlpha * .5f); ofCircle(size / 2, size / 2, innerRad); ofSetLineWidth(1); ofNoFill(); int depthLevel = GetBeatwheelDepthLevel(); int slicesPerBar = TheTransport->GetTimeSigTop() * (1 << depthLevel); int numSlices = slicesPerBar * mNumBars; int loopLength = mLoopLength; if (mBeatwheelSingleMeasure) { numSlices = slicesPerBar; loopLength = mLoopLength / mNumBars; } ofSetColor(0, 0, 0, gModuleDrawAlpha); float subdivisions = 600; int samplesPerPixel = loopLength / subdivisions; for (int i = 0; i < subdivisions; i++) { float radians = (i * TWO_PI) / subdivisions; //ofSetColor(200,200,200,gModuleDrawAlpha); float sinR = sin(radians); float cosR = cos(radians); //ofLine(centerX+sinR*innerRad, centerY-cosR*innerRad, centerX+sinR*outerRad, centerY-cosR*outerRad); float mag = 0; int position = i * samplesPerPixel; //rms int j; for (j = 0; j < samplesPerPixel && position + j < loopLength - 1; ++j) { for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) mag += mBuffer->GetChannel(ch)[position + j]; } mag /= j; mag = sqrtf(mag); mag = sqrtf(mag); mag = MIN(1.0f, mag); float inner = (waveformCenter - mag * waveformHeight); float outer = (waveformCenter + mag * waveformHeight); //ofSetColor(0,0,0,gModuleDrawAlpha); ofLine(centerX + sinR * inner, centerY - cosR * inner, centerX + sinR * outer, centerY - cosR * outer); } ofSetLineWidth(3); ofSetColor(0, 255, 0, gModuleDrawAlpha); float displayPos = GetActualLoopPos(0); float position = displayPos / loopLength; float radians = position * TWO_PI; float sinR = sin(radians); float cosR = cos(radians); ofLine(centerX + sinR * innerRad, centerY - cosR * innerRad, centerX + sinR * outerRad, centerY - cosR * outerRad); ofSetLineWidth(4); ofSetColor(255, 0, 0, gModuleDrawAlpha); if (mBeatwheelDepthRight > 0 && mBeatwheelPosRight >= 0) { radians = mBeatwheelPosRight * TWO_PI; sinR = sin(radians); cosR = cos(radians); ofLine(centerX + sinR * outerRad * .9f, centerY - cosR * outerRad * .9f, centerX + sinR * outerRad, centerY - cosR * outerRad); } if (mBeatwheelDepthLeft > 0 && mBeatwheelPosLeft >= 0) { radians = mBeatwheelPosLeft * TWO_PI; sinR = sin(radians); cosR = cos(radians); ofLine(centerX + sinR * outerRad * .9f, centerY - cosR * outerRad * .9f, centerX + sinR * outerRad, centerY - cosR * outerRad); } if (depthLevel > 0) { ofSetLineWidth(1); ofSetColor(150, 150, 150, gModuleDrawAlpha); for (int i = 0; i < numSlices; ++i) { radians = (i * TWO_PI) / numSlices; sinR = sin(radians); cosR = cos(radians); ofLine(centerX + sinR * waveformCenter, centerY - cosR * waveformCenter, centerX + sinR * outerRad, centerY - cosR * outerRad); } } ofPopStyle(); ofPopMatrix(); } bool Looper::DrawToPush2Screen() { ofPushMatrix(); ofTranslate(60, 3); float displayPos = GetActualLoopPos(0); mBufferMutex.lock(); DrawAudioBuffer(180, 74, mBuffer, 0, mLoopLength, displayPos, mVol); mBufferMutex.unlock(); ofPopMatrix(); return false; } void Looper::Clear() { mBuffer->Clear(); mLastCommitTime = gTime; mVol = 1; mFourTet = 0; mPitchShift = 1; } void Looper::SetNumBars(int numBars) { numBars = MIN(numBars, kMaxNumBars); int oldNumBars = mNumBars; mNumBars = numBars; if (mNumBars != oldNumBars) UpdateNumBars(oldNumBars); } void Looper::BakeVolume() { mUndoBuffer->CopyFrom(mBuffer, mLoopLength); for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) Mult(mBuffer->GetChannel(ch), mVol * mVol, mLoopLength); mVol = 1; mSmoothedVol = 1; mWantBakeVolume = false; } void Looper::UpdateNumBars(int oldNumBars) { assert(mNumBars > 0); int sampsPerBar = abs(int(TheTransport->MsPerBar() / 1000 * gSampleRate)); SetLoopLength(MIN(sampsPerBar * mNumBars, MAX_BUFFER_SIZE - 1)); while (mLoopPos > sampsPerBar) mLoopPos -= sampsPerBar; mLoopPos += sampsPerBar * (TheTransport->GetMeasure(gTime) % mNumBars); if (oldNumBars < mNumBars) { int oldLoopLength = abs(int(TheTransport->MsPerBar() * oldNumBars / 1000 * gSampleRate)); oldLoopLength = MIN(oldLoopLength, MAX_BUFFER_SIZE - 1); for (int i = 1; i < mNumBars / oldNumBars; ++i) { for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) BufferCopy(mBuffer->GetChannel(ch) + oldLoopLength * i, mBuffer->GetChannel(ch), oldLoopLength); } } } void Looper::SetLoopLength(int length) { assert(length > 0); mLoopLength = length; if (mLoopPosOffsetSlider != nullptr) mLoopPosOffsetSlider->SetExtents(0, length); mBufferTempo = TheTransport->GetTempo(); } void Looper::MergeIn(Looper* otherLooper) { int newNumBars = MAX(mNumBars, otherLooper->mNumBars); SetNumBars(newNumBars); otherLooper->SetNumBars(newNumBars); if (mVol > 0.01f) { for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) { Mult(otherLooper->mBuffer->GetChannel(ch), (otherLooper->mVol * otherLooper->mVol) / (mVol * mVol), mLoopLength); //keep other looper at same apparent volume Add(mBuffer->GetChannel(ch), otherLooper->mBuffer->GetChannel(ch), mLoopLength); } } else //ours was silent, just replace it { mBuffer->CopyFrom(otherLooper->mBuffer, mLoopLength); mVol = 1; } otherLooper->Clear(); if (mRecorder) mLastCommit = mRecorder->IncreaseCommitCount(); } void Looper::SwapBuffers(Looper* otherLooper) { assert(otherLooper); ChannelBuffer* temp = otherLooper->mBuffer; int length = otherLooper->mLoopLength; int numBars = otherLooper->mNumBars; float vol = otherLooper->mVol; otherLooper->mVol = mVol; otherLooper->mBuffer = mBuffer; otherLooper->SetLoopLength(mLoopLength); otherLooper->mNumBars = mNumBars; mBuffer = temp; SetLoopLength(length); mNumBars = numBars; mVol = vol; } void Looper::CopyBuffer(Looper* sourceLooper) { assert(sourceLooper); mBuffer->CopyFrom(sourceLooper->mBuffer, mLoopLength); SetLoopLength(sourceLooper->mLoopLength); mNumBars = sourceLooper->mNumBars; } void Looper::Commit(RollingBuffer* commitBuffer, bool replaceOnCommit, float offsetMs) { if (mRecorder) { mRecorder->ResetSpeed(); mLastCommit = mRecorder->IncreaseCommitCount(); } BakeVolume(); mLastCommitTime = gTime; mLoopCount = 0; mLoopPosOffset = 0; mLoopPosOffsetSlider->DisableLFO(); mAllowScratch = false; mScratchSpeed = 1; mFourTet = 0; mPitchShift = 1; if (mGranulator) mGranulator->OnCommit(); mCommitBuffer = commitBuffer; mReplaceOnCommit = replaceOnCommit; mCommitMsOffset = offsetMs; } void Looper::SetMute(double time, bool mute) { mMute = mute; mMuteRamp.Start(time, mMute ? 0 : 1, time + 1); } void Looper::FilesDropped(std::vector<std::string> files, int x, int y) { Sample sample; sample.Read(files[0].c_str()); SampleDropped(x, y, &sample); } void Looper::SampleDropped(int x, int y, Sample* sample) { assert(sample); int numSamples = sample->LengthInSamples(); if (numSamples <= 0) return; if (sample->GetNumBars() > 0) SetNumBars(sample->GetNumBars()); float lengthRatio = float(numSamples) / mLoopLength; mBuffer->SetNumActiveChannels(sample->NumChannels()); for (int i = 0; i < mLoopLength; ++i) { float offset = i * lengthRatio; for (int ch = 0; ch < sample->NumChannels(); ++ch) mBuffer->GetChannel(ch)[i] = GetInterpolatedSample(offset, sample->Data()->GetChannel(ch), numSamples); } } void Looper::GetModuleDimensions(float& width, float& height) { width = kBufferX * 2 + kBufferWidth; height = 182; } void Looper::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); if (x >= kBufferX + kBufferWidth / 3 && x < kBufferX + (kBufferWidth * 2) / 3 && y >= kBufferY + kBufferHeight / 3 && y < kBufferY + (kBufferHeight * 2) / 3 && mBufferTempo == TheTransport->GetTempo() && gHoveredUIControl == nullptr) { ChannelBuffer grab(mLoopLength); grab.SetNumActiveChannels(mBuffer->NumActiveChannels()); for (int ch = 0; ch < grab.NumActiveChannels(); ++ch) BufferCopy(grab.GetChannel(ch), mBuffer->GetChannel(ch), mLoopLength); TheSynth->GrabSample(&grab, "loop", false, mNumBars); } } void Looper::ButtonClicked(ClickButton* button, double time) { if (button == mClearButton) { mUndoBuffer->CopyFrom(mBuffer, mLoopLength); Clear(); } if (button == mMergeButton && mRecorder) mRecorder->RequestMerge(this); if (button == mSwapButton && mRecorder) mRecorder->RequestSwap(this); if (button == mCopyButton && mRecorder) mRecorder->RequestCopy(this); if (button == mVolumeBakeButton) mWantBakeVolume = true; if (button == mSaveButton) { Sample::WriteDataToFile(ofGetTimestampString("loops/loop_%Y-%m-%d_%H-%M-%S.wav").c_str(), mBuffer, mLoopLength); } if (button == mCommitButton && mRecorder) mRecorder->Commit(this); if (button == mDoubleSpeedButton) { if (mSpeed == 1) { HalveNumBars(); mSpeed = 2; ResampleForSpeed(GetPlaybackSpeed()); } } if (button == mHalveSpeedButton) { if (mSpeed == 1 && mLoopLength < MAX_BUFFER_SIZE / 2) { DoubleNumBars(); mSpeed = .5f; ResampleForSpeed(GetPlaybackSpeed()); } } if (button == mExtendButton) { int newLength = mNumBars * 2; if (newLength <= 16) SetNumBars(newLength); } if (button == mUndoButton) mWantUndo = true; if (button == mWriteOffsetButton) mWantShiftOffset = true; if (button == mQueueCaptureButton) { mCaptureQueued = true; mLastCommitTime = time; } if (button == mResampleButton) ResampleForSpeed(GetPlaybackSpeed()); } void Looper::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mScratchSpeedSlider) { if (!mAllowScratch && !TheSynth->IsLoadingState()) mScratchSpeed = 1; } if (slider == mFourTetSlider) { if (mFourTet == 0 && !TheSynth->IsLoadingState()) mLoopPosOffset = 0; } if (slider == mVolSlider) { if (mVol > oldVal) { mLoopCount = 0; //stop fading for a few loops } } } void Looper::RadioButtonUpdated(RadioButton* radio, int oldVal, double time) { } void Looper::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mNumBarsSelector) UpdateNumBars(oldVal); } void Looper::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mAllowScratchCheckbox) { if (mAllowScratch == false) { mScratchSpeed = 1; mLoopPosOffset = 0; } } if (checkbox == mMuteCheckbox) { SetMute(time, mMute); } if (checkbox == mWriteInputCheckbox) { if (mWriteInput) { if (mBufferTempo != TheTransport->GetTempo()) ResampleForSpeed(GetPlaybackSpeed()); mWriteInputRamp.Start(time, 1, time + 10); } else { mWriteInputRamp.Start(time, 0, time + 10); } } } void Looper::HalveNumBars() { if (mNumBars > 1) { mNumBars /= 2; } else { int bufferSize = int(TheTransport->MsPerBar() * mNumBars / 1000 * gSampleRate); if (bufferSize < MAX_BUFFER_SIZE / 2) //if we can fit it { //copy it over twice to make this just one bar mNumBars = 2; UpdateNumBars(1); mNumBars = 1; } } } void Looper::DoShiftMeasure() { int measureSize = int(TheTransport->MsPerBar() * gSampleRate / 1000); for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) { float* newBuffer = new float[MAX_BUFFER_SIZE]; BufferCopy(newBuffer, mBuffer->GetChannel(ch) + measureSize, mLoopLength - measureSize); BufferCopy(newBuffer + mLoopLength - measureSize, mBuffer->GetChannel(ch), measureSize); mBufferMutex.lock(); mBuffer->SetChannelPointer(newBuffer, ch, true); mBufferMutex.unlock(); } mWantShiftMeasure = false; } void Looper::DoHalfShift() { int halfMeasureSize = int(TheTransport->MsPerBar() * gSampleRate / 1000 / 2); for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) { float* newBuffer = new float[MAX_BUFFER_SIZE]; BufferCopy(newBuffer, mBuffer->GetChannel(ch) + halfMeasureSize, mLoopLength - halfMeasureSize); BufferCopy(newBuffer + mLoopLength - halfMeasureSize, mBuffer->GetChannel(ch), halfMeasureSize); mBufferMutex.lock(); mBuffer->SetChannelPointer(newBuffer, ch, true); mBufferMutex.unlock(); } mWantHalfShift = false; } void Looper::DoShiftDownbeat() { int shift = int(mLoopPos); for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) { float* newBuffer = new float[MAX_BUFFER_SIZE]; BufferCopy(newBuffer, mBuffer->GetChannel(ch) + shift, mLoopLength - shift); BufferCopy(newBuffer + mLoopLength - shift, mBuffer->GetChannel(ch), shift); mBufferMutex.lock(); mBuffer->SetChannelPointer(newBuffer, ch, true); mBufferMutex.unlock(); } mWantShiftDownbeat = false; } void Looper::DoShiftOffset() { int shift = int(mLoopPosOffset); if (shift != 0) { for (int ch = 0; ch < mBuffer->NumActiveChannels(); ++ch) { float* newBuffer = new float[MAX_BUFFER_SIZE]; BufferCopy(newBuffer, mBuffer->GetChannel(ch) + shift, mLoopLength - shift); BufferCopy(newBuffer + mLoopLength - shift, mBuffer->GetChannel(ch), shift); mBufferMutex.lock(); mBuffer->SetChannelPointer(newBuffer, ch, true); mBufferMutex.unlock(); } } mWantShiftOffset = false; mLoopPosOffset = 0; } void Looper::Rewrite() { mWantRewrite = true; } void Looper::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { //jump around in loop if (velocity > 0) { float measurePos = fmod(pitch / 16.0f, mNumBars); float sampsPerBar = TheTransport->MsPerBar() / 1000.0f * gSampleRate; mLoopPosOffset = (measurePos - fmod(TheTransport->GetMeasureTime(time), mNumBars)) * sampsPerBar; if (mLoopPosOffset < 0) mLoopPosOffset += mLoopLength; mLoopPosOffsetSlider->DisableLFO(); } } void Looper::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadFloat("decay", moduleInfo, false); SetUpFromSaveData(); } void Looper::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); mDecay = mModuleSaveData.GetFloat("decay"); } void Looper::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); out << mLoopLength; out << mBufferTempo; mBuffer->Save(out, mLoopLength); } void Looper::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); in >> mLoopLength; if (rev >= 1) in >> mBufferTempo; int readLength; mBuffer->Load(in, readLength, ChannelBuffer::LoadMode::kAnyBufferSize); assert(mLoopLength == readLength); } ```
/content/code_sandbox/Source/Looper.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
11,363
```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 **/ // // IAudioEffect.h // additiveSynth // // Created by Ryan Challinor on 11/21/12. // // #pragma once #include "IDrawableModule.h" #include "ChannelBuffer.h" class IAudioEffect : public IDrawableModule { public: virtual ~IAudioEffect() {} virtual void ProcessAudio(double time, ChannelBuffer* buffer) = 0; void SetEnabled(bool enabled) override = 0; virtual float GetEffectAmount() { return 0; } virtual std::string GetType() = 0; bool CanMinimize() override { return false; } bool IsSaveable() override { return false; } virtual void LoadLayout(const ofxJSONElement& moduleInfo) override {} virtual void SaveLayout(ofxJSONElement& moduleInfo) override {} }; ```
/content/code_sandbox/Source/IAudioEffect.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
275
```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 **/ /* ============================================================================== IPulseReceiver.h Created: 20 Sep 2018 9:24:33pm Author: Ryan Challinor ============================================================================== */ #pragma once class PatchCableSource; enum PulseFlags { kPulseFlag_None = 0x0, kPulseFlag_Reset = 0x1, kPulseFlag_Random = 0x2, kPulseFlag_SyncToTransport = 0x4, kPulseFlag_Backward = 0x8, kPulseFlag_Align = 0x10, kPulseFlag_Repeat = 0x20 }; class IPulseReceiver { public: virtual ~IPulseReceiver() {} virtual void OnPulse(double time, float velocity, int flags) = 0; }; class IPulseSource { public: IPulseSource() {} virtual ~IPulseSource() {} void DispatchPulse(PatchCableSource* destination, double time, float velocity, int flags); }; ```
/content/code_sandbox/Source/IPulseReceiver.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
322
```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 **/ // // AudioMeter.cpp // Bespoke // // Created by Ryan Challinor on 6/18/15. // // #include "AudioMeter.h" #include "Profiler.h" #include "ModularSynth.h" AudioMeter::AudioMeter() : IAudioProcessor(gBufferSize) { mAnalysisBuffer = new float[gBufferSize]; } void AudioMeter::CreateUIControls() { IDrawableModule::CreateUIControls(); mLevelSlider = new FloatSlider(this, "level", 5, 2, 110, 15, &mLevel, 0, mMaxLevel); } AudioMeter::~AudioMeter() { delete[] mAnalysisBuffer; } void AudioMeter::Process(double time) { PROFILER(AudioMeter); IAudioReceiver* target = GetTarget(); if (target == nullptr) return; SyncBuffers(); if (mEnabled) { ComputeSliders(0); Clear(mAnalysisBuffer, gBufferSize); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) Add(mAnalysisBuffer, GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize()); mPeakTracker.Process(mAnalysisBuffer, gBufferSize); mLevel = sqrtf(mPeakTracker.GetPeak()); } 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(); } void AudioMeter::DrawModule() { if (Minimized() || IsVisible() == false) return; mLevelSlider->Draw(); } void AudioMeter::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadFloat("maxlevel", moduleInfo, 1); SetUpFromSaveData(); } void AudioMeter::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); mMaxLevel = mModuleSaveData.GetFloat("maxlevel"); mLevelSlider->SetExtents(0, mMaxLevel); } ```
/content/code_sandbox/Source/AudioMeter.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
588
```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 **/ /* ============================================================================== NoteToPulse.h Created: 20 Sep 2018 9:43:00pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "INoteReceiver.h" #include "IPulseReceiver.h" class PatchCableSource; class NoteToPulse : public IDrawableModule, public INoteReceiver, public IPulseSource { public: NoteToPulse(); virtual ~NoteToPulse(); static IDrawableModule* Create() { return new NoteToPulse(); } 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 SendCC(int control, int value, int voiceIdx = -1) 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& width, float& height) override { width = 110; height = 0; } }; ```
/content/code_sandbox/Source/NoteToPulse.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
439
```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 **/ // // NoteVibrato.cpp // Bespoke // // Created by Ryan Challinor on 12/27/15. // // #include "NoteVibrato.h" #include "OpenFrameworksPort.h" #include "ModularSynth.h" NoteVibrato::NoteVibrato() { } void NoteVibrato::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } NoteVibrato::~NoteVibrato() { TheTransport->RemoveAudioPoller(this); } void NoteVibrato::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 NoteVibrato::DrawModule() { if (Minimized() || IsVisible() == false) return; mVibratoSlider->Draw(); mIntervalSelector->Draw(); } void NoteVibrato::OnTransportAdvanced(float amount) { ComputeSliders(0); } void NoteVibrato::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled) { mModulation.GetPitchBend(voiceIdx)->AppendTo(modulation.pitchBend); modulation.pitchBend = mModulation.GetPitchBend(voiceIdx); } PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void NoteVibrato::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mVibratoSlider) mModulation.GetPitchBend(-1)->SetLFO(mVibratoInterval, mVibratoAmount); } void NoteVibrato::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mIntervalSelector) mModulation.GetPitchBend(-1)->SetLFO(mVibratoInterval, mVibratoAmount); } void NoteVibrato::CheckboxUpdated(Checkbox* checkbox, double time) { } void NoteVibrato::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadFloat("range", moduleInfo, 1, 0, 64, K(isTextField)); SetUpFromSaveData(); } void NoteVibrato::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); mVibratoSlider->SetExtents(0, mModuleSaveData.GetFloat("range")); } ```
/content/code_sandbox/Source/NoteVibrato.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
863
```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 **/ // // ScaleDegree.cpp // Bespoke // // Created by Ryan Challinor on 4/5/16. // // #include "ScaleDegree.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" #include "UIControlMacros.h" ScaleDegree::ScaleDegree() { } void ScaleDegree::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); DROPDOWN(mScaleDegreeSelector, "degree", &mScaleDegree, 50); CHECKBOX(mRetriggerCheckbox, "retrigger", &mRetrigger); CHECKBOX(mDiatonicCheckbox, "diatonic", &mDiatonic); ENDUIBLOCK(mWidth, mHeight); mScaleDegreeSelector->AddLabel("-I", -7); mScaleDegreeSelector->AddLabel("-II", -6); mScaleDegreeSelector->AddLabel("-III", -5); mScaleDegreeSelector->AddLabel("-IV", -4); mScaleDegreeSelector->AddLabel("-V", -3); mScaleDegreeSelector->AddLabel("-VI", -2); mScaleDegreeSelector->AddLabel("-VII", -1); mScaleDegreeSelector->AddLabel("I", 0); mScaleDegreeSelector->AddLabel("II", 1); mScaleDegreeSelector->AddLabel("III", 2); mScaleDegreeSelector->AddLabel("IV", 3); mScaleDegreeSelector->AddLabel("V", 4); mScaleDegreeSelector->AddLabel("VI", 5); mScaleDegreeSelector->AddLabel("VII", 6); mScaleDegreeSelector->AddLabel("I+", 7); } void ScaleDegree::DrawModule() { if (Minimized() || IsVisible() == false) return; mScaleDegreeSelector->Draw(); mRetriggerCheckbox->Draw(); mDiatonicCheckbox->Draw(); } void ScaleDegree::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) mNoteOutput.Flush(time); } void ScaleDegree::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 = TransformPitch(pitch); } else { mInputNotes[pitch].mOn = false; } PlayNoteOutput(time, mInputNotes[pitch].mOutputPitch, velocity, mInputNotes[pitch].mVoiceIdx, modulation); } } int ScaleDegree::TransformPitch(int pitch) { if (mDiatonic) { int tone = TheScale->GetToneFromPitch(pitch); tone += mScaleDegree; return TheScale->GetPitchFromTone(tone); } else { int semitones = TheScale->GetPitchFromTone(mScaleDegree) - TheScale->ScaleRoot(); return pitch + semitones; } } void ScaleDegree::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mScaleDegreeSelector && mEnabled && mRetrigger) { for (int pitch = 0; pitch < 128; ++pitch) { if (mInputNotes[pitch].mOn) { PlayNoteOutput(time, mInputNotes[pitch].mOutputPitch, 0, mInputNotes[pitch].mVoiceIdx, ModulationParameters()); mInputNotes[pitch].mOutputPitch = TransformPitch(pitch); PlayNoteOutput(time, mInputNotes[pitch].mOutputPitch, mInputNotes[pitch].mVelocity, mInputNotes[pitch].mVoiceIdx, ModulationParameters()); } } } } void ScaleDegree::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void ScaleDegree::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/ScaleDegree.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,068
```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 **/ // // TextEntry.cpp // modularSynth // // Created by Ryan Challinor on 12/5/12. // // #include "TextEntry.h" #include "ModularSynth.h" #include "SynthGlobals.h" #include "IDrawableModule.h" #include "FileStream.h" #include "UserPrefs.h" #include "juce_gui_basics/juce_gui_basics.h" IKeyboardFocusListener* IKeyboardFocusListener::sCurrentKeyboardFocus = nullptr; IKeyboardFocusListener* IKeyboardFocusListener::sKeyboardFocusBeforeClick = nullptr; //static void IKeyboardFocusListener::ClearActiveKeyboardFocus(bool notifyListeners) { if (sCurrentKeyboardFocus && notifyListeners) sCurrentKeyboardFocus->AcceptEntry(false); sCurrentKeyboardFocus = nullptr; } TextEntry::TextEntry(ITextEntryListener* owner, const char* name, int x, int y, int charWidth, char* var) : mVarCString(var) { Construct(owner, name, x, y, charWidth); } TextEntry::TextEntry(ITextEntryListener* owner, const char* name, int x, int y, int charWidth, std::string* var) : mVarString(var) { Construct(owner, name, x, y, charWidth); } TextEntry::TextEntry(ITextEntryListener* owner, const char* name, int x, int y, int charWidth, int* var, int min, int max) : mVarInt(var) , mType(kTextEntry_Int) , mIntMin(min) , mIntMax(max) { Construct(owner, name, x, y, charWidth); } TextEntry::TextEntry(ITextEntryListener* owner, const char* name, int x, int y, int charWidth, float* var, float min, float max) : mVarFloat(var) , mType(kTextEntry_Float) , mFloatMin(min) , mFloatMax(max) { Construct(owner, name, x, y, charWidth); } void TextEntry::Construct(ITextEntryListener* owner, const char* name, int x, int y, int charWidth) { mCharWidth = charWidth; mListener = owner; UpdateDisplayString(); SetName(name); mLabelSize = gFont.GetStringWidth(name, 13) + 3; SetPosition(x, y); assert(owner); IDrawableModule* module = dynamic_cast<IDrawableModule*>(owner); if (module) module->AddUIControl(this); SetParent(dynamic_cast<IClickable*>(owner)); } TextEntry::~TextEntry() { } void TextEntry::Delete() { if (IKeyboardFocusListener::GetActiveKeyboardFocus() == this) IKeyboardFocusListener::ClearActiveKeyboardFocus(false); delete this; } void TextEntry::Render() { ofPushStyle(); ofSetLineWidth(.5f); float xOffset = 0; if (mDrawLabel) { DrawTextNormal(Name(), mX, mY + 12); xOffset = mLabelSize; } bool isCurrent = IKeyboardFocusListener::GetActiveKeyboardFocus() == this; ofColor color(255, 255, 255); if (!isCurrent && mInErrorMode) color.set(200, 100, 100); if (!isCurrent) UpdateDisplayString(); float w, h; GetDimensions(w, h); if (isCurrent) { ofSetColor(color, gModuleDrawAlpha * .1f); ofFill(); ofRect(mX + xOffset, mY, w - xOffset, h); } ofSetColor(color, gModuleDrawAlpha); ofNoFill(); ofRect(mX + xOffset, mY, w - xOffset, h); gFontFixedWidth.DrawString(mString, 12, mX + 2 + xOffset, mY + 12); if (IKeyboardFocusListener::GetActiveKeyboardFocus() == this) { if (mCaretBlink) { int caretX = mX + 2 + xOffset; int caretY = mY + 1; if (mCaretPosition > 0) { char beforeCaret[MAX_TEXTENTRY_LENGTH]; strncpy(beforeCaret, mString, mCaretPosition); beforeCaret[mCaretPosition] = 0; caretX += gFontFixedWidth.GetStringWidth(beforeCaret, 12); } ofFill(); ofRect(caretX, caretY, 1, 12, L(corner, 1)); } mCaretBlinkTimer += ofGetLastFrameTime(); if (mCaretBlinkTimer > .3f) { mCaretBlinkTimer -= .3f; mCaretBlink = !mCaretBlink; } } if (mCaretPosition != mCaretPosition2 && isCurrent) { ofPushStyle(); ofFill(); ofSetColor(255, 255, 255, 90); int selStartX = mX + 2 + xOffset; int selEndX = mX + 2 + xOffset; int selY = mY + 1; // int start = MIN(mCaretPosition, mCaretPosition2); char selectionTmp[MAX_TEXTENTRY_LENGTH]; strncpy(selectionTmp, mString, start); selectionTmp[start] = 0; selStartX += gFontFixedWidth.GetStringWidth(selectionTmp, 12); // int end = MAX(mCaretPosition, mCaretPosition2); strncpy(selectionTmp, mString, end); selectionTmp[end] = 0; selEndX += gFontFixedWidth.GetStringWidth(selectionTmp, 12); ofRect(selStartX, selY, selEndX - selStartX, 12, 0); ofPopStyle(); } /*if (mHovered) { ofSetColor(100, 100, 100, .8f*gModuleDrawAlpha); ofFill(); ofRect(mX+xOffset,mY-12,GetStringWidth(Name()),10); ofSetColor(255, 255, 255, gModuleDrawAlpha); DrawTextNormal(Name(), mX+xOffset, mY); }*/ ofPopStyle(); DrawHover(mX + xOffset, mY, w - xOffset, h); } void TextEntry::GetDimensions(float& width, float& height) { if (mFlexibleWidth) width = MAX(30.0f, gFontFixedWidth.GetStringWidth(mString, 12) + 4); else width = mCharWidth * 9; if (mDrawLabel) width += mLabelSize; height = 15; } void TextEntry::OnClicked(float x, float y, bool right) { if (right) return; float xOffset = 2; if (mDrawLabel) xOffset += mLabelSize; if (sKeyboardFocusBeforeClick != this) { SelectAll(); } else { mCaretPosition = 0; char caretCheck[MAX_TEXTENTRY_LENGTH]; size_t checkLength = strnlen(mString, MAX_TEXTENTRY_LENGTH); strncpy(caretCheck, mString, checkLength); int lastSubstrWidth = gFontFixedWidth.GetStringWidth(caretCheck, 12); for (int i = (int)checkLength - 1; i >= 0; --i) { caretCheck[i] = 0; //shorten string by one int substrWidth = gFontFixedWidth.GetStringWidth(caretCheck, 12); //ofLog() << x << " " << i << " " << (xOffset + substrWidth); if (x > xOffset + ((substrWidth + lastSubstrWidth) * .5f)) { mCaretPosition = i + 1; break; } lastSubstrWidth = substrWidth; } mCaretPosition2 = mCaretPosition; } MakeActiveTextEntry(false); } void TextEntry::MakeActiveTextEntry(bool setCaretToEnd) { SetActiveKeyboardFocus(this); if (mListener) mListener->TextEntryActivated(this); if (setCaretToEnd) { mCaretPosition = (int)strlen(mString); mCaretPosition2 = mCaretPosition; } mCaretBlink = true; mCaretBlinkTimer = 0; } void TextEntry::RemoveSelectedText() { int caretStart = MAX(0, MIN(mCaretPosition, mCaretPosition2)); int caretEnd = MIN(strlen(mString), MAX(mCaretPosition, mCaretPosition2)); std::string newString = mString; strcpy(mString, (newString.substr(0, caretStart) + newString.substr(caretEnd)).c_str()); MoveCaret(caretStart, false); } void TextEntry::SelectAll() { mCaretPosition = 0; mCaretPosition2 = strnlen(mString, MAX_TEXTENTRY_LENGTH); } void TextEntry::OnKeyPressed(int key, bool isRepeat) { if (key == OF_KEY_RETURN) { AcceptEntry(true); IKeyboardFocusListener::ClearActiveKeyboardFocus(!K(notifyListeners)); } else if (key == OF_KEY_TAB) { TextEntry* pendingNewEntry = nullptr; if (GetKeyModifiers() == kModifier_Shift) pendingNewEntry = mPreviousTextEntry; else pendingNewEntry = mNextTextEntry; AcceptEntry(false); IKeyboardFocusListener::ClearActiveKeyboardFocus(!K(notifyListeners)); if (pendingNewEntry) { pendingNewEntry->MakeActiveTextEntry(true); pendingNewEntry->SelectAll(); } } else if (key == juce::KeyPress::backspaceKey) { int len = (int)strlen(mString); if (mCaretPosition != mCaretPosition2) { RemoveSelectedText(); } else if (mCaretPosition > 0) { for (int i = mCaretPosition - 1; i < len; ++i) mString[i] = mString[i + 1]; --mCaretPosition; --mCaretPosition2; } } else if (key == juce::KeyPress::deleteKey) { int len = (int)strlen(mString); if (mCaretPosition != mCaretPosition2) { RemoveSelectedText(); } else { for (int i = mCaretPosition; i < len; ++i) mString[i] = mString[i + 1]; } } else if (key == OF_KEY_ESC) { IKeyboardFocusListener::ClearActiveKeyboardFocus(K(notifyListeners)); mCaretPosition2 = mCaretPosition; } else if (key == OF_KEY_LEFT) { if (GetKeyModifiers() & kModifier_Command) MoveCaret(0); else if (!(GetKeyModifiers() & kModifier_Shift) && mCaretPosition != mCaretPosition2) MoveCaret(MIN(mCaretPosition, mCaretPosition2)); else if (mCaretPosition > 0) MoveCaret(mCaretPosition - 1); } else if (key == OF_KEY_RIGHT) { if (GetKeyModifiers() & kModifier_Command) MoveCaret((int)strlen(mString)); else if (!(GetKeyModifiers() & kModifier_Shift) && mCaretPosition != mCaretPosition2) MoveCaret(MAX(mCaretPosition, mCaretPosition2)); else if (mCaretPosition < (int)strlen(mString)) MoveCaret(mCaretPosition + 1); } else if (key == OF_KEY_UP) { if (mType == kTextEntry_Float) { if (*mVarFloat + 1 <= mFloatMax) { *mVarFloat += 1; UpdateDisplayString(); AcceptEntry(false); } } else if (mType == kTextEntry_Int) { if (*mVarInt + 1 <= mIntMax) { *mVarInt += 1; UpdateDisplayString(); AcceptEntry(false); } } } else if (key == OF_KEY_DOWN) { if (mType == kTextEntry_Float) { if (*mVarFloat - 1 >= mFloatMin) { *mVarFloat -= 1; UpdateDisplayString(); AcceptEntry(false); } } else if (mType == kTextEntry_Int) { if (*mVarInt - 1 >= mIntMin) { *mVarInt -= 1; UpdateDisplayString(); AcceptEntry(false); } } } else if (toupper(key) == 'V' && GetKeyModifiers() == kModifier_Command) { if (mCaretPosition != mCaretPosition2) RemoveSelectedText(); juce::String clipboard = TheSynth->GetTextFromClipboard(); std::string newString = mString; strcpy(mString, (newString.substr(0, mCaretPosition) + clipboard.toStdString() + newString.substr(mCaretPosition)).c_str()); if (UserPrefs.immediate_paste.Get()) AcceptEntry(true); else MoveCaret(mCaretPosition + clipboard.length()); } else if ((toupper(key) == 'C' || toupper(key) == 'X') && GetKeyModifiers() == kModifier_Command) { if (mCaretPosition != mCaretPosition2) { int caretStart = MIN(mCaretPosition, mCaretPosition2); int caretEnd = MAX(mCaretPosition, mCaretPosition2); std::string tmpString(mString); TheSynth->CopyTextToClipboard(tmpString.substr(caretStart, caretEnd - caretStart)); if (toupper(key) == 'X') RemoveSelectedText(); } } else if (toupper(key) == 'A' && GetKeyModifiers() == kModifier_Command) { SelectAll(); } else if (key == juce::KeyPress::homeKey) { MoveCaret(0); } else if (key == juce::KeyPress::endKey) { MoveCaret((int)strlen(mString)); } else if (key < CHAR_MAX && juce::CharacterFunctions::isPrintable((char)key)) { if (mCaretPosition != mCaretPosition2) RemoveSelectedText(); AddCharacter((char)key); } } void TextEntry::AddCharacter(char c) { if (AllowCharacter(c)) { int len = (int)strlen(mString); if (/*len < mCharWidth && */ len < MAX_TEXTENTRY_LENGTH - 1) { for (int i = len; i > mCaretPosition; --i) mString[i] = mString[i - 1]; mString[mCaretPosition] = c; mString[len + 1] = '\0'; ++mCaretPosition; ++mCaretPosition2; } } } void TextEntry::UpdateDisplayString() { if (mVarCString) StringCopy(mString, mVarCString, MAX_TEXTENTRY_LENGTH); if (mVarString) StringCopy(mString, mVarString->c_str(), MAX_TEXTENTRY_LENGTH); if (mVarInt) StringCopy(mString, ofToString(*mVarInt).c_str(), MAX_TEXTENTRY_LENGTH); if (mVarFloat) StringCopy(mString, ofToString(*mVarFloat).c_str(), MAX_TEXTENTRY_LENGTH); } void TextEntry::ClearInput() { std::memset(mString, 0, MAX_TEXTENTRY_LENGTH); mCaretPosition = 0; mCaretPosition2 = 0; } void TextEntry::SetText(std::string text) { if (mVarCString) StringCopy(mVarCString, text.c_str(), MAX_TEXTENTRY_LENGTH); if (mVarString) *mVarString = text; mCaretPosition = 0; mCaretPosition2 = 0; } void TextEntry::SetFromMidiCC(float slider, double time, bool setViaModulator) { if (mType == kTextEntry_Int) { *mVarInt = GetValueForMidiCC(slider); UpdateDisplayString(); } if (mType == kTextEntry_Float) { *mVarFloat = GetValueForMidiCC(slider); UpdateDisplayString(); } } float TextEntry::GetValueForMidiCC(float slider) const { if (mType == kTextEntry_Int) { slider = ofClamp(slider, 0, 1); return (int)round(ofMap(slider, 0, 1, mIntMin, mIntMax)); } if (mType == kTextEntry_Float) { slider = ofClamp(slider, 0, 1); return ofMap(slider, 0, 1, mFloatMin, mFloatMax); } return 0; } float TextEntry::GetMidiValue() const { if (mType == kTextEntry_Int) return ofMap(*mVarInt, mIntMin, mIntMax, 0, 1); if (mType == kTextEntry_Float) return ofMap(*mVarFloat, mFloatMin, mFloatMax, 0, 1); return 0; } void TextEntry::GetRange(float& min, float& max) { if (mType == kTextEntry_Int) { min = mIntMin; max = mIntMax; } else if (mType == kTextEntry_Float) { min = mFloatMin; max = mFloatMax; } else { min = 0; max = 1; } } void TextEntry::SetValue(float value, double time, bool forceUpdate /*= false*/) { if (mType == kTextEntry_Int) { *mVarInt = std::round(value); UpdateDisplayString(); } if (mType == kTextEntry_Float) { *mVarFloat = value; UpdateDisplayString(); } } float TextEntry::GetValue() const { if (mType == kTextEntry_Int) return *mVarInt; if (mType == kTextEntry_Float) return *mVarFloat; return 0; } int TextEntry::GetNumValues() { if (mType == kTextEntry_Int) return mIntMax - mIntMin + 1; return 0; } std::string TextEntry::GetDisplayValue(float val) const { if (mType == kTextEntry_Int || mType == kTextEntry_Float) return ofToString(val); return mString; } void TextEntry::AcceptEntry(bool pressedEnter) { if (!pressedEnter && mRequireEnterToAccept) { CancelEntry(); return; } if (mVarCString) StringCopy(mVarCString, mString, MAX_TEXTENTRY_LENGTH); if (mVarString) *mVarString = mString; if (mVarInt && mString[0] != 0) { *mVarInt = ofClamp(ofToInt(mString), mIntMin, mIntMax); StringCopy(mString, ofToString(*mVarInt).c_str(), MAX_TEXTENTRY_LENGTH); } if (mVarFloat && mString[0] != 0) { *mVarFloat = ofClamp(ofToFloat(mString), mFloatMin, mFloatMax); StringCopy(mString, ofToString(*mVarFloat).c_str(), MAX_TEXTENTRY_LENGTH); } if (mListener) mListener->TextEntryComplete(this); } void TextEntry::CancelEntry() { if (mListener) mListener->TextEntryCancelled(this); } void TextEntry::MoveCaret(int pos, bool allowSelection) { mCaretPosition = pos; if (!allowSelection || !(GetKeyModifiers() & kModifier_Shift)) mCaretPosition2 = mCaretPosition; mCaretBlink = true; mCaretBlinkTimer = 0; } bool TextEntry::AllowCharacter(char c) { if (mType == kTextEntry_Text) return juce::CharacterFunctions::isPrintable(c); if (mType == kTextEntry_Int) return juce::CharacterFunctions::isDigit((char)c) || c == '-'; if (mType == kTextEntry_Float) return juce::CharacterFunctions::isDigit((char)c) || c == '.' || c == '-'; return false; } void TextEntry::Increment(float amount) { if (mType == kTextEntry_Float) { float newVal = *mVarFloat + amount; if (newVal >= mFloatMin && newVal <= mFloatMax) { *mVarFloat = newVal; UpdateDisplayString(); AcceptEntry(false); } } else if (mType == kTextEntry_Int) { int newVal = *mVarInt + (int)amount; if (newVal >= mIntMin && newVal <= mIntMax) { *mVarInt = newVal; UpdateDisplayString(); AcceptEntry(false); } } } void TextEntry::SetNextTextEntry(TextEntry* entry) { mNextTextEntry = entry; if (entry) entry->mPreviousTextEntry = this; } bool TextEntry::MouseMoved(float x, float y) { mHovered = TestHover(x, y); CheckHover(x, y); return false; } namespace { const int kSaveStateRev = 0; } void TextEntry::SaveState(FileStreamOut& out) { out << kSaveStateRev; out << std::string(mString); } void TextEntry::LoadState(FileStreamIn& in, bool shouldSetValue) { int rev; in >> rev; LoadStateValidate(rev <= kSaveStateRev); std::string var; in >> var; if (shouldSetValue) { StringCopy(mString, var.c_str(), MAX_TEXTENTRY_LENGTH); AcceptEntry(false); } } ```
/content/code_sandbox/Source/TextEntry.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
5,063
```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 **/ // // ControlSequencer.cpp // Bespoke // // Created by Ryan Challinor on 8/27/15. // // #include "ControlSequencer.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "UIControlMacros.h" #include "MathUtils.h" std::list<ControlSequencer*> ControlSequencer::sControlSequencers; ControlSequencer::ControlSequencer() { sControlSequencers.push_back(this); } void ControlSequencer::Init() { IDrawableModule::Init(); mTransportListenerInfo = TheTransport->AddListener(this, mInterval, OffsetInfo(0, true), false); } ControlSequencer::~ControlSequencer() { TheTransport->RemoveListener(this); sControlSequencers.remove(this); } void ControlSequencer::CreateUIControls() { IDrawableModule::CreateUIControls(); int width, height; UIBLOCK(3, 3, 100); INTSLIDER(mLengthSlider, "length", &mLength, 1, 32); UIBLOCK_SHIFTRIGHT(); DROPDOWN(mIntervalSelector, "interval", (int*)(&mInterval), 40); UIBLOCK_SHIFTRIGHT(); BUTTON(mRandomize, "random"); UIBLOCK_NEWLINE(); CHECKBOX(mRecordCheckbox, "record", &mRecord); ENDUIBLOCK(width, height); mGrid = new UIGrid("uigrid", 5, height + 3, mRandomize->GetRect().getMaxX() - 6, 40, mLength, 1, this); UIBLOCK(15, height + 5); for (size_t i = 0; i < mStepSliders.size(); ++i) { FLOATSLIDER(mStepSliders[i], ("step " + ofToString(i)).c_str(), &mGrid->GetVal(i, 0), 0, 1); } ENDUIBLOCK0(); mControlCable = new PatchCableSource(this, kConnectionType_ValueSetter); //mControlCable->SetManualPosition(86, 10); AddPatchCableSource(mControlCable); mGrid->SetGridMode(UIGrid::kMultislider); mGrid->SetHighlightCol(gTime, -1); mGrid->SetMajorColSize(4); mGrid->SetListener(this); mIntervalSelector->AddLabel("8", kInterval_8); mIntervalSelector->AddLabel("4", kInterval_4); 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); } void ControlSequencer::Poll() { } void ControlSequencer::Step(double time, int pulseFlags) { int length = mLength; if (length <= 0) length = 1; int direction = 1; if (pulseFlags & kPulseFlag_Backward) direction = -1; if (pulseFlags & kPulseFlag_Repeat) direction = 0; mStep = (mStep + direction + length) % length; if (pulseFlags & kPulseFlag_Reset) mStep = 0; else if (pulseFlags & kPulseFlag_Random) mStep = gRandom() % length; if (!mHasExternalPulseSource || (pulseFlags & kPulseFlag_SyncToTransport)) { mStep = TheTransport->GetSyncedStep(time, this, mTransportListenerInfo, length); } if (pulseFlags & kPulseFlag_Align) { int stepsPerMeasure = TheTransport->GetStepsPerMeasure(this); int numMeasures = ceil(float(length) / stepsPerMeasure); int measure = TheTransport->GetMeasure(time) % numMeasures; int step = ((TheTransport->GetQuantized(time, mTransportListenerInfo) % stepsPerMeasure) + measure * stepsPerMeasure) % length; mStep = step; } mGrid->SetHighlightCol(time, mStep); if (mRecord && mTargets[0] != nullptr) mGrid->SetVal(mStep, 0, mTargets[0]->GetMidiValue()); if (mEnabled && !mRecord) { mControlCable->AddHistoryEvent(time, true); mControlCable->AddHistoryEvent(time + 15, false); for (auto* target : mTargets) { if (target != nullptr) target->SetFromMidiCC(mGrid->GetVal(mStep, 0), time, true); } } } void ControlSequencer::OnPulse(double time, float velocity, int flags) { mHasExternalPulseSource = true; Step(time, flags); } void ControlSequencer::OnTimeEvent(double time) { if (!mHasExternalPulseSource) Step(time, 0); } void ControlSequencer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (velocity > 0) { mHasExternalPulseSource = true; mStep = pitch % std::max(1, mLength); Step(time, kPulseFlag_Repeat); } } void ControlSequencer::DrawModule() { if (Minimized() || IsVisible() == false) return; mGrid->SetShowing(!mSliderMode); mGrid->Draw(); mIntervalSelector->Draw(); mLengthSlider->Draw(); mRandomize->Draw(); mRecordCheckbox->Draw(); DrawTextNormal("length: " + ofToString((TheTransport->GetDuration(mInterval) * mLength) / TheTransport->MsPerBar(), 2) + " measures", mRecordCheckbox->GetRect(K(local)).getMaxX() + 5, mRecordCheckbox->GetRect(K(local)).getMinY() + 12); int currentHover = mGrid->CurrentHover(); if (!mSliderMode && currentHover != -1 && GetUIControl()) { ofPushStyle(); ofSetColor(ofColor::grey); float val = mGrid->GetVal(currentHover % mGrid->GetCols(), currentHover / mGrid->GetCols()); DrawTextNormal(GetUIControl()->GetDisplayValue(GetUIControl()->GetValueForMidiCC(val)), mGrid->GetPosition(true).x, mGrid->GetPosition(true).y + 12); ofPopStyle(); } for (size_t i = 0; i < mStepSliders.size(); ++i) { if (mSliderMode) { bool showing = i < mLength; mStepSliders[i]->SetShowing(showing); mStepSliders[i]->Draw(); auto rect = mStepSliders[i]->GetRect(true); if (showing && GetUIControl()) { float val = mGrid->GetVal(i, 0); DrawTextNormal(GetUIControl()->GetDisplayValue(GetUIControl()->GetValueForMidiCC(val)), rect.getMaxX() + 5, rect.y + 12); } if (i == mStep) { ofPushStyle(); ofSetColor(0, 255, 0); ofFill(); ofRect(rect.x - 12, rect.y + 3, 10, 10); ofPopStyle(); } } else { mStepSliders[i]->SetShowing(false); } } } void ControlSequencer::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); mGrid->TestClick(x, y, right); } void ControlSequencer::MouseReleased() { IDrawableModule::MouseReleased(); mGrid->MouseReleased(); } bool ControlSequencer::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); mGrid->NotifyMouseMoved(x, y); return false; } void ControlSequencer::GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) { if (grid == mGrid) { int numValues = GetUIControl() ? GetUIControl()->GetNumValues() : 0; if (numValues > 1) { for (int i = 0; i < mGrid->GetCols(); ++i) { float val = mGrid->GetVal(i, 0); val = int((val * (numValues - 1)) + .5f) / float(numValues - 1); //quantize to match the number of allowed values mGrid->SetVal(i, 0, val); } } } } void ControlSequencer::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { bool wasEmpty = (mTargets[0] == nullptr); for (size_t i = 0; i < mTargets.size(); ++i) { if (i < mControlCable->GetPatchCables().size()) mTargets[i] = dynamic_cast<IUIControl*>(mControlCable->GetPatchCables()[i]->GetTarget()); else mTargets[i] = nullptr; } if (wasEmpty && mControlCable->GetPatchCables().size() == 1) { for (int i = 0; i < mGrid->GetCols(); ++i) mGrid->SetVal(i, 0, GetUIControl()->GetMidiValue()); } } void ControlSequencer::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mLengthSlider) { mGrid->SetGrid(mLength, 1); 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) mGrid->SetVal(i, 0, mGrid->GetVal(i % oldLengthPow2, 0)); } } } void ControlSequencer::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mIntervalSelector) { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) transportListenerInfo->mInterval = mInterval; } } void ControlSequencer::ButtonClicked(ClickButton* button, double time) { if (button == mRandomize) { for (int i = 0; i < mGrid->GetCols(); ++i) mGrid->SetVal(i, 0, ofRandom(1)); } } namespace { const float extraW = 10; const float extraH = 47; } void ControlSequencer::GetModuleDimensions(float& width, float& height) { if (mSliderMode) { width = 200; height = mLength * 17 + extraH; } else { width = mGrid->GetWidth() + extraW; height = mGrid->GetHeight() + extraH; } } void ControlSequencer::Resize(float w, float h) { w = MAX(w - extraW, 130); h = MAX(h - extraH, 40); SetGridSize(w, h); } void ControlSequencer::SetGridSize(float w, float h) { mGrid->SetDimensions(w, h); } void ControlSequencer::SaveLayout(ofxJSONElement& moduleInfo) { } void ControlSequencer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadBool("slider_mode", moduleInfo, true); SetUpFromSaveData(); } void ControlSequencer::SetUpFromSaveData() { mSliderMode = mModuleSaveData.GetBool("slider_mode"); } void ControlSequencer::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); mGrid->SaveState(out); out << mGrid->GetWidth(); out << mGrid->GetHeight(); out << mHasExternalPulseSource; } void ControlSequencer::LoadState(FileStreamIn& in, int rev) { mLoadRev = rev; if (ModularSynth::sLoadingFileSaveStateRev == 422) { in >> mLoadRev; LoadStateValidate(mLoadRev <= GetModuleSaveStateRev()); } IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev <= 421) { in >> mLoadRev; LoadStateValidate(mLoadRev <= GetModuleSaveStateRev()); } mGrid->LoadState(in); if (mLoadRev >= 1) { float width, height; in >> width; in >> height; mGrid->SetDimensions(width, height); } if (mLoadRev == 0) { //port old data float len = 0; if (mOldLengthStr == "4n") len = .25f; if (mOldLengthStr == "2n") len = .5f; if (mOldLengthStr == "1") len = 1; if (mOldLengthStr == "2") len = 2; if (mOldLengthStr == "3") len = 3; if (mOldLengthStr == "4") len = 4; if (mOldLengthStr == "6") len = 6; if (mOldLengthStr == "8") len = 8; if (mOldLengthStr == "16") len = 16; if (mOldLengthStr == "32") len = 32; if (mOldLengthStr == "64") len = 64; if (mOldLengthStr == "128") len = 128; mLength = int(len * TheTransport->CountInStandardMeasure(mInterval)); int min, max; mLengthSlider->GetRange(min, max); if (mLength > max) mLengthSlider->SetExtents(min, mLength); } if (rev < 2) { mSliderMode = false; mModuleSaveData.SetBool("slider_mode", false); } if (rev >= 3) in >> mHasExternalPulseSource; } bool ControlSequencer::LoadOldControl(FileStreamIn& in, std::string& oldName) { if (mLoadRev < 1) { if (oldName == "length") { //load dropdown string int dropdownRev; in >> dropdownRev; in >> mOldLengthStr; return true; } } return false; } ```
/content/code_sandbox/Source/ControlSequencer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
3,588
```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 **/ // // ValueSetter.cpp // Bespoke // // Created by Ryan Challinor on 1/1/16. // // #include "ValueSetter.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "ModulationChain.h" #include "UIControlMacros.h" ValueSetter::ValueSetter() { } ValueSetter::~ValueSetter() { } void ValueSetter::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); UICONTROL_CUSTOM(mValueEntry, new TextEntry(UICONTROL_BASICS("value"), 7, &mValue, -99999, 99999); mValueEntry->DrawLabel(true);); UIBLOCK_SHIFTRIGHT(); UICONTROL_CUSTOM(mButton, new ClickButton(UICONTROL_BASICS("set"))); ENDUIBLOCK(mWidth, mHeight); auto entryRect = mValueEntry->GetRect(); mValueSlider = new FloatSlider(this, "slider", entryRect.x, entryRect.y, entryRect.width, entryRect.height, &mValue, 0, 1); mValueSlider->SetShowing(false); mControlCable = new PatchCableSource(this, kConnectionType_ValueSetter); AddPatchCableSource(mControlCable); } void ValueSetter::DrawModule() { if (Minimized() || IsVisible() == false) return; mValueEntry->Draw(); mValueSlider->Draw(); mButton->Draw(); } void ValueSetter::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { for (size_t i = 0; i < mTargets.size(); ++i) { if (i < mControlCable->GetPatchCables().size()) { mTargets[i] = dynamic_cast<IUIControl*>(mControlCable->GetPatchCables()[i]->GetTarget()); if (mControlCable->GetPatchCables().size() == 1 && mTargets[i] != nullptr) mValueSlider->SetExtents(mTargets[i]->GetModulationRangeMin(), mTargets[i]->GetModulationRangeMax()); } else { mTargets[i] = nullptr; } } } void ValueSetter::OnPulse(double time, float velocity, int flags) { if (velocity > 0 && mEnabled) { ComputeSliders((time - gTime) * gSampleRateMs); Go(time); } } void ValueSetter::ButtonClicked(ClickButton* button, double time) { if (mEnabled && button == mButton && mLastClickTime != time) { mLastClickTime = time; Go(time); } } void ValueSetter::Go(double time) { mControlCable->AddHistoryEvent(time, true); mControlCable->AddHistoryEvent(time + 15, false); for (size_t i = 0; i < mTargets.size(); ++i) { if (mTargets[i] != nullptr) mTargets[i]->SetValue(mValue, time, K(forceUpdate)); } } void ValueSetter::SaveLayout(ofxJSONElement& moduleInfo) { } void ValueSetter::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadBool("show_slider", moduleInfo, false); SetUpFromSaveData(); } void ValueSetter::SetUpFromSaveData() { bool showSlider = mModuleSaveData.GetBool("show_slider"); mValueEntry->SetShowing(!showSlider); mValueSlider->SetShowing(showSlider); } ```
/content/code_sandbox/Source/ValueSetter.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
892
```objective-c /* * ofxJSONFile.h * asift * * Created by Jeffrey Crouse on 12/17/10. * */ #pragma once #include <json/json.h> #include "OpenFrameworksPort.h" //using namespace Json; extern "C" size_t decode_html_entities_utf8(char* dest, const char* src); class ofxJSONElement : public Json::Value { public: ofxJSONElement(){}; ofxJSONElement(std::string jsonString); ofxJSONElement(const Json::Value& v); bool parse(std::string jsonString); bool open(std::string filename); bool save(std::string filename, bool pretty = false); std::string getRawString(bool pretty = true); }; ```
/content/code_sandbox/Source/ofxJSONElement.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
160
```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 **/ // // EffectChain.h // modularSynth // // Created by Ryan Challinor on 11/25/12. // // #pragma once #include <iostream> #include "IAudioProcessor.h" #include "IDrawableModule.h" #include "ClickButton.h" #include "Slider.h" #include "Checkbox.h" #include "DropdownList.h" #define MAX_EFFECTS_IN_CHAIN 100 #define MIN_EFFECT_WIDTH 80 class IAudioEffect; class EffectChain : public IDrawableModule, public IAudioProcessor, public IButtonListener, public IFloatSliderListener, public IDropdownListener { public: EffectChain(); virtual ~EffectChain(); static IDrawableModule* Create() { return new EffectChain(); } static bool AcceptsAudio() { return true; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void SetEnabled(bool enabled) override { mEnabled = enabled; } void Init() override; void Poll() override; void AddEffect(std::string type, std::string desiredName, bool onTheFly); void SetWideCount(int count) { mNumFXWide = count; } //IAudioSource void Process(double time) override; void KeyPressed(int key, bool isRepeat) override; void KeyReleased(int key) override; bool HasPush2OverrideControls() const override { return true; } void GetPush2OverrideControls(std::vector<IUIControl*>& controls) const 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; virtual void LoadBasics(const ofxJSONElement& moduleInfo, std::string typeName) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; virtual void SaveLayout(ofxJSONElement& moduleInfo) override; virtual void UpdateOldControlName(std::string& oldName) override; bool IsEnabled() const override { return mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; std::vector<IUIControl*> ControlsToIgnoreInSaveState() const override; int GetRowHeight(int row) const; int NumRows() const; void DeleteEffect(int index); void MoveEffect(int index, int direction); void UpdateReshuffledDryWetSliders(); ofVec2f GetEffectPos(int index) const; struct EffectControls { ClickButton* mMoveLeftButton{ nullptr }; ClickButton* mMoveRightButton{ nullptr }; ClickButton* mDeleteButton{ nullptr }; FloatSlider* mDryWetSlider{ nullptr }; ClickButton* mPush2DisplayEffectButton{ nullptr }; }; std::vector<IAudioEffect*> mEffects{}; ChannelBuffer mDryBuffer; std::vector<EffectControls> mEffectControls; std::array<float, MAX_EFFECTS_IN_CHAIN> mDryWetLevels{}; double mSwapTime{ -1 }; int mSwapFromIdx{ -1 }; int mSwapToIdx{ -1 }; ofVec2f mSwapFromPos; ofVec2f mSwapToPos; float mVolume{ 1 }; FloatSlider* mVolumeSlider{ nullptr }; int mNumFXWide{ 3 }; bool mInitialized{ false }; bool mShowSpawnList{ true }; int mWantToDeleteEffectAtIndex{ -1 }; IAudioEffect* mPush2DisplayEffect{ nullptr }; std::vector<std::string> mEffectTypesToSpawn; int mSpawnIndex{ -1 }; DropdownList* mEffectSpawnList{ nullptr }; ClickButton* mSpawnEffectButton{ nullptr }; ClickButton* mPush2ExitEffectButton{ nullptr }; ofMutex mEffectMutex; }; ```
/content/code_sandbox/Source/EffectChain.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
997
```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 **/ // // RandomNoteGenerator.cpp // Bespoke // // Created by Ryan Challinor on 11/28/15. // // #include "RandomNoteGenerator.h" #include "SynthGlobals.h" #include "DrumPlayer.h" #include "ModularSynth.h" RandomNoteGenerator::RandomNoteGenerator() { } void RandomNoteGenerator::Init() { IDrawableModule::Init(); TheTransport->AddListener(this, mInterval, OffsetInfo(0, true), true); } void RandomNoteGenerator::CreateUIControls() { IDrawableModule::CreateUIControls(); mIntervalSelector = new DropdownList(this, "interval", 5, 2, ((int*)(&mInterval))); 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); mProbabilitySlider = new FloatSlider(this, "probability", 5, 20, 100, 15, &mProbability, 0, 1); mPitchSlider = new IntSlider(this, "pitch", 5, 38, 100, 15, &mPitch, 0, 127); mVelocitySlider = new FloatSlider(this, "velocity", 5, 56, 100, 15, &mVelocity, 0, 1); mOffsetSlider = new FloatSlider(this, "offset", 5, 74, 100, 15, &mOffset, -1, 1); mSkipSlider = new IntSlider(this, "skip", mIntervalSelector, kAnchor_Right, 60, 15, &mSkip, 1, 10); } RandomNoteGenerator::~RandomNoteGenerator() { TheTransport->RemoveListener(this); } void RandomNoteGenerator::DrawModule() { if (Minimized() || IsVisible() == false) return; mIntervalSelector->Draw(); mSkipSlider->Draw(); mProbabilitySlider->Draw(); mPitchSlider->Draw(); mVelocitySlider->Draw(); mOffsetSlider->Draw(); } void RandomNoteGenerator::OnTimeEvent(double time) { if (!mEnabled) return; ++mSkipCount; mNoteOutput.Flush(time); if (mSkipCount >= mSkip) { mSkipCount = 0; if (mProbability >= ofRandom(1)) PlayNoteOutput(time, mPitch, mVelocity * 127, -1); } } void RandomNoteGenerator::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) mNoteOutput.Flush(time); } void RandomNoteGenerator::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mOffsetSlider) { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) { transportListenerInfo->mInterval = mInterval; transportListenerInfo->mOffsetInfo = OffsetInfo(mOffset / TheTransport->CountInStandardMeasure(mInterval), !K(offsetIsInMs)); } } } void RandomNoteGenerator::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mPitchSlider) mNoteOutput.Flush(time); } void RandomNoteGenerator::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mIntervalSelector) { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) { transportListenerInfo->mInterval = mInterval; transportListenerInfo->mOffsetInfo = OffsetInfo(mOffset / TheTransport->CountInStandardMeasure(mInterval), !K(offsetIsInMs)); } } } void RandomNoteGenerator::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void RandomNoteGenerator::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/RandomNoteGenerator.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,116
```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 **/ /* ============================================================================== Panner.h Created: 10 Oct 2017 9:49:16pm Author: Ryan Challinor ============================================================================== */ #pragma once #include <iostream> #include "IAudioProcessor.h" #include "IDrawableModule.h" #include "Slider.h" #include "ClickButton.h" #include "RollingBuffer.h" #include "Ramp.h" class Panner : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public IButtonListener, public IIntSliderListener { public: Panner(); virtual ~Panner(); static IDrawableModule* Create() { return new Panner(); } static bool AcceptsAudio() { return true; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void SetPan(float pan) { mPan = pan; } //IAudioSource void Process(double time) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; void ButtonClicked(ClickButton* button, 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& w, float& h) override { w = 120; h = 40; } float mPan{ 0 }; Ramp mPanRamp; FloatSlider* mPanSlider{ nullptr }; float mWiden{ 0 }; FloatSlider* mWidenSlider{ nullptr }; RollingBuffer mWidenerBuffer{ 2048 }; }; ```
/content/code_sandbox/Source/Panner.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
542
```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 **/ // // BufferShuffler.cpp // // Created by Ryan Challinor on 6/23/23. // // #include "BufferShuffler.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Profiler.h" #include "UIControlMacros.h" BufferShuffler::BufferShuffler() : IAudioProcessor(gBufferSize) , mInputBuffer(20 * 48000) { } void BufferShuffler::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); UICONTROL_CUSTOM(mGridControlTarget, new GridControlTarget(UICONTROL_BASICS("grid"))); UIBLOCK_SHIFTRIGHT(); UIBLOCK_PUSHSLIDERWIDTH(80); INTSLIDER(mNumBarsSlider, "num bars", &mNumBars, 1, 8); UIBLOCK_SHIFTRIGHT(); DROPDOWN(mIntervalSelector, "interval", (int*)&mInterval, 40); UIBLOCK_SHIFTRIGHT(); DROPDOWN(mPlaybackStyleDropdown, "playback style", (int*)&mPlaybackStyle, 80); UIBLOCK_NEWLINE(); CHECKBOX(mFreezeInputCheckbox, "freeze input", &mFreezeInput); UIBLOCK_SHIFTRIGHT(); FLOATSLIDER(mFourTetSlider, "fourtet", &mFourTet, 0, 1); UIBLOCK_SHIFTRIGHT(); DROPDOWN(mFourTetSlicesDropdown, "fourtetslices", &mFourTetSlices, 40); ENDUIBLOCK0(); mIntervalSelector->AddLabel("4n", kInterval_4n); mIntervalSelector->AddLabel("8n", kInterval_8n); mIntervalSelector->AddLabel("16n", kInterval_16n); mIntervalSelector->AddLabel("32n", kInterval_32n); mPlaybackStyleDropdown->AddLabel("normal", (int)PlaybackStyle::Normal); mPlaybackStyleDropdown->AddLabel("double", (int)PlaybackStyle::Double); mPlaybackStyleDropdown->AddLabel("half", (int)PlaybackStyle::Half); mPlaybackStyleDropdown->AddLabel("reverse", (int)PlaybackStyle::Reverse); mPlaybackStyleDropdown->AddLabel("double reverse", (int)PlaybackStyle::DoubleReverse); mPlaybackStyleDropdown->AddLabel("half reverse", (int)PlaybackStyle::HalfReverse); mFourTetSlicesDropdown->AddLabel(" 1", 1); mFourTetSlicesDropdown->AddLabel(" 2", 2); mFourTetSlicesDropdown->AddLabel(" 4", 4); mFourTetSlicesDropdown->AddLabel(" 8", 8); mFourTetSlicesDropdown->AddLabel("16", 16); } BufferShuffler::~BufferShuffler() { } void BufferShuffler::Poll() { UpdateGridControllerLights(false); } void BufferShuffler::Process(double time) { PROFILER(BufferShuffler); IAudioReceiver* target = GetTarget(); if (target == nullptr) return; SyncBuffers(); mInputBuffer.SetNumActiveChannels(GetBuffer()->NumActiveChannels()); int bufferSize = target->GetBuffer()->BufferSize(); if (mEnabled) { int writePosition = GetWritePositionInSamples(time); for (int i = 0; i < bufferSize; ++i) { ComputeSliders(0); if (mPlaybackSampleStartTime != -1 && time >= mPlaybackSampleStartTime) { int numSlices = GetNumSlices(); int slicePosIndex = mQueuedSlice; if (mQueuedPlaybackStyle != PlaybackStyle::None) mPlaybackStyle = mQueuedPlaybackStyle; mQueuedPlaybackStyle = PlaybackStyle::None; if (GetSlicePlaybackRate() < 0) slicePosIndex += 1; float slicePos = (slicePosIndex % numSlices) / (float)numSlices; mPlaybackSampleIndex = int(GetLengthInSamples() * slicePos); mPlaybackSampleStartTime = -1; mSwitchAndRamp.StartSwitch(); if (mDrawDebug) AddDebugLine(ofToString(gTime) + " switch and ramp for slice start", 10); } if (mPlaybackSampleStopTime != -1 && time >= mPlaybackSampleStopTime) { mPlaybackSampleIndex = -1; mPlaybackSampleStopTime = -1; mSwitchAndRamp.StartSwitch(); if (mDrawDebug) AddDebugLine(ofToString(gTime) + " switch and ramp for slice end", 10); } for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { if (!mFreezeInput) mInputBuffer.GetChannel(ch)[writePosition] = GetBuffer()->GetChannel(ch)[i]; float outputSample = mOnlyPlayWhenTriggered ? 0 : GetBuffer()->GetChannel(ch)[i]; if (mPlaybackSampleIndex != -1) { outputSample = GetInterpolatedSample(mPlaybackSampleIndex, mInputBuffer.GetChannel(ch), GetLengthInSamples()); } else if (mFreezeInput || mFourTet > 0) { int readPosition = writePosition; outputSample = mOnlyPlayWhenTriggered ? 0 : mInputBuffer.GetChannel(ch)[readPosition]; } if (mFourTet > 0) { float readPosition = GetFourTetPosition(time); if (ch == 0) { if (abs(readPosition - mFourTetSampleIndex) > 1000) { mSwitchAndRamp.StartSwitch(); //smooth out pop when jumping forward to next slice if (mDrawDebug) AddDebugLine(ofToString(gTime) + " switch and ramp for fourtet jump", 10); } if (mFourTetSampleIndex > writePosition - 1 && readPosition <= writePosition) { mSwitchAndRamp.StartSwitch(); //smooth out pop when moving over write head if (mDrawDebug) AddDebugLine(ofToString(gTime) + " switch and ramp for fourtet write head pass", 10); } mFourTetSampleIndex = readPosition; } float fourTetSample = GetInterpolatedSample(readPosition, mInputBuffer.GetChannel(ch), GetLengthInSamples()); outputSample = ofLerp(outputSample, fourTetSample, mFourTet); } GetBuffer()->GetChannel(ch)[i] = mSwitchAndRamp.Process(ch, outputSample); } if (mPlaybackSampleIndex != -1) mPlaybackSampleIndex = FloatWrap(mPlaybackSampleIndex + GetSlicePlaybackRate(), GetLengthInSamples()); writePosition = (writePosition + 1) % GetLengthInSamples(); time += gInvSampleRateMs; } } 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(); } float BufferShuffler::GetFourTetPosition(double time) { float measurePos = TheTransport->GetMeasurePos(time); measurePos += TheTransport->GetMeasure(time) % mNumBars; measurePos /= mNumBars; int numSlices = mFourTetSlices * 2 * mNumBars; measurePos *= numSlices; int slice = (int)measurePos; float sliceProgress = measurePos - slice; float offset; if (slice % 2 == 0) offset = (sliceProgress + slice / 2) * (GetLengthInSamples() / float(numSlices) * 2); else offset = (1 - sliceProgress + slice / 2) * (GetLengthInSamples() / float(numSlices) * 2); return FloatWrap(offset, GetLengthInSamples()); } void BufferShuffler::DrawModule() { if (Minimized() || IsVisible() == false) return; mNumBarsSlider->Draw(); mIntervalSelector->Draw(); mFreezeInputCheckbox->Draw(); mPlaybackStyleDropdown->Draw(); mGridControlTarget->Draw(); mFourTetSlider->Draw(); mFourTetSlicesDropdown->Draw(); DrawBuffer(5, 37, mWidth - 10, mHeight - 45); } void BufferShuffler::DrawModuleUnclipped() { if (mDrawDebug) DrawTextNormal(mDebugDisplayText, 0, mHeight + 20); } void BufferShuffler::DrawBuffer(float x, float y, float w, float h) { ofPushMatrix(); ofTranslate(x, y); DrawAudioBuffer(w, h, &mInputBuffer, 0, GetLengthInSamples(), -1); ofPopMatrix(); ofPushStyle(); ofFill(); float writePosX = x + GetWritePositionInSamples(gTime) / (float)GetLengthInSamples() * w; ofSetColor(200, 200, 200); ofCircle(writePosX, y, 3); if (mPlaybackSampleIndex != -1) { float playPosX = x + mPlaybackSampleIndex / (float)GetLengthInSamples() * w; ofSetColor(0, 255, 0); ofLine(playPosX, y, playPosX, y + h); } if (mFourTet > 0) { float playPosX = x + mFourTetSampleIndex / (float)GetLengthInSamples() * w; ofSetColor(0, 255, 0); ofLine(playPosX, y, playPosX, y + h); } ofSetColor(255, 255, 255, 35); int numSlices = GetNumSlices(); for (int i = 0; i < numSlices; i += 2) ofRect(x + i * w / numSlices, y, w / numSlices, h); ofPopStyle(); } void BufferShuffler::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (velocity > 0) { mQueuedSlice = pitch; if (mUseVelocitySpeedControl) mQueuedPlaybackStyle = VelocityToPlaybackStyle(velocity); mPlaybackSampleStartTime = time; mPlaybackSampleStopTime = -1; } else { if (mQueuedSlice == pitch) { mQueuedSlice = -1; mPlaybackSampleStopTime = time; } } } int BufferShuffler::GetNumSlices() { return TheTransport->CountInStandardMeasure(mInterval) * TheTransport->GetTimeSigTop() / TheTransport->GetTimeSigBottom() * mNumBars; } void BufferShuffler::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); if (!right && x >= 5 && x <= mWidth - 5 && y > 20) { float bufferWidth = mWidth - 10; float pos = (x - 5) / bufferWidth; int slice = int(pos * GetNumSlices()); PlayOneShot(slice); } } void BufferShuffler::PlayOneShot(int slice) { mQueuedSlice = slice; double sliceSizeMs = TheTransport->GetMeasureFraction(mInterval) * TheTransport->MsPerBar(); double currentTime = NextBufferTime(false); double remainderMs; TransportListenerInfo timeInfo(nullptr, mInterval, OffsetInfo(0, false), false); TheTransport->GetQuantized(currentTime, &timeInfo, &remainderMs); double timeUntilNextInterval = sliceSizeMs - remainderMs; mPlaybackSampleStartTime = currentTime + timeUntilNextInterval; mPlaybackSampleStopTime = mPlaybackSampleStartTime + sliceSizeMs / abs(GetSlicePlaybackRate()); } int BufferShuffler::GetWritePositionInSamples(double time) { return GetLengthInSamples() / mNumBars * ((TheTransport->GetMeasure(time) % mNumBars) + TheTransport->GetMeasurePos(time)); } int BufferShuffler::GetLengthInSamples() { return mNumBars * TheTransport->MsPerBar() * gSampleRateMs; } BufferShuffler::PlaybackStyle BufferShuffler::VelocityToPlaybackStyle(int velocity) const { if (velocity > 100) return PlaybackStyle::Normal; if (velocity > 80) return PlaybackStyle::Double; if (velocity > 60) return PlaybackStyle::Half; if (velocity > 40) return PlaybackStyle::Reverse; if (velocity > 20) return PlaybackStyle::DoubleReverse; else return PlaybackStyle::HalfReverse; } float BufferShuffler::GetSlicePlaybackRate() const { switch (mPlaybackStyle) { case PlaybackStyle::Normal: return 1; case PlaybackStyle::Double: return 2; case PlaybackStyle::Half: return .5f; case PlaybackStyle::Reverse: return -1; case PlaybackStyle::DoubleReverse: return -2; case PlaybackStyle::HalfReverse: return -.5f; default: return 1; } } bool BufferShuffler::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 = 7 - gridIndex / 8; int index = x + y * 8; if (y == 7) { if (midiValue > 0 && x < 5) mPlaybackStyle = PlaybackStyle(x + 1); else mPlaybackStyle = PlaybackStyle::Normal; } else if (index < GetNumSlices() && midiValue > 0) { PlayOneShot(index); } return true; } } return false; } void BufferShuffler::UpdatePush2Leds(Push2Control* push2) { for (int x = 0; x < 8; ++x) { for (int y = 0; y < 8; ++y) { int pushColor = 0; int index = x + y * 8; int writeSlice = GetWritePositionInSamples(gTime) * GetNumSlices() / GetLengthInSamples(); int playSlice = mPlaybackSampleIndex * GetNumSlices() / GetLengthInSamples(); if (y == 7) { if (x < 5) pushColor = (x == (int)mPlaybackStyle - 1) ? 2 : 1; } else if (index < GetNumSlices()) { if (index == mQueuedSlice && mPlaybackSampleStartTime != -1) pushColor = 32; else if (mPlaybackSampleIndex >= 0 && index == playSlice) pushColor = 126; else if (mPlaybackSampleIndex == -1 && index == writeSlice) pushColor = 120; else pushColor = 16; } push2->SetLed(kMidiMessage_Note, x + (7 - y) * 8 + 36, pushColor); } } } bool BufferShuffler::DrawToPush2Screen() { DrawBuffer(371, 10, 400, 60); return false; } void BufferShuffler::OnControllerPageSelected() { if (mGridControlTarget->GetGridController()) mGridControlTarget->GetGridController()->ResetLights(); UpdateGridControllerLights(true); } void BufferShuffler::OnGridButton(int x, int y, float velocity, IGridController* grid) { if (velocity > 0) { int index = x + y * mGridControlTarget->GetGridController()->NumCols(); if (index >= 0 && index < GetNumSlices()) PlayOneShot(index); } } void BufferShuffler::UpdateGridControllerLights(bool force) { if (mGridControlTarget->GetGridController() == nullptr) return; for (int x = 0; x < mGridControlTarget->GetGridController()->NumCols(); ++x) { for (int y = 0; y < mGridControlTarget->GetGridController()->NumRows(); ++y) { GridColor color = kGridColorOff; int index = x + y * mGridControlTarget->GetGridController()->NumCols(); int writeSlice = GetWritePositionInSamples(gTime) * GetNumSlices() / GetLengthInSamples(); int playSlice = mPlaybackSampleIndex * GetNumSlices() / GetLengthInSamples(); if (index < GetNumSlices()) { if (index == mQueuedSlice && mPlaybackSampleStartTime != -1) color = kGridColor2Dim; else if (mPlaybackSampleIndex >= 0 && index == playSlice) color = kGridColor2Bright; else if (mPlaybackSampleIndex == -1 && index == writeSlice) color = kGridColor1Bright; else color = kGridColor1Dim; } mGridControlTarget->GetGridController()->SetLight(x, y, color, force); } } } void BufferShuffler::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadBool("use_velocity_speed_control", moduleInfo, false); mModuleSaveData.LoadBool("only_play_when_triggered", moduleInfo, false); SetUpFromSaveData(); } void BufferShuffler::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); mUseVelocitySpeedControl = mModuleSaveData.GetBool("use_velocity_speed_control"); mOnlyPlayWhenTriggered = mModuleSaveData.GetBool("only_play_when_triggered"); } void BufferShuffler::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); out << mWidth; out << mHeight; out << gSampleRate; out << GetLengthInSamples(); out << mInputBuffer.NumActiveChannels(); mInputBuffer.Save(out, GetLengthInSamples()); } void BufferShuffler::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (rev < 0) return; LoadStateValidate(rev <= GetModuleSaveStateRev()); in >> mWidth; in >> mHeight; Resize(mWidth, mHeight); int savedSampleRate; in >> savedSampleRate; int savedLength; in >> savedLength; int savedChannelCount; in >> savedChannelCount; if (savedSampleRate == gSampleRate) { mInputBuffer.Load(in, savedLength, ChannelBuffer::LoadMode::kAnyBufferSize); } else { ChannelBuffer readBuffer(savedLength); readBuffer.Load(in, savedLength, ChannelBuffer::LoadMode::kAnyBufferSize); float sampleRateRatio = (float)gSampleRate / savedSampleRate; int adjustedLength = savedLength * sampleRateRatio; mInputBuffer.SetNumActiveChannels(savedChannelCount); for (int ch = 0; ch < savedChannelCount; ++ch) { float* destBuffer = mInputBuffer.GetChannel(ch); float* srcBuffer = readBuffer.GetChannel(ch); for (int i = 0; i < adjustedLength; ++i) destBuffer[i] = GetInterpolatedSample(i / sampleRateRatio, srcBuffer, savedLength); } } } ```
/content/code_sandbox/Source/BufferShuffler.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
4,580
```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 **/ // // TimerDisplay.cpp // Bespoke // // Created by Ryan Challinor on 7/2/14. // // #include "TimerDisplay.h" #include "SynthGlobals.h" #include "ModularSynth.h" TimerDisplay::TimerDisplay() { mStartTime = gTime; } void TimerDisplay::CreateUIControls() { IDrawableModule::CreateUIControls(); mResetButton = new ClickButton(this, "reset", 15, 39); } TimerDisplay::~TimerDisplay() { } void TimerDisplay::ButtonClicked(ClickButton* button, double time) { if (button == mResetButton) mStartTime = gTime; } void TimerDisplay::DrawModule() { if (Minimized() || IsVisible() == false) return; mResetButton->Draw(); int secs = (int)((gTime - mStartTime) / 1000); int mins = secs / 60; secs %= 60; std::string zeroPadMins = ""; if (mins < 10) zeroPadMins = "0"; std::string zeroPadSecs = ""; if (secs < 10) zeroPadSecs = "0"; ofPushStyle(); ofSetColor(255, 255, 255); gFont.DrawString(zeroPadMins + ofToString(mins) + ":" + zeroPadSecs + ofToString(secs), 52, 15, 36); ofPopStyle(); } ```
/content/code_sandbox/Source/TimerDisplay.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
419
```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 **/ /* ============================================================================== MathUtils.cpp Created: 12 Nov 2017 8:24:59pm Author: Ryan Challinor ============================================================================== */ #include "MathUtils.h" namespace MathUtils { float Bezier(float t, float p0, float p1, float p2, float p3) { return CUBE(1 - t) * p0 + 3 * SQUARE(1 - t) * t * p1 + 3 * (1 - t) * SQUARE(t) * p2 + CUBE(t) * p3; } ofVec2f Bezier(float t, ofVec2f p0, ofVec2f p1, ofVec2f p2, ofVec2f p3) { return ofVec2f(Bezier(t, p0.x, p1.x, p2.x, p3.x), Bezier(t, p0.y, p1.y, p2.y, p3.y)); //below comments help visualize bezier /*if (t < .333f) return ofVec2f(ofLerp(p0.x,p1.x, t*3), ofLerp(p0.y,p1.y, t*3)); else if (t < .666f) return ofVec2f(ofLerp(p1.x,p2.x,(t-.333f)*3), ofLerp(p1.y,p2.y,(t-.333f)*3)); else return ofVec2f(ofLerp(p2.x,p3.x, (t-.666f)*3), ofLerp(p2.y,p3.y, (t-.666f)*3));*/ } float BezierDerivative(float t, float p0, float p1, float p2, float p3) { return 3 * SQUARE(1 - t) * (p1 - p0) + 6 * (1 - t) * t * (p2 - p1) + 3 * t * t * (p3 - p2); } ofVec2f BezierPerpendicular(float t, ofVec2f p0, ofVec2f p1, ofVec2f p2, ofVec2f p3) { ofVec2f perp(-BezierDerivative(t, p0.y, p1.y, p2.y, p3.y), BezierDerivative(t, p0.x, p1.x, p2.x, p3.x)); return perp / sqrt(perp.lengthSquared()); } ofVec2f ScaleVec(ofVec2f a, ofVec2f b) { return ofVec2f(a.x * b.x, a.y * b.y); } ofVec2f Normal(ofVec2f v) { return v / sqrtf(v.lengthSquared()); } float Curve(float t, float curve) { return powf(t, expf(-2 * curve)); } int HighestPow2(int n) { int res = 0; for (int i = n; i >= 1; i--) { // If i is a power of 2 if ((i & (i - 1)) == 0) { res = i; break; } } return res; } }; ```
/content/code_sandbox/Source/MathUtils.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
822
```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 **/ // originally from Quuxplusone/Xoshiro256ss. // Upstream's public domain, so I assume all's ok. // Original comment: // The "xoshiro256** 1.0" generator. // C++ port by Arthur O'Dwyer (2021). // Based on the C version by David Blackman and Sebastiano Vigna (2018), // path_to_url #ifndef BESPOKESYNTH_XOSHIRO256SS_H #define BESPOKESYNTH_XOSHIRO256SS_H #include <cstddef> #include <cstdint> #include <climits> // CHAR_BIT #include <random> namespace bespoke::core { namespace detail { template <class T> constexpr size_t BitSizeOf() { return sizeof(T) * CHAR_BIT; } constexpr std::uint64_t splitmix64(std::uint64_t x) { std::uint64_t z = (x += 0x9e3779b97f4a7c15uLL); z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9uLL; z = (z ^ (z >> 27)) * 0x94d049bb133111ebuLL; return z ^ (z >> 31); } constexpr std::uint64_t rotl(std::uint64_t x, int k) { return (x << k) | (x >> (BitSizeOf<std::uint64_t>() - k)); } /** * Xoshiro256** as a C++ RandomNumberEngine, * which can be used in C++ random algorithms. */ struct Xoshiro256ss { using result_type = std::uint64_t; std::uint64_t s[4]{}; constexpr explicit Xoshiro256ss() : Xoshiro256ss(0) { } constexpr explicit Xoshiro256ss(std::uint64_t seed) { s[0] = splitmix64(seed); s[1] = splitmix64(seed); s[2] = splitmix64(seed); s[3] = splitmix64(seed); } /** * Constructor for seeding from a `std::random_device`. * * \param[in] rd Random device to seed this engine with. */ constexpr explicit Xoshiro256ss(std::random_device& rd) { // Get 64 bits out of the random device. // // This lambda is quite literal, as it fetches // 2 iterations of the random engine, and // shifts + OR's them into a 64bit value. auto get_u64 = [&rd] { std::uint64_t the_thing = rd(); return (the_thing << 32) | rd(); }; // seed with 256 bits of entropy from the random device + splitmix64 // to ensure we seed it well, as per recommendation. s[0] = splitmix64(get_u64()); s[1] = splitmix64(get_u64()); s[2] = splitmix64(get_u64()); s[3] = splitmix64(get_u64()); } static constexpr result_type min() { return 0; } static constexpr result_type max() { return std::uint64_t(-1); } constexpr result_type operator()() { result_type result = rotl(s[1] * 5, 7) * 9; result_type t = s[1] << 17; s[2] ^= s[0]; s[3] ^= s[1]; s[1] ^= s[2]; s[0] ^= s[3]; s[2] ^= t; s[3] = rotl(s[3], 45); return result; } }; } using detail::Xoshiro256ss; } #endif //BESPOKESYNTH_XOSHIRO256SS_H ```
/content/code_sandbox/Source/Xoshiro256ss.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
992
```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 **/ // // LiveGranulator.h // modularSynth // // Created by Ryan Challinor on 10/2/13. // // #pragma once #include <iostream> #include "IAudioEffect.h" #include "IDrawableModule.h" #include "Checkbox.h" #include "Granulator.h" #include "Slider.h" #include "RollingBuffer.h" #include "Transport.h" #include "DropdownList.h" #define FREEZE_EXTRA_SAMPLES_COUNT 2 * gSampleRate class LiveGranulator : public IAudioEffect, public IFloatSliderListener, public ITimeListener, public IDropdownListener { public: LiveGranulator(); virtual ~LiveGranulator(); static IAudioEffect* Create() { return new LiveGranulator(); } 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 "granulator"; } void OnTimeEvent(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; bool IsEnabled() const override { return mEnabled; } private: void Freeze(); //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override { w = mWidth; h = mHeight; } float mBufferLength; RollingBuffer mBuffer; Granulator mGranulator; FloatSlider* mGranOverlap{ nullptr }; FloatSlider* mGranSpeed{ nullptr }; FloatSlider* mGranLengthMs{ nullptr }; FloatSlider* mGranPosRandomize{ nullptr }; FloatSlider* mGranSpeedRandomize{ nullptr }; FloatSlider* mGranSpacingRandomize{ nullptr }; Checkbox* mGranOctaveCheckbox{ nullptr }; float mDry{ 0 }; FloatSlider* mDrySlider{ nullptr }; bool mFreeze{ false }; Checkbox* mFreezeCheckbox{ nullptr }; int mFreezeExtraSamples{ 0 }; float mPos{ 0 }; FloatSlider* mPosSlider{ nullptr }; NoteInterval mAutoCaptureInterval{ NoteInterval::kInterval_None }; DropdownList* mAutoCaptureDropdown{ nullptr }; FloatSlider* mWidthSlider{ nullptr }; float mWidth{ 200 }; float mHeight{ 20 }; float mBufferX{ 0 }; }; ```
/content/code_sandbox/Source/LiveGranulator.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
675
```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 **/ // // CanvasControls.cpp // Bespoke // // Created by Ryan Challinor on 12/30/14. // // #include "CanvasControls.h" #include "OpenFrameworksPort.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Canvas.h" #include "CanvasElement.h" CanvasControls::CanvasControls() { } CanvasControls::~CanvasControls() { } void CanvasControls::CreateUIControls() { IDrawableModule::CreateUIControls(); mRemoveElementButton = new ClickButton(this, "delete", 5, 1); mNumVisibleRowsEntry = new TextEntry(this, "view rows", 175, 1, 3, &mCanvas->mNumVisibleRows, 1, 9999); mClearButton = new ClickButton(this, "clear", 270, 1); mDragModeSelector = new DropdownList(this, "drag mode", 310, 1, (int*)(&mCanvas->mDragMode)); mDragModeSelector->AddLabel("drag both", Canvas::kDragBoth); mDragModeSelector->AddLabel("horizontal", Canvas::kDragHorizontal); mDragModeSelector->AddLabel("vertical", Canvas::kDragVertical); mNumVisibleRowsEntry->DrawLabel(true); // Block modulator cables from connecting to these controls. mRemoveElementButton->SetCableTargetable(false); mNumVisibleRowsEntry->SetCableTargetable(false); mClearButton->SetCableTargetable(false); mDragModeSelector->SetCableTargetable(false); mNumVisibleRowsEntry->SetCableTargetable(false); SetElement(nullptr); } void CanvasControls::SetCanvas(Canvas* canvas) { mCanvas = canvas; mWidth = mCanvas->GetWidth(); mCanvas->SetControls(this); StringCopy(NameMutable(), (std::string(mCanvas->Name()) + "_controls").c_str(), MAX_TEXTENTRY_LENGTH); } void CanvasControls::SetElement(CanvasElement* element) { if (mSelectedElement) { for (auto* control : mSelectedElement->GetUIControls()) control->SetShowing(false); } mSelectedElement = element; if (mSelectedElement) { int idx = 0; for (auto* control : mSelectedElement->GetUIControls()) { control->SetShowing(true); control->SetPosition(5 + (idx / 4) * 110, 20 + (idx % 4) * 18); ++idx; } } } void CanvasControls::AllowDragModeSelection(bool allow) { mDragModeSelector->SetShowing(allow); } void CanvasControls::PreDrawModule() { float x, y; mCanvas->GetPosition(x, y, K(localOnly)); SetPosition(x, y + 13 + mCanvas->GetHeight()); } void CanvasControls::DrawModule() { ofPushStyle(); ofFill(); ofSetColor(100, 100, 100); ofRect(0, 0, mWidth, 19); ofPopStyle(); mRemoveElementButton->Draw(); mNumVisibleRowsEntry->Draw(); mClearButton->Draw(); mDragModeSelector->Draw(); if (mSelectedElement) { for (auto* control : mSelectedElement->GetUIControls()) control->Draw(); } } void CanvasControls::GetModuleDimensions(float& width, float& height) { width = mWidth; height = 92; } void CanvasControls::CheckboxUpdated(Checkbox* checkbox, double time) { for (auto* element : mCanvas->GetElements()) { if (element->GetHighlighted()) element->CheckboxUpdated(checkbox->Name(), checkbox->GetValue() > 0, time); } } void CanvasControls::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { for (auto* element : mCanvas->GetElements()) { if (element->GetHighlighted()) element->FloatSliderUpdated(slider->Name(), oldVal, slider->GetValue(), time); } } void CanvasControls::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { for (auto* element : mCanvas->GetElements()) { if (element->GetHighlighted()) element->IntSliderUpdated(slider->Name(), oldVal, slider->GetValue(), time); } } void CanvasControls::TextEntryComplete(TextEntry* entry) { if (entry == mNumVisibleRowsEntry) { if (mCanvas->mNumVisibleRows > mCanvas->GetNumRows()) mCanvas->mNumVisibleRows = mCanvas->GetNumRows(); } } void CanvasControls::ButtonClicked(ClickButton* button, double time) { if (button == mRemoveElementButton) { mSelectedElement = nullptr; std::vector<CanvasElement*> elementsToDelete; for (auto* element : mCanvas->GetElements()) { if (element->GetHighlighted()) elementsToDelete.push_back(element); } for (auto* element : elementsToDelete) { for (auto* control : element->GetUIControls()) { control->SetShowing(false); RemoveUIControl(control); control->Delete(); } mCanvas->RemoveElement(element); } } if (button == mClearButton) { mCanvas->Clear(); } std::vector<CanvasElement*> elements = mCanvas->GetElements(); //make a copy of the list, since I may modify the list through the actions below for (auto* element : elements) { if (element->GetHighlighted()) element->ButtonClicked(button->Name(), time); } } void CanvasControls::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void CanvasControls::SetUpFromSaveData() { } ```
/content/code_sandbox/Source/CanvasControls.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,378
```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 **/ // // DotGrid.h // Bespoke // // Created by Ryan Challinor on 12/27/23. // // #pragma once #include "IUIControl.h" #include "SynthGlobals.h" class DotGrid : public IUIControl { public: static constexpr int kMaxCols = 128; static constexpr int kMaxRows = 128; struct DotPosition { DotPosition(int col, int row) : mCol(col) , mRow(row) {} void Clear() { mCol = -1; mRow = -1; } bool IsValid() const { return mCol != -1; } int mCol; int mRow; }; struct DotData { bool mOn; float mVelocity; float mLength; double mLastPlayTime; //unserialized }; DotGrid(IClickable* parent, std::string name, int x, int y, int w, int h, int cols, int rows); void Init(int x, int y, int w, int h, int cols, int rows, IClickable* parent); void SetGrid(int cols, int rows); int GetRows() { return mRows; } int GetCols() { return mCols; } void Render() override; 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; void SetHighlightCol(double time, int col); int GetHighlightCol(double time) const; void SetMajorColSize(int size) { mMajorCol = size; } int GetMajorColSize() const { return mMajorCol; } void Clear(); void SetDimensions(float width, float height) { mWidth = width; mHeight = height; } float GetWidth() const { return mWidth; } float GetHeight() const { return mHeight; } const std::array<DotData, kMaxCols * kMaxRows>& GetData() const { return mData; } void SetData(std::array<DotData, kMaxCols * kMaxRows>& data) { mData = data; } bool GetNoHover() const override { return true; } bool CanBeTargetedBy(PatchCableSource* source) const override; const DotData& GetDataAt(int col, int row) const; void OnPlayed(double time, int col, int row); float GetDotSize() const; int GetMaxColumns() const { return kMaxCols; } void CopyDot(DotPosition from, DotPosition to); bool IsValidPosition(DotPosition pos) const; DotPosition GetGridCellAt(float x, float y, bool clamp = true); ofVec2f GetCellPosition(int col, int row); //IUIControl void SetFromMidiCC(float slider, double time, bool setViaModulator) override {} void SetValue(float value, double time, bool forceUpdate = false) override {} bool IsSliderControl() override { return false; } bool IsButtonControl() override { return false; } bool ShouldSerializeForSnapshot() const override { return true; } void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, bool shouldSetValue = true) override; protected: ~DotGrid(); //protected so that it can't be created on the stack private: void OnClicked(float x, float y, bool right) override; void GetDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } void KeyPressed(int key, bool repeat) override; int GetDataIndex(int col, int row) const { return col + row * kMaxCols; } float GetX(int col) const; float GetY(int row) const; void DrawGridCircle(int col, int row, float radiusPercent) const; struct HighlightColBuffer { double time{ 0 }; int col{ -1 }; }; enum class DragBehavior { Pending, Length, Velocity }; DragBehavior mDragBehavior{ DragBehavior::Pending }; float mWidth{ 200 }; float mHeight{ 200 }; int mRows{ 0 }; int mCols{ 0 }; bool mClick{ false }; DotPosition mHoldCell{ -1, -1 }; ofVec2f mLastDragPosition{ -1, -1 }; bool mMouseReleaseCanClear{ false }; std::array<DotData, kMaxCols * kMaxRows> mData{}; std::array<HighlightColBuffer, 10> mHighlightColBuffer{}; int mNextHighlightColPointer{ 0 }; int mMajorCol{ -1 }; DotPosition mCurrentHover{ -1, -1 }; }; ```
/content/code_sandbox/Source/DotGrid.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,183
```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 **/ /* ============================================================================== PulseDelayer.cpp Created: 15 Feb 2020 2:53:22pm Author: Ryan Challinor ============================================================================== */ #include "PulseDelayer.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" #include "Profiler.h" PulseDelayer::PulseDelayer() { } void PulseDelayer::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } PulseDelayer::~PulseDelayer() { TheTransport->RemoveAudioPoller(this); } void PulseDelayer::CreateUIControls() { IDrawableModule::CreateUIControls(); mDelaySlider = new FloatSlider(this, "delay", 4, 4, 100, 15, &mDelay, 0, 1, 4); } void PulseDelayer::DrawModule() { if (Minimized() || IsVisible() == false) return; mDelaySlider->Draw(); float t = (gTime - mLastPulseTime) / (mDelay * TheTransport->GetDuration(kInterval_1n)); if (t > 0 && t < 1) { ofPushStyle(); ofNoFill(); ofCircle(54, 11, 10); ofFill(); ofSetColor(255, 255, 255, gModuleDrawAlpha); ofCircle(54 + sin(t * TWO_PI) * 10, 11 - cos(t * TWO_PI) * 10, 2); ofPopStyle(); } } void PulseDelayer::CheckboxUpdated(Checkbox* checkbox, double time) { if (!mEnabled) mConsumeIndex = mAppendIndex; //effectively clears the queue } void PulseDelayer::OnTransportAdvanced(float amount) { PROFILER(PulseDelayer); ComputeSliders(0); int end = mAppendIndex; if (mAppendIndex < mConsumeIndex) end += kQueueSize; for (int i = mConsumeIndex; i < end; ++i) { const PulseInfo& info = mInputPulses[i % kQueueSize]; if (gTime + TheTransport->GetEventLookaheadMs() >= info.mTriggerTime) { DispatchPulse(GetPatchCableSource(), info.mTriggerTime, info.mVelocity, info.mFlags); mConsumeIndex = (mConsumeIndex + 1) % kQueueSize; } } } void PulseDelayer::OnPulse(double time, float velocity, int flags) { if (!mEnabled) { DispatchPulse(GetPatchCableSource(), time, velocity, flags); return; } if (velocity > 0) mLastPulseTime = time; if ((mAppendIndex + 1) % kQueueSize != mConsumeIndex) { PulseInfo info; info.mVelocity = velocity; info.mTriggerTime = time + mDelay / (float(TheTransport->GetTimeSigTop()) / TheTransport->GetTimeSigBottom()) * TheTransport->MsPerBar(); info.mFlags = flags; mInputPulses[mAppendIndex] = info; mAppendIndex = (mAppendIndex + 1) % kQueueSize; } } void PulseDelayer::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void PulseDelayer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void PulseDelayer::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/PulseDelayer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
911
```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 **/ // // Oscillator.cpp // Bespoke // // Created by Ryan Challinor on 7/3/14. // // #include "Oscillator.h" float Oscillator::Value(float phase) const { if (mType == kOsc_Tri) phase += .5f * FPI; //shift phase to make triangle start at zero instead of 1, to eliminate click on start if (mShuffle > 0) { phase = fmod(phase, FTWO_PI * 2); float shufflePoint = FTWO_PI * (1 + mShuffle); if (phase < shufflePoint) phase = phase / (1 + mShuffle); else phase = (phase - shufflePoint) / (1 - mShuffle); } phase = fmod(phase, FTWO_PI); float sample = 0; switch (mType) { case kOsc_Sin: sample = sin(phase); break; case kOsc_Saw: sample = SawSample(phase); break; case kOsc_NegSaw: sample = -SawSample(phase); break; case kOsc_Square: if (mSoften == 0) { sample = phase > (FTWO_PI * mPulseWidth) ? -1 : 1; } else { float phase01 = phase / FTWO_PI; phase01 += .75f; phase01 -= (mPulseWidth - .5f) / 2; phase01 -= int(phase01); sample = ofClamp((fabs(phase01 - .5f) * 4 - 1 + (mPulseWidth - .5f) * 2) / mSoften, -1, 1); } break; case kOsc_Tri: sample = fabs(phase / FTWO_PI - .5f) * 4 - 1; break; case kOsc_Random: sample = ofRandom(-1, 1); break; default: //assert(false); break; } if (mType != kOsc_Square && mPulseWidth != .5f) sample = (Bias(sample / 2 + .5f, mPulseWidth) - .5f) * 2; //give "pulse width" to non-square oscillators return sample; } float Oscillator::SawSample(float phase) const { phase /= FTWO_PI; if (mSoften == 0) return phase * 2 - 1; if (phase < 1 - mSoften) return phase / (1 - mSoften) * 2 - 1; return 1 - ((phase - (1 - mSoften)) / mSoften * 2); } ```
/content/code_sandbox/Source/Oscillator.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
725
```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 **/ /* ============================================================================== MPETweaker.cpp Created: 6 Aug 2021 9:11:13pm Author: Ryan Challinor ============================================================================== */ #include "MPETweaker.h" #include "OpenFrameworksPort.h" #include "ModularSynth.h" #include "UIControlMacros.h" MPETweaker::MPETweaker() { for (int voiceIdx = -1; voiceIdx < kNumVoices; ++voiceIdx) { mModulationMult.GetPitchBend(voiceIdx)->SetValue(1); mModulationOffset.GetPitchBend(voiceIdx)->SetValue(0); mModulationMult.GetPressure(voiceIdx)->SetValue(1); mModulationOffset.GetPressure(voiceIdx)->SetValue(0); mModulationMult.GetModWheel(voiceIdx)->SetValue(1); mModulationOffset.GetModWheel(voiceIdx)->SetValue(0); } } MPETweaker::~MPETweaker() { } void MPETweaker::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK(130); FLOATSLIDER_DIGITS(mPitchBendMultiplierSlider, "pitchbend mult", &mPitchBendMultiplier, -3, 3, 2); UIBLOCK_SHIFTRIGHT(); FLOATSLIDER_DIGITS(mPitchBendOffsetSlider, "pitchbend offset", &mPitchBendOffset, -1, 1, 1); UIBLOCK_NEWLINE(); FLOATSLIDER_DIGITS(mPressureMultiplierSlider, "pressure mult", &mPressureMultiplier, -3, 3, 2); UIBLOCK_SHIFTRIGHT(); FLOATSLIDER_DIGITS(mPressureOffsetSlider, "pressure offset", &mPressureOffset, -1, 1, 1); UIBLOCK_NEWLINE(); FLOATSLIDER_DIGITS(mModWheelMultiplierSlider, "modwheel mult", &mModWheelMultiplier, -3, 3, 2); UIBLOCK_SHIFTRIGHT(); FLOATSLIDER_DIGITS(mModWheelOffsetSlider, "modwheel offset", &mModWheelOffset, -1, 1, 1); UIBLOCK_NEWLINE(); ENDUIBLOCK(mWidth, mHeight); } void MPETweaker::DrawModule() { if (Minimized() || IsVisible() == false) return; mPitchBendMultiplierSlider->Draw(); mPitchBendOffsetSlider->Draw(); mPressureMultiplierSlider->Draw(); mPressureOffsetSlider->Draw(); mModWheelMultiplierSlider->Draw(); mModWheelOffsetSlider->Draw(); } void MPETweaker::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled) { mModulationMult.GetPitchBend(voiceIdx)->MultiplyIn(modulation.pitchBend); mModulationOffset.GetPitchBend(voiceIdx)->AppendTo(mModulationMult.GetPitchBend(voiceIdx)); modulation.pitchBend = mModulationOffset.GetPitchBend(voiceIdx); mModulationMult.GetPressure(voiceIdx)->MultiplyIn(modulation.pressure); mModulationOffset.GetPressure(voiceIdx)->AppendTo(mModulationMult.GetPressure(voiceIdx)); modulation.pressure = mModulationOffset.GetPressure(voiceIdx); mModulationMult.GetModWheel(voiceIdx)->MultiplyIn(modulation.modWheel); mModulationOffset.GetModWheel(voiceIdx)->AppendTo(mModulationMult.GetModWheel(voiceIdx)); modulation.modWheel = mModulationOffset.GetModWheel(voiceIdx); } PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void MPETweaker::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mPitchBendMultiplierSlider) { for (int voiceIdx = -1; voiceIdx < kNumVoices; ++voiceIdx) mModulationMult.GetPitchBend(voiceIdx)->SetValue(mPitchBendMultiplier); } if (slider == mPitchBendOffsetSlider) { for (int voiceIdx = -1; voiceIdx < kNumVoices; ++voiceIdx) mModulationOffset.GetPitchBend(voiceIdx)->SetValue(mPitchBendOffset); } if (slider == mPressureMultiplierSlider) { for (int voiceIdx = -1; voiceIdx < kNumVoices; ++voiceIdx) mModulationMult.GetPressure(voiceIdx)->SetValue(mPressureMultiplier); } if (slider == mPressureOffsetSlider) { for (int voiceIdx = -1; voiceIdx < kNumVoices; ++voiceIdx) mModulationOffset.GetPressure(voiceIdx)->SetValue(mPressureOffset); } if (slider == mModWheelMultiplierSlider) { for (int voiceIdx = -1; voiceIdx < kNumVoices; ++voiceIdx) mModulationMult.GetModWheel(voiceIdx)->SetValue(mModWheelMultiplier); } if (slider == mModWheelOffsetSlider) { for (int voiceIdx = -1; voiceIdx < kNumVoices; ++voiceIdx) mModulationOffset.GetModWheel(voiceIdx)->SetValue(mModWheelOffset); } } void MPETweaker::CheckboxUpdated(Checkbox* checkbox, double time) { } void MPETweaker::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void MPETweaker::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/MPETweaker.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,337
```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 **/ // // ADSRDisplay.h // modularSynth // // Created by Ryan Challinor on 4/28/13. // // #pragma once #include "IUIControl.h" #include "ADSR.h" #include "Slider.h" class IDrawableModule; class EnvelopeEditor; class ADSRDisplay : public IUIControl { public: ADSRDisplay(IDrawableModule* owner, const char* name, int x, int y, int w, int h, ::ADSR* adsr); void Render() override; void MouseReleased() override; bool MouseMoved(float x, float y) override; void SetVol(float vol) { mVol = vol; } void SetHighlighted(bool highlighted) { mHighlighted = highlighted; } float GetMaxTime() const { return mMaxTime; } float& GetMaxTime() { return mMaxTime; } void SetMaxTime(float maxTime); void SetADSR(::ADSR* adsr); ::ADSR* GetADSR() { return mAdsr; } void SpawnEnvelopeEditor(); void SetOverrideDrawTime(double time) { mOverrideDrawTime = time; } void SetDimensions(float w, float h) { mWidth = w; mHeight = h; } void SetShowing(bool showing) override { IUIControl::SetShowing(showing); UpdateSliderVisibility(); } FloatSlider* GetASlider() { return mASlider; } FloatSlider* GetDSlider() { return mDSlider; } FloatSlider* GetSSlider() { return mSSlider; } FloatSlider* GetRSlider() { return mRSlider; } //IUIControl void SetFromMidiCC(float slider, double time, bool setViaModulator) override {} void SetValue(float value, double time, bool forceUpdate = false) override {} bool CanBeTargetedBy(PatchCableSource* source) const override { return false; } void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, bool shouldSetValue = true) override; bool GetNoHover() const override { return true; } enum DisplayMode { kDisplayEnvelope, kDisplaySliders }; static void ToggleDisplayMode(); protected: ~ADSRDisplay(); //protected so that it can't be created on the stack private: enum AdjustParam { kAdjustAttack, kAdjustDecaySustain, kAdjustRelease, kAdjustEnvelopeEditor, kAdjustNone, kAdjustAttackAR, kAdjustReleaseAR, kAdjustViewLength } mAdjustMode{ AdjustParam::kAdjustNone }; void OnClicked(float x, float y, bool right) override; void GetDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } void UpdateSliderVisibility(); ofVec2f GetDrawPoint(float time, const ADSR::EventInfo& adsrEvent); float mWidth; float mHeight; float mVol{ 1 }; float mMaxTime{ 1000 }; bool mClick{ false }; ::ADSR* mAdsr; ofVec2f mClickStart; ::ADSR mClickAdsr; float mClickLength{ 1000 }; bool mHighlighted{ false }; FloatSlider* mASlider{ nullptr }; FloatSlider* mDSlider{ nullptr }; FloatSlider* mSSlider{ nullptr }; FloatSlider* mRSlider{ nullptr }; static DisplayMode sDisplayMode; EnvelopeEditor* mEditor{ nullptr }; double mOverrideDrawTime{ -1 }; std::array<double, 10> mDrawTimeHistory{}; int mDrawTimeHistoryIndex{ 0 }; }; ```
/content/code_sandbox/Source/ADSRDisplay.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
934
```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 **/ // // SampleCanvas.cpp // Bespoke // // Created by Ryan Challinor on 6/24/15. // // #include "SampleCanvas.h" #include "IAudioReceiver.h" #include "IAudioSource.h" #include "SynthGlobals.h" #include "DrumPlayer.h" #include "ModularSynth.h" #include "CanvasControls.h" #include "CanvasElement.h" #include "Profiler.h" #include "Sample.h" #include "CanvasTimeline.h" #include "CanvasScrollbar.h" SampleCanvas::SampleCanvas() { } void SampleCanvas::CreateUIControls() { IDrawableModule::CreateUIControls(); mNumMeasuresSlider = new IntSlider(this, "measures", 5, 5, 100, 15, &mNumMeasures, 1, 16); mIntervalSelector = new DropdownList(this, "interval", 110, 5, (int*)(&mInterval)); 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); mCanvas = new Canvas(this, 5, 35, 790, 100, mNumMeasures, L(rows, 4), L(cols, 4), &(SampleCanvasElement::Create)); AddUIControl(mCanvas); mCanvasControls = new CanvasControls(); mCanvasControls->SetCanvas(mCanvas); mCanvasControls->CreateUIControls(); AddChild(mCanvasControls); UpdateNumColumns(); mCanvas->SetListener(this); mCanvasTimeline = new CanvasTimeline(mCanvas, "timeline"); AddUIControl(mCanvasTimeline); mCanvasScrollbarHorizontal = new CanvasScrollbar(mCanvas, "scrollh", CanvasScrollbar::Style::kHorizontal); AddUIControl(mCanvasScrollbarHorizontal); mCanvasScrollbarVertical = new CanvasScrollbar(mCanvas, "scrollv", CanvasScrollbar::Style::kVertical); AddUIControl(mCanvasScrollbarVertical); } SampleCanvas::~SampleCanvas() { mCanvas->SetListener(nullptr); } void SampleCanvas::Process(double time) { PROFILER(SampleCanvas); IAudioReceiver* target = GetTarget(); if (!mEnabled || target == nullptr) return; float canvasPos = GetCurPos(time); mCanvas->SetCursorPos(canvasPos); int bufferSize = target->GetBuffer()->BufferSize(); assert(bufferSize == gBufferSize); gWorkChannelBuffer.Clear(); const std::vector<CanvasElement*>& elements = mCanvas->GetElements(); for (int elemIdx = 0; elemIdx < elements.size(); ++elemIdx) { SampleCanvasElement* element = static_cast<SampleCanvasElement*>(elements[elemIdx]); Sample* clip = element->GetSample(); float vol = element->GetVolume(); if (clip == nullptr || element->IsMuted()) continue; for (int i = 0; i < bufferSize; ++i) { float sampleIndex = 0; float pos = GetCurPos(time + i * gInvSampleRateMs); sampleIndex = ofMap(pos, element->GetStart(), element->GetEnd(), 0, clip->LengthInSamples()); if (sampleIndex >= 0 && sampleIndex < clip->LengthInSamples()) { for (int ch = 0; ch < target->GetBuffer()->NumActiveChannels(); ++ch) { int sampleChannel = MAX(ch, clip->NumChannels() - 1); gWorkChannelBuffer.GetChannel(ch)[i] += GetInterpolatedSample(sampleIndex, clip->Data()->GetChannel(sampleChannel), clip->LengthInSamples()) * vol; } } } } for (int ch = 0; ch < target->GetBuffer()->NumActiveChannels(); ++ch) { ChannelBuffer* out = GetTarget()->GetBuffer(); Add(out->GetChannel(ch), gWorkChannelBuffer.GetChannel(ch), gBufferSize); GetVizBuffer()->WriteChunk(gWorkChannelBuffer.GetChannel(ch), gBufferSize, ch); } } double SampleCanvas::GetCurPos(double time) const { int loopMeasures = MAX(1, int(mCanvas->mLoopEnd - mCanvas->mLoopStart)); return (((TheTransport->GetMeasure(time) % loopMeasures) + TheTransport->GetMeasurePos(time)) + mCanvas->mLoopStart) / mCanvas->GetLength(); } void SampleCanvas::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); /*float canvasX,canvasY; mCanvas->GetPosition(canvasX, canvasY, true); if (y >= 0 && y < canvasY) { float pos = float(x - canvasX)/mCanvas->GetWidth() * mCanvas->GetNumCols(); TheTransport->SetMeasureTime(pos); }*/ } void SampleCanvas::CanvasUpdated(Canvas* canvas) { if (canvas == mCanvas) { } } namespace { const float extraW = 20; const float extraH = 163; } void SampleCanvas::Resize(float w, float h) { w = MAX(w - extraW, 390); h = MAX(h - extraH, 40); mCanvas->SetDimensions(w, h); } void SampleCanvas::GetModuleDimensions(float& width, float& height) { width = mCanvas->GetWidth() + extraW; height = mCanvas->GetHeight() + extraH; } void SampleCanvas::FilesDropped(std::vector<std::string> files, int x, int y) { Sample sample; sample.Read(files[0].c_str()); SampleDropped(x, y, &sample); } void SampleCanvas::SampleDropped(int x, int y, Sample* sample) { CanvasCoord coord = mCanvas->GetCoordAt(x - mCanvas->GetPosition(true).x, y - mCanvas->GetPosition(true).y); coord.col = MAX(0, coord.col); coord.row = MAX(0, coord.row); SampleCanvasElement* element = static_cast<SampleCanvasElement*>(mCanvas->CreateElement(coord.col, coord.row)); Sample* newSamp = new Sample(); newSamp->CopyFrom(sample); element->SetSample(newSamp); double lengthMs = sample->LengthInSamples() / sample->GetSampleRateRatio() / gSampleRateMs; element->mLength = lengthMs / TheTransport->GetDuration(mInterval); mCanvas->AddElement(element); mCanvas->SelectElement(element); } void SampleCanvas::DrawModule() { if (Minimized() || IsVisible() == false) return; mNumMeasuresSlider->Draw(); mIntervalSelector->Draw(); mCanvas->Draw(); mCanvasTimeline->Draw(); mCanvasScrollbarHorizontal->Draw(); mCanvasScrollbarVertical->Draw(); mCanvasControls->Draw(); } void SampleCanvas::SetNumMeasures(int numMeasures) { mNumMeasures = numMeasures; mCanvas->SetLength(mNumMeasures); mCanvas->SetNumCols(TheTransport->CountInStandardMeasure(mInterval) * mNumMeasures); if (mInterval < kInterval_8n) mCanvas->SetMajorColumnInterval(TheTransport->CountInStandardMeasure(mInterval)); else mCanvas->SetMajorColumnInterval(TheTransport->CountInStandardMeasure(mInterval) / 4); mCanvas->mViewStart = 0; mCanvas->mViewEnd = mNumMeasures; mCanvas->mLoopStart = 0; mCanvas->mLoopEnd = mNumMeasures; } void SampleCanvas::UpdateNumColumns() { mCanvas->RescaleNumCols(TheTransport->CountInStandardMeasure(mInterval) * mNumMeasures); if (mInterval < kInterval_8n) mCanvas->SetMajorColumnInterval(TheTransport->CountInStandardMeasure(mInterval)); else mCanvas->SetMajorColumnInterval(TheTransport->CountInStandardMeasure(mInterval) / 4); } void SampleCanvas::CheckboxUpdated(Checkbox* checkbox, double time) { } void SampleCanvas::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void SampleCanvas::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mNumMeasuresSlider) { SetNumMeasures(mNumMeasures); } } void SampleCanvas::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mIntervalSelector) { UpdateNumColumns(); } } void SampleCanvas::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadInt("rows", moduleInfo, 4, 1, 30, K(isTextField)); SetUpFromSaveData(); } void SampleCanvas::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); mCanvas->SetNumRows(mModuleSaveData.GetInt("rows")); } void SampleCanvas::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); out << mCanvas->GetWidth(); out << mCanvas->GetHeight(); } void SampleCanvas::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 w, h; in >> w; in >> h; mCanvas->SetDimensions(w, h); } ```
/content/code_sandbox/Source/SampleCanvas.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,378
```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 **/ // // Pumper.cpp // modularSynth // // Created by Ryan Challinor on 3/16/13. // // #include "Pumper.h" #include "Profiler.h" #include "UIControlMacros.h" #include "ModularSynth.h" namespace { const int kAdsrTime = 10000; } Pumper::Pumper() { mAdsr.SetNumStages(2); mAdsr.GetStageData(0).time = kAdsrTime * .05f; mAdsr.GetStageData(0).target = .25f; mAdsr.GetStageData(0).curve = 0; mAdsr.GetStageData(1).time = kAdsrTime * .3f; mAdsr.GetStageData(1).target = 1; mAdsr.GetStageData(1).curve = -0.5f; SyncToAdsr(); } void Pumper::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); FLOATSLIDER(mAmountSlider, "amount", &mAmount, 0, 1); FLOATSLIDER(mLengthSlider, "length", &mLength, 0, 1); FLOATSLIDER(mCurveSlider, "curve", &mAdsr.GetStageData(1).curve, -1, 1); FLOATSLIDER(mAttackSlider, "attack", &mAttack, 0, 1); DROPDOWN(mIntervalSelector, "interval", (int*)(&mInterval), 40); UIBLOCK_SHIFTRIGHT(); ENDUIBLOCK(mWidth, mHeight); mIntervalSelector->AddLabel("1n", kInterval_1n); mIntervalSelector->AddLabel("2n", kInterval_2n); mIntervalSelector->AddLabel("4n", kInterval_4n); mIntervalSelector->AddLabel("8n", kInterval_8n); mIntervalSelector->AddLabel("16n", kInterval_16n); mIntervalSelector->AddLabel("32n", kInterval_32n); } Pumper::~Pumper() { } void Pumper::ProcessAudio(double time, ChannelBuffer* buffer) { PROFILER(Pumper); if (!mEnabled) return; float bufferSize = buffer->BufferSize(); ComputeSliders(0); double intervalPos = GetIntervalPos(time); ADSR::EventInfo adsrEvent(0, kAdsrTime); adsrEvent.mStartBlendFromValue = 1; /*const float smoothingTimeMs = 35; float smoothingOffset = smoothingTimeMs / TheTransport->GetDuration(mInterval); mLFO.SetOffset(mOffset + smoothingOffset);*/ for (int i = 0; i < bufferSize; ++i) { float adsrValue = mAdsr.Value((intervalPos + i * gInvSampleRateMs / TheTransport->GetDuration(mInterval)) * kAdsrTime, &adsrEvent); float value = mLastValue * .99f + adsrValue * .01f; for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) buffer->GetChannel(ch)[i] *= value; mLastValue = value; } } double Pumper::GetIntervalPos(double time) { return fmod(TheTransport->GetMeasurePos(time) * TheTransport->CountInStandardMeasure(mInterval), 1.0); } void Pumper::DrawModule() { if (!mEnabled) return; mAmountSlider->Draw(); mLengthSlider->Draw(); mCurveSlider->Draw(); mAttackSlider->Draw(); mIntervalSelector->Draw(); ofPushStyle(); ofSetColor(0, 200, 0, 50); ofFill(); ofRect(0, mHeight * .8f, mLastValue * mWidth, mHeight * .2f); ofPopStyle(); ofPushStyle(); ofSetColor(245, 58, 135); ofBeginShape(); ADSR::EventInfo adsrEvent(0, kAdsrTime); adsrEvent.mStartBlendFromValue = 1; for (int i = 0; i < mWidth; i++) { float x = i; float y = mAdsr.Value(float(i) / mWidth * kAdsrTime, &adsrEvent) * mHeight; ofVertex(x, mHeight - y); } ofEndShape(false); ofSetColor(255, 255, 255, 100); { float x = GetIntervalPos(gTime) * mWidth; ofLine(x, 0, x, mHeight); } ofPopStyle(); } float Pumper::GetEffectAmount() { if (!mEnabled) return 0; return mAmount; } void Pumper::DropdownUpdated(DropdownList* list, int oldVal, double time) { } void Pumper::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mAmountSlider) { mAdsr.GetStageData(0).target = 1 - mAmount; } if (slider == mLengthSlider) { mAdsr.GetStageData(1).time = (mLength + mAttack) * kAdsrTime; } if (slider == mAttackSlider) { mAdsr.GetStageData(0).time = mAttack * kAdsrTime; mAdsr.GetStageData(1).time = (mLength + mAttack) * kAdsrTime; } } void Pumper::SyncToAdsr() { mAmount = 1 - mAdsr.GetStageData(0).target; mLength = (mAdsr.GetStageData(1).time - mAdsr.GetStageData(0).time) / kAdsrTime; mAttack = mAdsr.GetStageData(0).time / kAdsrTime; } void Pumper::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); mAdsr.SaveState(out); } void Pumper::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); mAdsr.LoadState(in); SyncToAdsr(); } ```
/content/code_sandbox/Source/Pumper.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,531
```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 **/ // // INonstandardController.h // Bespoke // // Created by Ryan Challinor on 5/1/14. // // #pragma once #include "MidiController.h" class ofxJSONElement; class INonstandardController { public: virtual ~INonstandardController() {} virtual void SendValue(int page, int control, float value, bool forceNoteOn = false, int channel = -1) = 0; virtual bool IsInputConnected() { return true; } virtual bool Reconnect() { return true; } virtual void Poll() {} virtual std::string GetControlTooltip(MidiMessageType type, int control) { return MidiController::GetDefaultTooltip(type, control); } virtual void SetLayoutData(ofxJSONElement& layout) {} virtual void SaveState(FileStreamOut& out) = 0; virtual void LoadState(FileStreamIn& in) = 0; }; ```
/content/code_sandbox/Source/INonstandardController.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
295
```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.cpp // Bespoke // // Created by Ryan Challinor on 5/6/16. // // #include "VelocityScaler.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" VelocityScaler::VelocityScaler() { } void VelocityScaler::CreateUIControls() { IDrawableModule::CreateUIControls(); mScaleSlider = new FloatSlider(this, "scale", 4, 2, 100, 15, &mScale, 0, 2); } void VelocityScaler::DrawModule() { if (Minimized() || IsVisible() == false) return; mScaleSlider->Draw(); } void VelocityScaler::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled) { ComputeSliders(0); if (velocity > 0) velocity = MAX(1, velocity * mScale); } PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void VelocityScaler::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void VelocityScaler::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/VelocityScaler.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
384
```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 **/ /* ============================================================================== LinnstrumentControl.h Created: 28 Oct 2018 2:17:18pm Author: Ryan Challinor ============================================================================== */ #pragma once #include <iostream> #include "MidiDevice.h" #include "IDrawableModule.h" #include "INoteReceiver.h" #include "DropdownList.h" #include "Scale.h" #include "ModulationChain.h" #include "Slider.h" class IAudioSource; class LinnstrumentControl : public IDrawableModule, public INoteReceiver, public IDropdownListener, public IScaleListener, public IFloatSliderListener, public MidiDeviceListener { public: LinnstrumentControl(); virtual ~LinnstrumentControl(); static IDrawableModule* Create() { return new LinnstrumentControl(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void Init() override; void Poll() override; 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 {} enum LinnstrumentColor { kLinnColor_Off, kLinnColor_Red, kLinnColor_Yellow, kLinnColor_Green, kLinnColor_Cyan, kLinnColor_Blue, kLinnColor_Magenta, kLinnColor_Black, kLinnColor_White, kLinnColor_Orange, kLinnColor_Lime, kLinnColor_Pink, kLinnColor_Invalid }; void SetGridColor(int x, int y, LinnstrumentColor color, bool ignoreRow = false); void OnMidiNote(MidiNote& note) override; void OnMidiControl(MidiControl& control) override; void OnScaleChanged() override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void DropdownClicked(DropdownList* list) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, 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 true; } private: void InitController(); void BuildControllerList(); void UpdateScaleDisplay(); void SendScaleInfo(); LinnstrumentColor GetDesiredGridColor(int x, int y); int GridToPitch(int x, int y); void SetPitchColor(int pitch, LinnstrumentColor color); void SendNRPN(int param, int value); //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override { w = 190; h = 7 + 17 * 4; } int mControllerIndex{ -1 }; DropdownList* mControllerList{ nullptr }; struct NoteAge { double mTime{ 0 }; int mColor{ 0 }; int mVoiceIndex{ -1 }; int mOutputPitch{ 0 }; void Update(int pitch, LinnstrumentControl* linnstrument); }; static const int kRows = 8; static const int kCols = 25; std::array<LinnstrumentColor, kRows * kCols> mGridColorState; std::array<NoteAge, 128> mNoteAge; float mDecayMs{ 500 }; FloatSlider* mDecaySlider{ nullptr }; bool mBlackout{ false }; Checkbox* mBlackoutCheckbox{ nullptr }; bool mLightOctaves{ false }; Checkbox* mLightOctavesCheckbox{ nullptr }; int mLinnstrumentOctave{ 5 }; bool mGuitarLines{ false }; Checkbox* mGuitarLinesCheckbox{ nullptr }; bool mControlPlayedLights{ true }; int mLastReceivedNRPNParamMSB{ 0 }; int mLastReceivedNRPNParamLSB{ 0 }; int mLastReceivedNRPNValueMSB{ 0 }; int mLastReceivedNRPNValueLSB{ 0 }; std::array<ModulationParameters, kNumVoices> mModulators; double mRequestedOctaveTime{ 0 }; MidiDevice mDevice; }; ```
/content/code_sandbox/Source/LinnstrumentControl.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,098
```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 **/ // // FreeverbEffect.cpp // Bespoke // // Created by Ryan Challinor on 12/19/14. // // #include "FreeverbEffect.h" #include "OpenFrameworksPort.h" #include "SynthGlobals.h" #include "Profiler.h" FreeverbEffect::FreeverbEffect() { //mFreeverb.setmode(GetParameter(KMode)); mFreeverb.setroomsize(mRoomSize); mFreeverb.setdamp(mDamp); mFreeverb.setwet(mWet); mFreeverb.setdry(mDry); mFreeverb.setwidth(mVerbWidth); mFreeverb.update(); } FreeverbEffect::~FreeverbEffect() { } void FreeverbEffect::CreateUIControls() { IDrawableModule::CreateUIControls(); mRoomSizeSlider = new FloatSlider(this, "room size", 5, 4, 95, 15, &mRoomSize, .1f, 1, 3); mRoomSizeSlider->SetMode(FloatSlider::Mode::kBezier); mDampSlider = new FloatSlider(this, "damp", 5, 20, 95, 15, &mDamp, 0, 100); mWetSlider = new FloatSlider(this, "wet", 5, 36, 95, 15, &mWet, 0, 1); mDrySlider = new FloatSlider(this, "dry", 5, 52, 95, 15, &mDry, 0, 1); mWidthSlider = new FloatSlider(this, "width", 5, 68, 95, 15, &mVerbWidth, 0, 100); } void FreeverbEffect::ProcessAudio(double time, ChannelBuffer* buffer) { PROFILER(FreeverbEffect); if (!mEnabled) return; float bufferSize = buffer->BufferSize(); ComputeSliders(0); if (mNeedUpdate) { mFreeverb.update(); mNeedUpdate = false; } int secondChannel = 1; if (buffer->NumActiveChannels() <= 1) secondChannel = 0; mFreeverb.processreplace(buffer->GetChannel(0), buffer->GetChannel(secondChannel), buffer->GetChannel(0), buffer->GetChannel(secondChannel), bufferSize, 1); } void FreeverbEffect::DrawModule() { if (!mEnabled) return; mRoomSizeSlider->Draw(); mDampSlider->Draw(); mWetSlider->Draw(); mDrySlider->Draw(); mWidthSlider->Draw(); } void FreeverbEffect::GetModuleDimensions(float& width, float& height) { if (mEnabled) { width = 105; height = 84; } else { width = 105; height = 0; } } float FreeverbEffect::GetEffectAmount() { if (!mEnabled) return 0; return mWet; } void FreeverbEffect::CheckboxUpdated(Checkbox* checkbox, double time) { } void FreeverbEffect::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mRoomSizeSlider) { mFreeverb.setroomsize(mRoomSize); mNeedUpdate = true; } if (slider == mDampSlider) { mFreeverb.setdamp(mDamp); mNeedUpdate = true; } if (slider == mWetSlider) { mFreeverb.setwet(mWet); mNeedUpdate = true; } if (slider == mDrySlider) { mFreeverb.setdry(mDry); mNeedUpdate = true; } if (slider == mWidthSlider) { mFreeverb.setwidth(mVerbWidth); mNeedUpdate = true; } } ```
/content/code_sandbox/Source/FreeverbEffect.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
947
```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 **/ /* ============================================================================== PlaySequencer.h Created: 12 Dec 2020 11:00:20pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "Transport.h" #include "Checkbox.h" #include "DropdownList.h" #include "ClickButton.h" #include "Slider.h" #include "UIGrid.h" #include "Scale.h" #include "ModulationChain.h" #include "GridController.h" class PlaySequencer : public NoteEffectBase, public IDrawableModule, public ITimeListener, public IButtonListener, public IDropdownListener, public IIntSliderListener, public IFloatSliderListener, public IGridControllerListener { public: PlaySequencer(); ~PlaySequencer(); static IDrawableModule* Create() { return new PlaySequencer(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; //IDrawableModule void Init() override; bool IsResizable() const override { return true; } void Resize(float w, float h) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } //IClickable void MouseReleased() override; bool MouseMoved(float x, float y) override; //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; //IGridControllerListener void OnControllerPageSelected() override; void OnGridButton(int x, int y, float velocity, IGridController* grid) override; //ITimeListener void OnTimeEvent(double time) override; //IButtonListener void ButtonClicked(ClickButton* button, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; //IDropdownListener void DropdownUpdated(DropdownList* list, int oldVal, double time) override; //IIntSliderListener void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; //IFloatSliderListener void FloatSliderUpdated(FloatSlider* slider, float oldVal, 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& w, float& h) override; void OnClicked(float x, float y, bool right) override; void SetGridSize(float w, float h); int GetStep(double time); void UpdateInterval(); void UpdateNumMeasures(int oldNumMeasures); void UpdateLights(bool betweener = false); int GetVelocityLevel(); class NoteOffScheduler : public ITimeListener { public: //ITimeListener void OnTimeEvent(double time) override; PlaySequencer* mOwner{ nullptr }; }; NoteInterval mInterval{ NoteInterval::kInterval_16n }; int mNumMeasures{ 1 }; bool mWrite{ false }; bool mNoteRepeat{ false }; bool mLinkColumns{ false }; float mWidth{ 240 }; float mHeight{ 20 }; bool mUseLightVelocity{ false }; bool mUseMedVelocity{ false }; bool mClearLane{ false }; bool mSustain{ false }; float mVelocityFull{ 1 }; float mVelocityMed{ .5 }; float mVelocityLight{ .25 }; DropdownList* mIntervalSelector{ nullptr }; Checkbox* mWriteCheckbox{ nullptr }; Checkbox* mNoteRepeatCheckbox{ nullptr }; Checkbox* mLinkColumnsCheckbox{ nullptr }; DropdownList* mNumMeasuresSelector{ nullptr }; UIGrid* mGrid{ nullptr }; GridControlTarget* mGridControlTarget{ nullptr }; NoteOffScheduler mNoteOffScheduler; struct PlayLane { int mInputVelocity{ 0 }; bool mIsPlaying{ false }; Checkbox* mMuteOrEraseCheckbox{ nullptr }; bool mMuteOrErase{ false }; }; std::array<PlayLane, 16> mLanes; struct SavedPattern { ClickButton* mStoreButton{ nullptr }; ClickButton* mLoadButton{ nullptr }; float mNumMeasures{ 1 }; std::array<float, MAX_GRID_COLS * MAX_GRID_ROWS> mData{}; bool mHasSequence{ false }; }; std::array<SavedPattern, 5> mSavedPatterns; TransportListenerInfo* mTransportListenerInfo{ nullptr }; }; ```
/content/code_sandbox/Source/PlaySequencer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,199
```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 **/ // // GateEffect.h // modularSynth // // Created by Ryan Challinor on 4/19/13. // // #pragma once #include <iostream> #include "IAudioEffect.h" #include "Slider.h" #include "Checkbox.h" class GateEffect : public IAudioEffect, public IIntSliderListener, public IFloatSliderListener { public: GateEffect(); static IAudioEffect* Create() { return new GateEffect(); } void CreateUIControls() override; void SetAttack(float ms) { mAttackTime = ms; } void SetRelease(float ms) { mReleaseTime = ms; } bool IsGateOpen() const { return mEnvelope > 0; } //IAudioEffect void ProcessAudio(double time, ChannelBuffer* buffer) override; void SetEnabled(bool enabled) override { mEnabled = enabled; } std::string GetType() override { return "gate"; } void CheckboxUpdated(Checkbox* checkbox, double time) override; void IntSliderUpdated(IntSlider* slider, int oldVal, 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 = 50; } float mThreshold{ .1 }; float mAttackTime{ 1 }; float mReleaseTime{ 1 }; FloatSlider* mThresholdSlider{ nullptr }; FloatSlider* mAttackSlider{ nullptr }; FloatSlider* mReleaseSlider{ nullptr }; float mEnvelope{ 0 }; float mPeak{ 0 }; }; ```
/content/code_sandbox/Source/GateEffect.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
481
```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 **/ // // NoteToFreq.cpp // Bespoke // // Created by Ryan Challinor on 12/17/15. // // #include "NoteToFreq.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "ModulationChain.h" NoteToFreq::NoteToFreq() { } NoteToFreq::~NoteToFreq() { } void NoteToFreq::CreateUIControls() { IDrawableModule::CreateUIControls(); mTargetCable = new PatchCableSource(this, kConnectionType_Modulator); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); } void NoteToFreq::DrawModule() { if (Minimized() || IsVisible() == false) return; } void NoteToFreq::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { OnModulatorRepatch(); } void NoteToFreq::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled && velocity > 0) { mPitch = pitch; mPitchBend = modulation.pitchBend; } } float NoteToFreq::Value(int samplesIn) { float bend = mPitchBend ? mPitchBend->GetValue(samplesIn) : 0; return TheScale->PitchToFreq(mPitch + bend); } void NoteToFreq::SaveLayout(ofxJSONElement& moduleInfo) { } void NoteToFreq::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void NoteToFreq::SetUpFromSaveData() { } ```
/content/code_sandbox/Source/NoteToFreq.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
467
```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 **/ /* ============================================================================== OpenFrameworksPort.cpp Created: 30 May 2016 9:13:01pm Author: Ryan Challinor ============================================================================== */ #ifdef BESPOKE_WINDOWS #include <windows.h> #endif #include "juce_opengl/juce_opengl.h" using namespace juce::gl; using namespace juce; #include <VersionInfo.h> #include "OpenFrameworksPort.h" #include "nanovg/nanovg.h" #define NANOVG_GLES2_IMPLEMENTATION #include "nanovg/nanovg_gl.h" #include "ModularSynth.h" #include "Push2Control.h" #include "UserData.h" ofColor ofColor::black(0, 0, 0); ofColor ofColor::white(255, 255, 255); ofColor ofColor::grey(128, 128, 128); ofColor ofColor::red(255, 0, 0); ofColor ofColor::green(0, 200, 0); ofColor ofColor::yellow(255, 255, 0); ofColor ofColor::orange(255, 165, 0); ofColor ofColor::blue(0, 0, 255); ofColor ofColor::purple(148, 0, 211); ofColor ofColor::lime(0, 255, 0); ofColor ofColor::magenta(255, 0, 255); ofColor ofColor::cyan(0, 255, 255); ofColor ofColor::clear(0, 0, 0, 0); NVGcontext* gNanoVG = nullptr; NVGcontext* gFontBoundsNanoVG = nullptr; std::string ofToDataPath(const std::string& path) { if (!path.empty() && (path[0] == '.' || juce::File::isAbsolutePath(path))) return path; static const auto sDataDir = [] { auto defaultDataDir = juce::File::getSpecialLocation(juce::File::userDocumentsDirectory).getChildFile("BespokeSynth").getFullPathName().toStdString(); auto dataDir = juce::SystemStats::getEnvironmentVariable("BESPOKE_DATA_DIR", defaultDataDir).toStdString(); #if BESPOKE_WINDOWS std::replace(begin(dataDir), end(dataDir), '\\', '/'); #endif UpdateUserData(dataDir); dataDir += '/'; return dataDir; }(); return sDataDir + path; } std::string ofToFactoryPath(const std::string& subdir) { std::string result; #if BESPOKE_MAC auto resDir = juce::File::getSpecialLocation(juce::File::SpecialLocationType::currentApplicationFile).getChildFile("Contents/Resources").getChildFile(subdir); #else auto resDir = juce::File::getSpecialLocation(juce::File::SpecialLocationType::currentExecutableFile).getSiblingFile(subdir); #if BESPOKE_LINUX if (!resDir.isDirectory()) { resDir = juce::File::getSpecialLocation(juce::File::SpecialLocationType::currentApplicationFile).getChildFile("../../share/BespokeSynth").getChildFile(subdir); if (!resDir.isDirectory()) resDir = juce::File{ juce::CharPointer_UTF8{ Bespoke::CMAKE_INSTALL_PREFIX } }.getChildFile("share/BespokeSynth").getChildFile(subdir); } #endif #endif if (!resDir.isDirectory()) throw std::runtime_error{ "Application directory not found. Please reinstall Bespoke." }; result = resDir.getFullPathName().toStdString(); #if BESPOKE_WINDOWS std::replace(begin(result), end(result), '\\', '/'); #endif return result; } std::string ofToResourcePath(const std::string& path) { if (!path.empty() && (path[0] == '.' || juce::File::isAbsolutePath(path))) return path; static const auto sResourceDir = ofToFactoryPath("resource") + '/'; return sResourceDir + path; } struct StyleStack { struct Style { Style() : fill(false) , color(255, 255, 255) , lineWidth(1) {} bool fill; ofColor color; float lineWidth; }; StyleStack() { stack.push_front(Style()); } void Push() { stack.push_front(GetStyle()); } void Pop() { stack.pop_front(); } Style& GetStyle() { return *stack.begin(); } std::list<Style> stack; }; static StyleStack sStyleStack; void ofPushStyle() { sStyleStack.Push(); } void ofPopStyle() { sStyleStack.Pop(); ofSetColor(sStyleStack.GetStyle().color); ofSetLineWidth(sStyleStack.GetStyle().lineWidth); } void ofPushMatrix() { nvgSave(gNanoVG); } void ofPopMatrix() { nvgRestore(gNanoVG); } void ofTranslate(float x, float y, float z) { nvgTranslate(gNanoVG, x, y); } void ofRotate(float radians) { nvgRotate(gNanoVG, radians); } void ofClipWindow(float x, float y, float width, float height, bool intersectWithExisting) { if (intersectWithExisting) nvgIntersectScissor(gNanoVG, x, y, width, height); else nvgScissor(gNanoVG, x, y, width, height); } void ofResetClipWindow() { nvgResetScissor(gNanoVG); } void ofSetColor(float r, float g, float b, float a) { sStyleStack.GetStyle().color = ofColor(r, g, b, a); if (Push2Control::sDrawingPush2Display) { nvgStrokeColor(gNanoVG, nvgRGBA(r, g, b, a)); nvgFillColor(gNanoVG, nvgRGBA(r, g, b, a)); return; } static int sImage = -1; if (sImage == -1) sImage = nvgCreateImage(gNanoVG, ofToResourcePath("noise.jpg").c_str(), NVG_IMAGE_REPEATX | NVG_IMAGE_REPEATY); NVGpaint pattern = nvgImagePattern(gNanoVG, ofRandom(0, 10), ofRandom(0, 10), 300 / gDrawScale / TheSynth->GetPixelRatio(), 300 / gDrawScale / TheSynth->GetPixelRatio(), ofRandom(0, 10), sImage, a); pattern.innerColor = nvgRGBA(r, g, b, a); pattern.outerColor = nvgRGBA(r, g, b, a); nvgStrokePaint(gNanoVG, pattern); nvgFillPaint(gNanoVG, pattern); } void ofSetColorGradient(const ofColor& colorA, const ofColor& colorB, ofVec2f gradientStart, ofVec2f gradientEnd) { sStyleStack.GetStyle().color = colorA; if (Push2Control::sDrawingPush2Display) { nvgStrokeColor(gNanoVG, nvgRGBA(colorA.r, colorA.g, colorA.b, colorA.a)); nvgFillColor(gNanoVG, nvgRGBA(colorA.r, colorA.g, colorA.b, colorA.a)); return; } NVGpaint pattern = nvgLinearGradient(gNanoVG, gradientStart.x, gradientStart.y, gradientEnd.x, gradientEnd.y, nvgRGBA(colorA.r, colorA.g, colorA.b, colorA.a), nvgRGBA(colorB.r, colorB.g, colorB.b, colorB.a)); nvgStrokePaint(gNanoVG, pattern); nvgFillPaint(gNanoVG, pattern); } void ofSetColor(float grey) { ofSetColor(grey, grey, grey); } void ofSetColor(const ofColor& color) { ofSetColor(color.r, color.g, color.b, color.a); } void ofSetColor(const ofColor& color, float a) { ofSetColor(color.r, color.g, color.b, a); } void ofFill() { sStyleStack.GetStyle().fill = true; } void ofNoFill() { sStyleStack.GetStyle().fill = false; } void ofCircle(float x, float y, float radius) { nvgBeginPath(gNanoVG); nvgCircle(gNanoVG, x, y, radius); if (sStyleStack.GetStyle().fill) nvgFill(gNanoVG); else nvgStroke(gNanoVG); } void ofRect(float x, float y, float width, float height, float cornerRadius /*=3*/) { nvgBeginPath(gNanoVG); nvgRoundedRect(gNanoVG, x, y, width, height, cornerRadius * gCornerRoundness); if (sStyleStack.GetStyle().fill) nvgFill(gNanoVG); else nvgStroke(gNanoVG); } void ofRect(const ofRectangle& rect, float cornerRadius /*=3*/) { ofRect(rect.x, rect.y, rect.width, rect.height, cornerRadius); } float ofClamp(float val, float a, float b) { if (val < a) return a; if (val > b) return b; return val; } float ofGetLastFrameTime() { /*TODO_PORT(Ryan)*/ return .01666f; } int ofToInt(const std::string& intString) { String str(intString); return str.getIntValue(); } float ofToFloat(const std::string& floatString) { String str(floatString); return str.getFloatValue(); } int ofHexToInt(const std::string& hexString) { String str(hexString); return str.getHexValue32(); } void ofLine(float x1, float y1, float x2, float y2) { nvgBeginPath(gNanoVG); nvgMoveTo(gNanoVG, x1, y1); nvgLineTo(gNanoVG, x2, y2); nvgStroke(gNanoVG); } void ofLine(ofVec2f v1, ofVec2f v2) { ofLine(v1.x, v1.y, v2.x, v2.y); } void ofSetLineWidth(float width) { sStyleStack.GetStyle().lineWidth = width; const float kLineWidthAdjustAmount = 0.25f; const float kLineWidthAdjustFactor = 1.5f; nvgStrokeWidth(gNanoVG, width * kLineWidthAdjustFactor + kLineWidthAdjustAmount); } namespace { std::vector<ofVec2f> gShapePoints; } void ofBeginShape() { gShapePoints.clear(); nvgBeginPath(gNanoVG); } void ofEndShape(bool close) { if (sStyleStack.GetStyle().fill) nvgFill(gNanoVG); else nvgStroke(gNanoVG); } void ofVertex(float x, float y, float z) { if (gShapePoints.empty()) nvgMoveTo(gNanoVG, x, y); else nvgLineTo(gNanoVG, x, y); gShapePoints.push_back(ofVec2f(x, y)); } void ofVertex(ofVec2f point) { ofVertex(point.x, point.y); } float ofMap(float val, float fromStart, float fromEnd, float toStart, float toEnd, bool clamp) { float ret; if (fromEnd - fromStart != 0) ret = ((val - fromStart) / (fromEnd - fromStart)) * (toEnd - toStart) + toStart; else ret = toEnd; if (clamp) ret = ofClamp(ret, MIN(toStart, toEnd), MAX(toStart, toEnd)); return ret; } float ofRandom(float max) { return max * gRandom01(gRandom); } float ofRandom(float x, float y) { // if there is no range, return the value if (x == y) return x; // float == ?, wise? epsilon? const float high = MAX(x, y); const float low = MIN(x, y); return low + ((high - low) * gRandom01(gRandom)); } void ofSetCircleResolution(float res) { } #if BESPOKE_WINDOWS namespace windowsport { struct timespec { long tv_sec; long tv_nsec; }; //header part int clock_gettime(int, struct timespec* spec) //C-file part { __int64 wintime; GetSystemTimeAsFileTime((FILETIME*)&wintime); wintime -= 116444736000000000ll; //1jan1601 to 1jan1970 spec->tv_sec = wintime / 10000000ll; //seconds spec->tv_nsec = wintime % 10000000ll * 100; //nano-seconds return 0; } } unsigned long long ofGetSystemTimeNanos() { //auto now = std::chrono::high_resolution_clock::now(); //return std::chrono::duration_cast<std::chrono:nanoseconds>(now.time_since_epoch()).count(); struct windowsport::timespec t; windowsport::clock_gettime(0, &t); return t.tv_sec * 1000000000 + t.tv_nsec; } #else unsigned long long ofGetSystemTimeNanos() { //auto now = std::chrono::high_resolution_clock::now(); //return std::chrono::duration_cast<std::chrono:nanoseconds>(now.time_since_epoch()).count(); struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1000000000 + t.tv_nsec; } #endif float ofGetWidth() { return TheSynth->GetMainComponent()->getWidth(); } float ofGetHeight() { return TheSynth->GetMainComponent()->getHeight(); } float ofGetFrameRate() { return TheSynth->GetFrameRate(); } float ofLerp(float start, float stop, float amt) { return start + (stop - start) * amt; } float ofDistSquared(float x1, float y1, float x2, float y2) { return ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } std::vector<std::string> ofSplitString(std::string str, std::string splitter, bool ignoreEmpty, bool trim) { StringArray tokens; tokens.addTokens(String(str), String(splitter), ""); if (ignoreEmpty) tokens.removeEmptyStrings(); if (trim) tokens.trim(); std::vector<std::string> ret; for (auto s : tokens) ret.push_back(s.toStdString()); return ret; } bool ofIsStringInString(const std::string& haystack, const std::string& needle) { return (strstr(haystack.c_str(), needle.c_str()) != nullptr); } void ofScale(float x, float y, float z) { nvgScale(gNanoVG, x, y); } void ofExit() { //TODO_PORT(Ryan) assert(false); } void ofToggleFullscreen() { #if !BESPOKE_WINDOWS if (Desktop::getInstance().getKioskModeComponent() == nullptr) Desktop::getInstance().setKioskModeComponent(TheSynth->GetMainComponent()->getTopLevelComponent(), false); else Desktop::getInstance().setKioskModeComponent(nullptr, false); #endif } void ofStringReplace(std::string& input, std::string searchStr, std::string replaceStr, bool firstOnly /*= false*/) { size_t uPos = 0; size_t uFindLen = searchStr.length(); size_t uReplaceLen = replaceStr.length(); if (uFindLen == 0) { return; } for (; (uPos = input.find(searchStr, uPos)) != std::string::npos;) { input.replace(uPos, uFindLen, replaceStr); uPos += uReplaceLen; if (firstOnly) break; } } //%Y-%m-%d-%H-%M-%S-%i std::string ofGetTimestampString(std::string in) { Time time = Time::getCurrentTime(); ofStringReplace(in, "%Y", ofToString(time.getYear())); char buff[16]; snprintf(buff, sizeof(buff), "%02d", time.getMonth() + 1); ofStringReplace(in, "%m", buff); snprintf(buff, sizeof(buff), "%02d", time.getDayOfMonth()); ofStringReplace(in, "%d", buff); snprintf(buff, sizeof(buff), "%02d", time.getHours()); ofStringReplace(in, "%H", buff); snprintf(buff, sizeof(buff), "%02d", time.getMinutes()); ofStringReplace(in, "%M", buff); snprintf(buff, sizeof(buff), "%02d", time.getSeconds()); ofStringReplace(in, "%S", buff); snprintf(buff, sizeof(buff), "%03d", time.getMilliseconds()); ofStringReplace(in, "%i", buff); return in; } void ofTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { ofBeginShape(); ofVertex(x1, y1); ofVertex(x2, y2); ofVertex(x3, y3); ofVertex(x1, y1); ofEndShape(); } float ofRectangle::getMinX() const { return MIN(x, x + width); // - width } float ofRectangle::getMaxX() const { return MAX(x, x + width); // - width } float ofRectangle::getMinY() const { return MIN(y, y + height); // - height } float ofRectangle::getMaxY() const { return MAX(y, y + height); // - height } bool ofRectangle::intersects(const ofRectangle& other) const { return (getMinX() < other.getMaxX() && getMaxX() > other.getMinX() && getMinY() < other.getMaxY() && getMaxY() > other.getMinY()); } bool ofRectangle::contains(float testX, float testY) const { return testX > getMinX() && testY > getMinY() && testX < getMaxX() && testY < getMaxY(); } void ofColor::setBrightness(int brightness) { float hue, saturation, oldBrightness; getHsb(hue, saturation, oldBrightness); setHsb(hue, saturation, brightness); } int ofColor::getBrightness() const { float max = r; if (g > max) { max = g; } if (b > max) { max = b; } return max; } void ofColor::setSaturation(int saturation) { float hue, oldSaturation, brightness; getHsb(hue, oldSaturation, brightness); setHsb(hue, saturation, brightness); } int ofColor::getSaturation() const { float max = getBrightness(); float min = r; if (g < min) min = g; if (b < min) min = b; if (max == min) // grays return 0; return 255 * (max - min) / max; } void ofColor::getHsb(float& hue, float& saturation, float& brightness) const { float max = getBrightness(); float min = r; if (g < min) { min = g; } if (b < min) { min = b; } if (max == min) { // grays hue = 0.f; saturation = 0.f; brightness = max; return; } float hueSixth; if (r == max) { hueSixth = (g - b) / (max - min); if (hueSixth < 0.f) hueSixth += 6.f; } else if (g == max) { hueSixth = 2.f + (b - r) / (max - min); } else { hueSixth = 4.f + (r - g) / (max - min); } hue = 255 * hueSixth / 6.f; saturation = 255 * (max - min) / max; brightness = max; } void ofColor::setHsb(int hue, int saturation, int brightness) { saturation = ofClamp(saturation, 0, 255); brightness = ofClamp(brightness, 0, 255); if (brightness == 0) { // black set(0, 0, 0); } else if (saturation == 0) { // grays set(brightness, brightness, brightness); } else { float hueSix = hue * 6.f / 255.0f; float saturationNorm = saturation / 255.0f; int hueSixCategory = (int)floorf(hueSix); float hueSixRemainder = hueSix - hueSixCategory; float pv = ((1.f - saturationNorm) * brightness); float qv = ((1.f - saturationNorm * hueSixRemainder) * brightness); float tv = ((1.f - saturationNorm * (1.f - hueSixRemainder)) * brightness); switch (hueSixCategory) { default: case 0: case 6: // r r = brightness; g = tv; b = pv; break; case 1: // g r = qv; g = brightness; b = pv; break; case 2: r = pv; g = brightness; b = tv; break; case 3: // b r = pv; g = qv; b = brightness; break; case 4: r = tv; g = pv; b = brightness; break; case 5: // back to r r = brightness; g = pv; b = qv; break; } } } ofColor ofColor::operator*(const ofColor& other) { return ofColor(r * other.r / 255.0f, g * other.g / 255.0f, b * other.b / 255.0f, a * other.a / 255.0f); } ofColor ofColor::operator*(float f) { return ofColor(r * f, g * f, b * f, a * f); } ofColor ofColor::operator+(const ofColor& other) { return ofColor(r + other.r, g + other.g, b + other.b, a + other.a); } void RetinaTrueTypeFont::LoadFont(std::string path) { mFontPath = ofToDataPath(path); File file(mFontPath.c_str()); if (file.existsAsFile()) { mFontHandle = nvgCreateFont(gNanoVG, path.c_str(), path.c_str()); mFontBoundsHandle = nvgCreateFont(gFontBoundsNanoVG, path.c_str(), path.c_str()); mLoaded = true; } else { mLoaded = false; } } void RetinaTrueTypeFont::DrawString(std::string str, float size, float x, float y) { if (!mLoaded) return; nvgFontFaceId(gNanoVG, mFontHandle); nvgFontSize(gNanoVG, size); if (ofIsStringInString(str, "\n") == false) { nvgText(gNanoVG, x, y, str.c_str(), nullptr); } else { std::vector<std::string> lines = ofSplitString(str, "\n"); float bounds[4]; nvgTextBounds(gNanoVG, 0, 0, str.c_str(), nullptr, bounds); float lineHeight = bounds[3] - bounds[1]; for (int i = 0; i < lines.size(); ++i) { nvgText(gNanoVG, x, y, lines[i].c_str(), nullptr); y += lineHeight; } } } ofRectangle RetinaTrueTypeFont::DrawStringWrap(std::string str, float size, float x, float y, float width) { if (!mLoaded) return ofRectangle(); TheSynth->LockRender(true); nvgFontFaceId(gNanoVG, mFontHandle); nvgFontSize(gNanoVG, size); nvgTextBox(gNanoVG, x, y, width, str.c_str(), nullptr); float bounds[4]; nvgTextBoxBounds(gNanoVG, x, y, width, str.c_str(), nullptr, bounds); ofRectangle rect(bounds[0], bounds[1], bounds[2] - bounds[0], bounds[3] - bounds[1]); TheSynth->LockRender(false); return rect; } float RetinaTrueTypeFont::GetStringWidth(std::string str, float size) { if (!mLoaded) return str.size() * 12; NVGcontext* vg; int handle; if (TheSynth->GetOpenGLContext()->getCurrentContext() != nullptr) { vg = gNanoVG; handle = mFontHandle; } else { vg = gFontBoundsNanoVG; handle = mFontBoundsHandle; } nvgFontFaceId(vg, handle); nvgFontSize(vg, size); float bounds[4]; float width = nvgTextBounds(vg, 0, 0, str.c_str(), nullptr, bounds); return width; } float RetinaTrueTypeFont::GetStringHeight(std::string str, float size) { if (!mLoaded) return str.size() * 12; NVGcontext* vg; int handle; if (TheSynth->GetOpenGLContext()->getCurrentContext() != nullptr) { vg = gNanoVG; handle = mFontHandle; } else { vg = gFontBoundsNanoVG; handle = mFontBoundsHandle; } nvgFontFaceId(vg, handle); nvgFontSize(vg, size); float bounds[4]; nvgTextBounds(vg, 0, 0, str.c_str(), nullptr, bounds); float lineHeight = bounds[3] - bounds[1]; return lineHeight; } ```
/content/code_sandbox/Source/OpenFrameworksPort.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
5,962
```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 **/ // // LaunchpadKeyboard.h // modularSynth // // Created by Ryan Challinor on 11/24/12. // // #pragma once #include <iostream> #include "Scale.h" #include "Checkbox.h" #include "Slider.h" #include "Transport.h" #include "DropdownList.h" #include "IDrawableModule.h" #include "INoteSource.h" #include "GridController.h" #include "Push2Control.h" class LaunchpadNoteDisplayer; class Chorder; class LaunchpadKeyboard : public IDrawableModule, public INoteSource, public IScaleListener, public IIntSliderListener, public ITimeListener, public IDropdownListener, public IFloatSliderListener, public IGridControllerListener, public IPush2GridController { public: LaunchpadKeyboard(); ~LaunchpadKeyboard(); static IDrawableModule* Create() { return new LaunchpadKeyboard(); } 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; } bool HasDebugDraw() const override { return true; } void SetDisplayer(LaunchpadNoteDisplayer* displayer) { mDisplayer = displayer; } void DisplayNote(int pitch, int velocity); void SetChorder(Chorder* chorder) { mChorder = chorder; } //IGridControllerListener void OnControllerPageSelected() override; void OnGridButton(int x, int y, float velocity, IGridController* grid) override; //IScaleListener void OnScaleChanged() override; //IDrawableModule void KeyPressed(int key, bool isRepeat) override; void KeyReleased(int key) override; void Exit() override; void Poll() override; //ITimeListener void OnTimeEvent(double time) 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 IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; void DropdownUpdated(DropdownList* list, int oldVal, 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 mEnabled; } private: enum LaunchpadLayout { kChromatic, kMajorThirds, kDiatonic, kChordIndividual, kChord, kGuitar, kSeptatonic, kDrum, kAllPads }; enum ArrangementMode { kFull, kFive, kSix }; //IDrawableModule void DrawModule() override; void DrawModuleUnclipped() override; void GetModuleDimensions(float& width, float& height) override { width = 120; height = 74; } void PlayKeyboardNote(double time, int pitch, int velocity); void UpdateLights(bool force = false); GridColor GetGridSquareColor(int x, int y); int GridToPitch(int x, int y); void HandleChordButton(int pitch, bool bOn); bool IsChordButtonPressed(int pitch); void PressedNoteFor(int x, int y, int velocity); void ReleaseNoteFor(int x, int y); int GridToPitchChordSection(int x, int y); int GetHeldVelocity(int pitch) { if (pitch >= 0 && pitch < 128) return mCurrentNotes[pitch]; else return 0; } int mRootNote{ 4 }; // 4 = E int mCurrentNotes[128]{}; bool mTestKeyHeld{ false }; int mOctave{ 3 }; IntSlider* mOctaveSlider{ nullptr }; bool mLatch{ false }; Checkbox* mLatchCheckbox{ nullptr }; LaunchpadLayout mLayout{ LaunchpadLayout::kChromatic }; DropdownList* mLayoutDropdown{ nullptr }; int mCurrentChord{ 0 }; std::vector<std::vector<int> > mChords; LaunchpadNoteDisplayer* mDisplayer{ nullptr }; ArrangementMode mArrangementMode{ ArrangementMode::kFull }; DropdownList* mArrangementModeDropdown{ nullptr }; std::list<int> mHeldChordTones; Chorder* mChorder{ nullptr }; bool mLatchChords{ false }; Checkbox* mLatchChordsCheckbox{ nullptr }; bool mWasChorderEnabled{ false }; bool mPreserveChordRoot{ true }; Checkbox* mPreserveChordRootCheckbox{ nullptr }; GridControlTarget* mGridControlTarget{ nullptr }; }; ```
/content/code_sandbox/Source/LaunchpadKeyboard.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,232
```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 **/ /* ============================================================================== ChordHold.h Created: 3 Mar 2021 9:56:09pm Author: Ryan Challinor ============================================================================== */ #pragma once #include <iostream> #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "ClickButton.h" #include "IPulseReceiver.h" class ChordHolder : public NoteEffectBase, public IDrawableModule, public IButtonListener, public IPulseReceiver { public: ChordHolder(); static IDrawableModule* Create() { return new ChordHolder(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return true; } 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; //IPulseReceiver void OnPulse(double time, float velocity, int flags) override; void CheckboxUpdated(Checkbox* checkbox, double time) override; void ButtonClicked(ClickButton* button, 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 = 131; height = 21; } void Stop(double time); std::array<bool, 128> mNoteInputHeld{ false }; std::array<bool, 128> mNotePlaying{ false }; ClickButton* mStopButton{ nullptr }; bool mOnlyPlayWhenPulsed{ false }; Checkbox* mOnlyPlayWhenPulsedCheckbox{ nullptr }; }; ```
/content/code_sandbox/Source/ChordHolder.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
531
```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 **/ // // PitchShiftEffect.cpp // Bespoke // // Created by Ryan Challinor on 3/21/15. // // #include "PitchShiftEffect.h" #include "OpenFrameworksPort.h" #include "SynthGlobals.h" #include "Profiler.h" PitchShiftEffect::PitchShiftEffect() { for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i) mPitchShifter[i] = new PitchShifter(1024); } PitchShiftEffect::~PitchShiftEffect() { for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i) delete mPitchShifter[i]; } void PitchShiftEffect::CreateUIControls() { IDrawableModule::CreateUIControls(); mRatioSlider = new FloatSlider(this, "ratio", 5, 4, 85, 15, &mRatio, .5f, 2.0f); mRatioSelector = new RadioButton(this, "ratioselector", 5, 20, &mRatioSelection, kRadioHorizontal); mRatioSelector->AddLabel(".5", 5); mRatioSelector->AddLabel("1", 10); mRatioSelector->AddLabel("1.5", 15); mRatioSelector->AddLabel("2", 20); } void PitchShiftEffect::ProcessAudio(double time, ChannelBuffer* buffer) { PROFILER(PitchShiftEffect); if (!mEnabled) return; float bufferSize = buffer->BufferSize(); ComputeSliders(0); for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) { mPitchShifter[ch]->SetRatio(mRatio); mPitchShifter[ch]->Process(buffer->GetChannel(ch), bufferSize); } } void PitchShiftEffect::DrawModule() { if (!mEnabled) return; mRatioSlider->Draw(); mRatioSelector->Draw(); } void PitchShiftEffect::GetModuleDimensions(float& width, float& height) { if (mEnabled) { width = 105; height = 39; } else { width = 105; height = 0; } } float PitchShiftEffect::GetEffectAmount() { if (!mEnabled) return 0; return ofClamp(fabsf((mRatio - 1) * 10), 0, 1); } void PitchShiftEffect::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void PitchShiftEffect::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mRatioSlider) mRatioSelection = -1; } void PitchShiftEffect::RadioButtonUpdated(RadioButton* radio, int oldVal, double time) { if (radio == mRatioSelector) mRatio = mRatioSelection / 10.0f; } ```
/content/code_sandbox/Source/PitchShiftEffect.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
726
```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 **/ // // Checkbox.cpp // modularSynth // // Created by Ryan Challinor on 12/4/12. // // #include "Checkbox.h" #include "IDrawableModule.h" #include "SynthGlobals.h" #include "FileStream.h" #include "PatchCable.h" Checkbox::Checkbox(IDrawableModule* owner, const char* label, int x, int y, bool* var) : mVar(var) , mOwner(owner) { assert(owner); SetLabel(label); SetPosition(x, y); owner->AddUIControl(this); SetParent(dynamic_cast<IClickable*>(owner)); CalcSliderVal(); } Checkbox::Checkbox(IDrawableModule* owner, const char* label, IUIControl* anchor, AnchorDirection anchorDirection, bool* var) : Checkbox(owner, label, -1, -1, var) { PositionTo(anchor, anchorDirection); } Checkbox::~Checkbox() { } void Checkbox::SetLabel(const char* label) { SetName(label); UpdateWidth(); } void Checkbox::SetDisplayText(bool display) { mDisplayText = display; UpdateWidth(); } void Checkbox::UpdateWidth() { if (mDisplayText) mWidth = 15 + GetStringWidth(Name()); else mWidth = mHeight - 3; } void Checkbox::UseCircleLook(ofColor color) { mUseCircleLook = true; mCustomColor = color; } void Checkbox::Poll() { if (*mVar != mLastSetValue) CalcSliderVal(); } void Checkbox::Render() { mLastDisplayedValue = *mVar; ofPushStyle(); DrawBeacon(mX + 6, mY + 8); ofColor color; if (IsPreset()) color.set(0, 255, 0); else if (mUseCircleLook) color = mCustomColor; else color.set(255, 255, 255); color.a = gModuleDrawAlpha; ofColor darkColor = color; darkColor.setBrightness(30); ofFill(); if (mUseCircleLook) { ofSetColor(darkColor); ofCircle(mX + mHeight / 2 - 1, mY + mHeight / 2 + 1, mHeight / 3); } else { ofSetColor(color.r, color.g, color.b, color.a * .2f); ofRect(mX, mY + 1, mHeight - 3, mHeight - 3); } ofSetColor(color); if (mDisplayText) DrawTextNormal(Name(), mX + 13, mY + 12); if (*mVar) { if (mUseCircleLook) ofCircle(mX + mHeight / 2 - 1, mY + mHeight / 2 + 1, mHeight / 5); else ofRect(mX + 2, mY + 3, mHeight - 7, mHeight - 7, 2); } ofPopStyle(); DrawHover(mX, mY, mWidth, mHeight); } void Checkbox::OnClicked(float x, float y, bool right) { if (right) return; *mVar = !(*mVar); CalcSliderVal(); mOwner->CheckboxUpdated(this, NextBufferTime(false)); } void Checkbox::CalcSliderVal() { mLastSetValue = *mVar; mSliderVal = *mVar ? 1 : 0; } bool Checkbox::MouseMoved(float x, float y) { CheckHover(x, y); return false; } void Checkbox::SetFromMidiCC(float slider, double time, bool setViaModulator) { slider = ofClamp(slider, 0, 1); mSliderVal = slider; bool on = GetValueForMidiCC(slider) > 0.5f; if (*mVar != on) { *mVar = on; mLastSetValue = *mVar; mOwner->CheckboxUpdated(this, time); } } float Checkbox::GetValueForMidiCC(float slider) const { return slider > .5f ? 1 : 0; } void Checkbox::SetValue(float value, double time, bool forceUpdate /*= false*/) { bool on = value > 0.5f; if (*mVar != on || forceUpdate) { *mVar = on; CalcSliderVal(); mOwner->CheckboxUpdated(this, time); } } float Checkbox::GetMidiValue() const { return mSliderVal; } float Checkbox::GetValue() const { return *mVar; } std::string Checkbox::GetDisplayValue(float val) const { return val > 0 ? "on" : "off"; } void Checkbox::Increment(float amount) { *mVar = !*mVar; CalcSliderVal(); } bool Checkbox::CanBeTargetedBy(PatchCableSource* source) const { if (source->GetConnectionType() == kConnectionType_Pulse) return true; return IUIControl::CanBeTargetedBy(source); } bool Checkbox::CheckNeedsDraw() { if (IUIControl::CheckNeedsDraw()) return true; return *mVar != mLastDisplayedValue; } void Checkbox::OnPulse(double time, float velocity, int flags) { SetValue(*mVar ? 0 : 1, time, false); } namespace { const int kSaveStateRev = 0; } void Checkbox::SaveState(FileStreamOut& out) { out << kSaveStateRev; out << (float)*mVar; } void Checkbox::LoadState(FileStreamIn& in, bool shouldSetValue) { int rev; in >> rev; LoadStateValidate(rev <= kSaveStateRev); float var; in >> var; if (shouldSetValue) SetValueDirect(var, gTime); } ```
/content/code_sandbox/Source/Checkbox.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,400
```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 **/ /* ============================================================================== LooperGranulator.h Created: 13 Mar 2021 1:55:54pm Author: Ryan Challinor ============================================================================== */ #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 "DropdownList.h" #include "Granulator.h" class Looper; class LooperGranulator : public IDrawableModule, public IButtonListener, public IFloatSliderListener, public IDropdownListener { public: LooperGranulator(); virtual ~LooperGranulator(); static IDrawableModule* Create() { return new LooperGranulator(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void ProcessFrame(double time, float bufferOffset, float* output); void DrawOverlay(ofRectangle bufferRect, int loopLength); bool IsActive() { return mOn; } bool ShouldFreeze() { return mOn && mFreeze; } void OnCommit(); 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 LoadLayout(const ofxJSONElement& moduleInfo) override; void SaveLayout(ofxJSONElement& moduleInfo) override; void SetUpFromSaveData() override; //IPatchable void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override; bool IsEnabled() const override { return true; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override; float mWidth{ 200 }; float mHeight{ 20 }; PatchCableSource* mLooperCable{ nullptr }; Looper* mLooper{ nullptr }; bool mOn{ false }; Checkbox* mOnCheckbox{ nullptr }; Granulator mGranulator; FloatSlider* mGranOverlap{ nullptr }; FloatSlider* mGranSpeed{ nullptr }; FloatSlider* mGranLengthMs{ nullptr }; float mDummyPos{ 0 }; FloatSlider* mPosSlider{ nullptr }; bool mFreeze{ false }; Checkbox* mFreezeCheckbox{ nullptr }; FloatSlider* mGranPosRandomize{ nullptr }; FloatSlider* mGranSpeedRandomize{ nullptr }; FloatSlider* mGranSpacingRandomize{ nullptr }; Checkbox* mGranOctaveCheckbox{ nullptr }; FloatSlider* mGranWidthSlider{ nullptr }; }; ```
/content/code_sandbox/Source/LooperGranulator.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
735
```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 **/ // // IAudioSource.cpp // Bespoke // // Created by Ryan Challinor on 12/16/15. // // #include "IAudioSource.h" #include "IAudioReceiver.h" #include "PatchCableSource.h" IAudioReceiver* IAudioSource::GetTarget(int index) { assert(index < GetNumTargets()); return GetPatchCableSource(index)->GetAudioReceiver(); } void IAudioSource::SyncOutputBuffer(int numChannels) { for (int i = 0; i < GetNumTargets(); ++i) { if (GetTarget(i)) { ChannelBuffer* out = GetTarget(i)->GetBuffer(); out->SetNumActiveChannels(MAX(numChannels, out->NumActiveChannels())); } } GetVizBuffer()->SetNumChannels(numChannels); } ```
/content/code_sandbox/Source/IAudioSource.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
273
```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 **/ /* ============================================================================== CanvasScrollbar.cpp Created: 22 Mar 2021 12:19:47am Author: Ryan Challinor ============================================================================== */ #include "CanvasScrollbar.h" #include "Canvas.h" #include "ModularSynth.h" CanvasScrollbar::CanvasScrollbar(Canvas* canvas, std::string name, Style style) : mStyle(style) , mCanvas(canvas) { SetName(name.c_str()); SetParent(canvas->GetModuleParent()); } void CanvasScrollbar::Render() { ofRectangle canvasRect = mCanvas->GetRect(true); if (mStyle == Style::kHorizontal) { SetPosition(canvasRect.x, canvasRect.getMaxY()); SetDimensions(canvasRect.width, 10); } if (mStyle == Style::kVertical) { SetPosition(canvasRect.getMaxX(), canvasRect.y); SetDimensions(10, canvasRect.height); } if (mAutoHide && GetBarStart() == 0) { if (mStyle == Style::kHorizontal && GetBarEnd() == mWidth) return; if (mStyle == Style::kVertical && GetBarEnd() == mHeight) return; } ofPushMatrix(); ofTranslate(mX, mY); ofPushStyle(); ofSetLineWidth(.5f); float w, h; GetDimensions(w, h); ofFill(); ofRect(0, 0, mWidth, mHeight); ofSetColor(255, 255, 255); if (mStyle == Style::kHorizontal) ofRect(GetBarStart(), 0, GetBarEnd() - GetBarStart(), mHeight); if (mStyle == Style::kVertical) ofRect(0, GetBarStart(), mWidth, GetBarEnd() - GetBarStart()); ofPopStyle(); ofPopMatrix(); } float CanvasScrollbar::GetBarStart() const { if (mStyle == Style::kHorizontal) return mCanvas->mViewStart / mCanvas->GetLength() * mWidth; if (mStyle == Style::kVertical) return ofMap(mCanvas->GetRowOffset(), 0, mCanvas->GetNumRows(), 0, mHeight); return 0; } float CanvasScrollbar::GetBarEnd() const { if (mStyle == Style::kHorizontal) return mCanvas->mViewEnd / mCanvas->GetLength() * mWidth; if (mStyle == Style::kVertical) return ofMap(mCanvas->GetRowOffset() + mCanvas->GetNumVisibleRows(), 0, mCanvas->GetNumRows(), 0, mHeight); return 1; } void CanvasScrollbar::OnClicked(float x, float y, bool right) { mClickMousePos.set(TheSynth->GetRawMouseX(), TheSynth->GetRawMouseY()); mDragOffset.set(0, 0); mClick = true; if (mStyle == Style::kHorizontal) mScrollBarOffset = x - GetBarStart(); if (mStyle == Style::kVertical) mScrollBarOffset = y - GetBarStart(); } void CanvasScrollbar::MouseReleased() { mClick = false; } bool CanvasScrollbar::MouseMoved(float x, float y) { CheckHover(x, y); if (mClick) { mDragOffset = (ofVec2f(TheSynth->GetRawMouseX(), TheSynth->GetRawMouseY()) - mClickMousePos) / gDrawScale; if (mStyle == Style::kHorizontal) { float viewLength = mCanvas->mViewEnd - mCanvas->mViewStart; mCanvas->mViewStart = ofClamp((x - mScrollBarOffset) / mWidth * mCanvas->GetLength(), 0, mCanvas->GetLength() - viewLength); mCanvas->mViewEnd = mCanvas->mViewStart + viewLength; } if (mStyle == Style::kVertical) mCanvas->SetRowOffset(ofClamp(int(ofMap(y - mScrollBarOffset, 0, mHeight, 0, mCanvas->GetNumRows()) + .5f), 0, mCanvas->GetNumRows() - mCanvas->GetNumVisibleRows())); } return false; } bool CanvasScrollbar::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) { return false; } void CanvasScrollbar::SaveState(FileStreamOut& out) { } void CanvasScrollbar::LoadState(FileStreamIn& in, bool shouldSetValue) { } ```
/content/code_sandbox/Source/CanvasScrollbar.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,103
```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 **/ // // Transport.h // modularSynth // // Created by Ryan Challinor on 12/2/12. // // #pragma once #include <iostream> #include "IDrawableModule.h" #include "Slider.h" #include "ClickButton.h" #include "DropdownList.h" #include "Checkbox.h" #include "IAudioPoller.h" class ITimeListener { public: virtual ~ITimeListener() {} virtual void OnTimeEvent(double time) = 0; static constexpr int kDefaultTransportPriority = 100; static constexpr int kTransportPriorityEarly = 0; static constexpr int kTransportPriorityLate = 200; static constexpr int kTransportPriorityVeryEarly = -1000; int mTransportPriority{ kDefaultTransportPriority }; }; enum NoteInterval { kInterval_1n, kInterval_2n, kInterval_2nt, kInterval_4n, kInterval_4nt, kInterval_8n, kInterval_8nt, kInterval_16n, kInterval_16nt, kInterval_32n, kInterval_32nt, kInterval_64n, kInterval_4nd, kInterval_8nd, kInterval_16nd, kInterval_2, kInterval_3, kInterval_4, kInterval_8, kInterval_16, kInterval_32, kInterval_64, kInterval_Free, kInterval_None, kInterval_CustomDivisor }; struct OffsetInfo { OffsetInfo(double offset, bool offsetIsInMs) : mOffset(offset) , mOffsetIsInMs(offsetIsInMs) {} double mOffset{ 0 }; bool mOffsetIsInMs{ false }; }; struct TransportListenerInfo { TransportListenerInfo(ITimeListener* listener, NoteInterval interval, OffsetInfo offsetInfo, bool useEventLookahead) : mListener(listener) , mInterval(interval) , mOffsetInfo(offsetInfo) , mUseEventLookahead(useEventLookahead) {} ITimeListener* mListener{ nullptr }; NoteInterval mInterval{ NoteInterval::kInterval_None }; OffsetInfo mOffsetInfo; bool mUseEventLookahead{ false }; int mCustomDivisor{ 8 }; }; class Transport : public IDrawableModule, public IButtonListener, public IFloatSliderListener, public IDropdownListener { public: Transport(); void CreateUIControls() override; void Poll() override; float GetTempo() { return mTempo; } void SetTempo(float tempo) { mTempo = tempo; } void SetTimeSignature(int top, int bottom) { mTimeSigTop = top; mTimeSigBottom = bottom; } int GetTimeSigTop() { return mTimeSigTop; } int GetTimeSigBottom() { return mTimeSigBottom; } void SetSwing(float swing) { mSwing = swing; } float GetSwing() { return mSwing; } double MsPerBar() const { return 60.0 / mTempo * 1000 * mTimeSigTop * 4.0 / mTimeSigBottom; } void Advance(double ms); TransportListenerInfo* AddListener(ITimeListener* listener, NoteInterval interval, OffsetInfo offsetInfo, bool useEventLookahead); void RemoveListener(ITimeListener* listener); TransportListenerInfo* GetListenerInfo(ITimeListener* listener); void AddAudioPoller(IAudioPoller* poller); void RemoveAudioPoller(IAudioPoller* poller); void ClearListenersAndPollers(); double GetDuration(NoteInterval interval); int GetQuantized(double time, const TransportListenerInfo* listenerInfo, double* remainderMs = nullptr); double GetMeasurePos(double time) const { return fmod(GetMeasureTime(time), 1); } void SetMeasureTime(double measureTime) { mMeasureTime = measureTime; } int GetMeasure(double time) const { return (int)floor(GetMeasureTime(time)); } double GetMeasureTime(double time) const; void SetMeasure(int count) { mMeasureTime = mMeasureTime - (int)mMeasureTime + count; } void SetDownbeat() { mMeasureTime = mMeasureTime - (int)mMeasureTime - .001; } static int CountInStandardMeasure(NoteInterval interval); void Reset(); void OnDrumEvent(NoteInterval drumEvent); void SetLoop(int measureStart, int measureEnd) { assert(measureStart < measureEnd); mLoopStartMeasure = measureStart; mLoopEndMeasure = measureEnd; mQueuedMeasure = measureStart; mJumpFromMeasure = measureEnd; } void ClearLoop() { mLoopStartMeasure = -1; mLoopEndMeasure = -1; mQueuedMeasure = -1; } void SetQueuedMeasure(double time, int measure); bool IsPastQueuedMeasureJump(double time) const; double GetMeasureFraction(NoteInterval interval); int GetStepsPerMeasure(ITimeListener* listener); int GetSyncedStep(double time, ITimeListener* listener, const TransportListenerInfo* listenerInfo, int length = -1); bool CheckNeedsDraw() override { return true; } double GetEventLookaheadMs() { return sDoEventLookahead ? sEventEarlyMs : 0; } //IDrawableModule void Init() override; void KeyPressed(int key, bool isRepeat) override; bool IsSingleton() const override { return true; } void ButtonClicked(ClickButton* button, double time) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void CheckboxUpdated(Checkbox* checkbox, double time) 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; } static bool sDoEventLookahead; static double sEventEarlyMs; bool IsEnabled() const override { return true; } static bool IsTripletInterval(NoteInterval interval); private: void UpdateListeners(double jumpMs); double Swing(double measurePos); double SwingBeat(double pos); void Nudge(double amount); void SetRandomTempo(); double GetMeasureTimeInternal(double time) const; //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = 140; height = 100; } float mTempo{ 120 }; int mTimeSigTop{ 4 }; int mTimeSigBottom{ 4 }; double mMeasureTime{ 0 }; int mSwingInterval{ 8 }; float mSwing{ .5 }; FloatSlider* mSwingSlider{ nullptr }; ClickButton* mResetButton{ nullptr }; ClickButton* mPlayPauseButton{ nullptr }; DropdownList* mTimeSigTopDropdown{ nullptr }; DropdownList* mTimeSigBottomDropdown{ nullptr }; DropdownList* mSwingIntervalDropdown{ nullptr }; bool mSetTempoBool{ false }; Checkbox* mSetTempoCheckbox{ nullptr }; double mStartRecordTime{ -1 }; ClickButton* mNudgeBackButton{ nullptr }; ClickButton* mNudgeForwardButton{ nullptr }; ClickButton* mIncreaseTempoButton{ nullptr }; ClickButton* mDecreaseTempoButton{ nullptr }; FloatSlider* mTempoSlider{ nullptr }; int mLoopStartMeasure{ -1 }; int mLoopEndMeasure{ -1 }; int mQueuedMeasure{ -1 }; int mJumpFromMeasure{ -1 }; bool mWantSetRandomTempo{ false }; float mNudgeFactor{ 0 }; std::list<TransportListenerInfo> mListeners; std::list<IAudioPoller*> mAudioPollers; }; extern Transport* TheTransport; ```
/content/code_sandbox/Source/Transport.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,903
```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.cpp Created: 29 Nov 2017 8:56:32pm Author: Ryan Challinor ============================================================================== */ #include "ModulatorMult.h" #include "Profiler.h" #include "ModularSynth.h" #include "PatchCableSource.h" ModulatorMult::ModulatorMult() { } void ModulatorMult::CreateUIControls() { IDrawableModule::CreateUIControls(); mValue1Slider = new FloatSlider(this, "value 1", 3, 2, 100, 15, &mValue1, 0, 1); mValue2Slider = new FloatSlider(this, "value 2", mValue1Slider, kAnchor_Below, 100, 15, &mValue2, 0, 10); mTargetCable = new PatchCableSource(this, kConnectionType_Modulator); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); } ModulatorMult::~ModulatorMult() { } void ModulatorMult::DrawModule() { if (Minimized() || IsVisible() == false) return; mValue1Slider->Draw(); mValue2Slider->Draw(); } void ModulatorMult::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { OnModulatorRepatch(); if (GetSliderTarget() && fromUserClick) { mValue1 = GetSliderTarget()->GetValue(); mValue2 = 1; mValue1Slider->SetExtents(GetSliderTarget()->GetMin(), GetSliderTarget()->GetMax()); mValue1Slider->SetMode(GetSliderTarget()->GetMode()); } } float ModulatorMult::Value(int samplesIn) { ComputeSliders(samplesIn); if (GetSliderTarget()) return ofClamp(mValue1 * mValue2, GetSliderTarget()->GetMin(), GetSliderTarget()->GetMax()); else return mValue1 * mValue2; } void ModulatorMult::SaveLayout(ofxJSONElement& moduleInfo) { } void ModulatorMult::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void ModulatorMult::SetUpFromSaveData() { } ```
/content/code_sandbox/Source/ModulatorMult.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
593
```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 **/ // // SustainPedal.cpp // Bespoke // // Created by Ryan Challinor on 5/7/14. // // #include "SustainPedal.h" #include "OpenFrameworksPort.h" #include "ModularSynth.h" SustainPedal::SustainPedal() { } void SustainPedal::CreateUIControls() { IDrawableModule::CreateUIControls(); mSustainCheckbox = new Checkbox(this, "sustain", 3, 3, &mSustain); } void SustainPedal::DrawModule() { if (Minimized() || IsVisible() == false) return; mSustainCheckbox->Draw(); } void SustainPedal::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mSustainCheckbox) { if (!mSustain) { for (int i = 0; i < 128; ++i) { if (mIsNoteBeingSustained[i]) { PlayNoteOutput(time, i, 0, -1); mIsNoteBeingSustained[i] = false; } } } } } void SustainPedal::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mSustain) { if (velocity > 0) { PlayNoteOutput(time, pitch, 0, voiceIdx, modulation); PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); mIsNoteBeingSustained[pitch] = false; //not being sustained by this module it if it's held down } else { mIsNoteBeingSustained[pitch] = true; } } else { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } } void SustainPedal::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void SustainPedal::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/SustainPedal.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
569
```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 **/ // // AudioMeter.h // Bespoke // // Created by Ryan Challinor on 6/18/15. // // #pragma once #include "IAudioProcessor.h" #include "IDrawableModule.h" #include "Slider.h" #include "PeakTracker.h" class AudioMeter : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener { public: AudioMeter(); virtual ~AudioMeter(); static IDrawableModule* Create() { return new AudioMeter(); } 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 {} 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 = 120; h = 22; } float mLevel{ 0 }; float mMaxLevel{ 1 }; FloatSlider* mLevelSlider{ nullptr }; PeakTracker mPeakTracker; float* mAnalysisBuffer{ nullptr }; }; ```
/content/code_sandbox/Source/AudioMeter.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
432
```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 **/ /* ============================================================================== PulseChance.h Created: 4 Feb 2020 12:17:59pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "IPulseReceiver.h" #include "Slider.h" #include "ClickButton.h" #include "TextEntry.h" class PulseChance : public IDrawableModule, public IPulseSource, public IPulseReceiver, public IFloatSliderListener, public ITextEntryListener, public IButtonListener { public: PulseChance(); virtual ~PulseChance(); static IDrawableModule* Create() { return new PulseChance(); } 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 mEnabled; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; void Reseed(); float mChance{ 1 }; FloatSlider* mChanceSlider{ nullptr }; float mLastRejectTime{ 0 }; float mLastAcceptTime{ 0 }; bool mDeterministic{ false }; Checkbox* mDeterministicCheckbox{ nullptr }; int mSeed{ 0 }; int mRandomIndex{ 0 }; TextEntry* mSeedEntry{ nullptr }; ClickButton* mReseedButton{ nullptr }; ClickButton* mPrevSeedButton{ nullptr }; ClickButton* mNextSeedButton{ nullptr }; }; ```
/content/code_sandbox/Source/PulseChance.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
554
```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.cpp Created: 15 Oct 2017 10:24:40am Author: Ryan Challinor ============================================================================== */ #include "IAudioProcessor.h" void IAudioProcessor::SyncBuffers(int overrideNumOutputChannels) { SyncInputBuffer(); int numOutputChannels = GetBuffer()->NumActiveChannels(); if (overrideNumOutputChannels != -1) numOutputChannels = overrideNumOutputChannels; SyncOutputBuffer(numOutputChannels); } ```
/content/code_sandbox/Source/IAudioProcessor.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
204
```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 **/ /* ============================================================================== UserPrefs.cpp Created: 24 Oct 2021 10:29:53pm Author: Ryan Challinor ============================================================================== */ #include "UserPrefs.h" #include "ModularSynth.h" #include "SynthGlobals.h" #include "DropdownList.h" #include "TextEntry.h" #include "Slider.h" #include "Checkbox.h" UserPrefsHolder UserPrefs; void RegisterUserPref(UserPref* pref) { UserPrefs.mUserPrefs.push_back(pref); } // Helper function to convert string to appropriate type and set the JSON value void setValueFromString(Json::Value& element, const std::string& value) { switch (element.type()) { case Json::nullValue: ofLog() << "Cannot update null value."; break; case Json::intValue: element = std::stoi(value); break; case Json::uintValue: element = static_cast<unsigned int>(std::stoul(value)); break; case Json::realValue: element = std::stod(value); break; case Json::stringValue: element = value; break; case Json::booleanValue: if (value == "true" || value == "1") { element = true; } else if (value == "false" || value == "0") { element = false; } else { ofLog() << "Invalid boolean value."; } break; case Json::arrayValue: case Json::objectValue: ofLog() << "Cannot update array or object value with a single command-line parameter."; break; default: ofLog() << "Unsupported JSON value type."; break; } } void UserPrefsHolder::Init() { mUserPrefsFile.open(TheSynth->GetUserPrefsPath()); // Look for overrides in command line options for (int i = 0; i < juce::JUCEApplication::getCommandLineParameterArray().size(); ++i) { juce::String argument = juce::JUCEApplication::getCommandLineParameterArray()[i]; if (argument == "-o" || argument == "--option") { juce::String argJsonOption = juce::JUCEApplication::getCommandLineParameterArray()[i + 1]; auto value = juce::JUCEApplication::getCommandLineParameterArray()[i + 2].toStdString(); auto& element = mUserPrefsFile[argJsonOption.toStdString()]; try { setValueFromString(element, value); } catch (std::invalid_argument) { ofLog() << "Failed to convert argument " << value << " to the desired type"; } } } for (auto* pref : mUserPrefs) pref->Init(); } std::string UserPrefsHolder::ToStringLeadingZeroes(int number) { char buffer[9]; snprintf(buffer, sizeof(buffer), "%08d", number); return buffer; } //////////////////////////////////////////////////////////////////////////////// void UserPrefString::Init() { try { if (!UserPrefs.mUserPrefsFile[mName].isNull()) mValue = UserPrefs.mUserPrefsFile[mName].asString(); } catch (Json::LogicError& e) { TheSynth->LogEvent("json error loading userpref for " + mName + ": " + e.what(), kLogEventType_Error); UserPrefs.mUserPrefsFile[mName] = mDefault; } } void UserPrefString::SetUpControl(IDrawableModule* owner) { mTextEntry = new TextEntry(dynamic_cast<ITextEntryListener*>(owner), mName.c_str(), -1, -1, mCharWidth, &mValue); } IUIControl* UserPrefString::GetControl() { return mTextEntry; } void UserPrefString::Save(int index, ofxJSONElement& prefsJson) //this numbering is a silly markup hack to get the json file to save ordered { prefsJson.removeMember(mName); prefsJson["**" + UserPrefsHolder::ToStringLeadingZeroes(index) + "**" + mName] = mValue; } bool UserPrefString::DiffersFromSavedValue() const { if (UserPrefs.mUserPrefsFile[mName].isNull()) return mValue != mDefault; return mValue != UserPrefs.mUserPrefsFile[mName].asString(); } //////////////////////////////////////////////////////////////////////////////// void UserPrefDropdownInt::Init() { try { if (!UserPrefs.mUserPrefsFile[mName].isNull()) mValue = UserPrefs.mUserPrefsFile[mName].asInt(); } catch (Json::LogicError& e) { TheSynth->LogEvent("json error loading userpref for " + mName + ": " + e.what(), kLogEventType_Error); UserPrefs.mUserPrefsFile[mName] = mDefault; } } void UserPrefDropdownInt::SetUpControl(IDrawableModule* owner) { mDropdown = new DropdownList(dynamic_cast<IDropdownListener*>(owner), mName.c_str(), -1, -1, &mIndex, mWidth); } IUIControl* UserPrefDropdownInt::GetControl() { return mDropdown; } void UserPrefDropdownInt::Save(int index, ofxJSONElement& prefsJson) //this numbering is a silly markup hack to get the json file to save ordered { prefsJson.removeMember(mName); prefsJson["**" + UserPrefsHolder::ToStringLeadingZeroes(index) + "**" + mName] = ofToInt(mDropdown->GetLabel(mIndex)); } bool UserPrefDropdownInt::DiffersFromSavedValue() const { if (UserPrefs.mUserPrefsFile[mName].isNull()) return ofToInt(mDropdown->GetLabel(mIndex)) != mDefault; return ofToInt(mDropdown->GetLabel(mIndex)) != UserPrefs.mUserPrefsFile[mName].asInt(); } //////////////////////////////////////////////////////////////////////////////// void UserPrefDropdownString::Init() { if (!UserPrefs.mUserPrefsFile[mName].isNull()) mValue = UserPrefs.mUserPrefsFile[mName].asString(); try { if (!UserPrefs.mUserPrefsFile[mName].isNull()) mValue = UserPrefs.mUserPrefsFile[mName].asString(); } catch (Json::LogicError& e) { TheSynth->LogEvent("json error loading userpref for " + mName + ": " + e.what(), kLogEventType_Error); UserPrefs.mUserPrefsFile[mName] = mDefault; } } void UserPrefDropdownString::SetUpControl(IDrawableModule* owner) { mDropdown = new DropdownList(dynamic_cast<IDropdownListener*>(owner), mName.c_str(), -1, -1, &mIndex, mWidth); } IUIControl* UserPrefDropdownString::GetControl() { return mDropdown; } void UserPrefDropdownString::Save(int index, ofxJSONElement& prefsJson) //this numbering is a silly markup hack to get the json file to save ordered { prefsJson.removeMember(mName); prefsJson["**" + UserPrefsHolder::ToStringLeadingZeroes(index) + "**" + mName] = mDropdown->GetLabel(mIndex); } bool UserPrefDropdownString::DiffersFromSavedValue() const { if (UserPrefs.mUserPrefsFile[mName].isNull()) return mDropdown->GetLabel(mIndex) != mDefault; return mDropdown->GetLabel(mIndex) != UserPrefs.mUserPrefsFile[mName].asString(); } //////////////////////////////////////////////////////////////////////////////// void UserPrefTextEntryInt::Init() { try { if (!UserPrefs.mUserPrefsFile[mName].isNull()) mValue = UserPrefs.mUserPrefsFile[mName].asInt(); } catch (Json::LogicError& e) { TheSynth->LogEvent("json error loading userpref for " + mName + ": " + e.what(), kLogEventType_Error); UserPrefs.mUserPrefsFile[mName] = mDefault; } } void UserPrefTextEntryInt::SetUpControl(IDrawableModule* owner) { mTextEntry = new TextEntry(dynamic_cast<ITextEntryListener*>(owner), mName.c_str(), -1, -1, mDigits, &mValue, mMin, mMax); } IUIControl* UserPrefTextEntryInt::GetControl() { return mTextEntry; } void UserPrefTextEntryInt::Save(int index, ofxJSONElement& prefsJson) //this numbering is a silly markup hack to get the json file to save ordered { prefsJson.removeMember(mName); prefsJson["**" + UserPrefsHolder::ToStringLeadingZeroes(index) + "**" + mName] = mValue; } bool UserPrefTextEntryInt::DiffersFromSavedValue() const { if (UserPrefs.mUserPrefsFile[mName].isNull()) return mValue != mDefault; return mValue != UserPrefs.mUserPrefsFile[mName].asInt(); } //////////////////////////////////////////////////////////////////////////////// void UserPrefTextEntryFloat::Init() { try { if (!UserPrefs.mUserPrefsFile[mName].isNull()) mValue = UserPrefs.mUserPrefsFile[mName].asFloat(); } catch (Json::LogicError& e) { TheSynth->LogEvent("json error loading userpref for " + mName + ": " + e.what(), kLogEventType_Error); UserPrefs.mUserPrefsFile[mName] = mDefault; } } void UserPrefTextEntryFloat::SetUpControl(IDrawableModule* owner) { mTextEntry = new TextEntry(dynamic_cast<ITextEntryListener*>(owner), mName.c_str(), -1, -1, mDigits, &mValue, mMin, mMax); } IUIControl* UserPrefTextEntryFloat::GetControl() { return mTextEntry; } void UserPrefTextEntryFloat::Save(int index, ofxJSONElement& prefsJson) //this numbering is a silly markup hack to get the json file to save ordered { prefsJson.removeMember(mName); prefsJson["**" + UserPrefsHolder::ToStringLeadingZeroes(index) + "**" + mName] = mValue; } bool UserPrefTextEntryFloat::DiffersFromSavedValue() const { if (UserPrefs.mUserPrefsFile[mName].isNull()) return mValue != mDefault; return mValue != UserPrefs.mUserPrefsFile[mName].asFloat(); } //////////////////////////////////////////////////////////////////////////////// void UserPrefBool::Init() { try { if (!UserPrefs.mUserPrefsFile[mName].isNull()) mValue = UserPrefs.mUserPrefsFile[mName].asBool(); } catch (Json::LogicError& e) { TheSynth->LogEvent("json error loading userpref for " + mName + ": " + e.what(), kLogEventType_Error); UserPrefs.mUserPrefsFile[mName] = mDefault; } } void UserPrefBool::SetUpControl(IDrawableModule* owner) { mCheckbox = new Checkbox(owner, mName.c_str(), -1, -1, &mValue); } IUIControl* UserPrefBool::GetControl() { return mCheckbox; } void UserPrefBool::Save(int index, ofxJSONElement& prefsJson) //this numbering is a silly markup hack to get the json file to save ordered { prefsJson.removeMember(mName); prefsJson["**" + UserPrefsHolder::ToStringLeadingZeroes(index) + "**" + mName] = mValue; } bool UserPrefBool::DiffersFromSavedValue() const { if (UserPrefs.mUserPrefsFile[mName].isNull()) return mValue != mDefault; return mValue != UserPrefs.mUserPrefsFile[mName].asBool(); } //////////////////////////////////////////////////////////////////////////////// void UserPrefFloat::Init() { try { if (!UserPrefs.mUserPrefsFile[mName].isNull()) mValue = UserPrefs.mUserPrefsFile[mName].asFloat(); } catch (Json::LogicError& e) { TheSynth->LogEvent("json error loading userpref for " + mName + ": " + e.what(), kLogEventType_Error); UserPrefs.mUserPrefsFile[mName] = mDefault; } } void UserPrefFloat::SetUpControl(IDrawableModule* owner) { mSlider = new FloatSlider(dynamic_cast<IFloatSliderListener*>(owner), mName.c_str(), -1, -1, 200, 15, &mValue, mMin, mMax); mSlider->SetShowName(false); } IUIControl* UserPrefFloat::GetControl() { return mSlider; } void UserPrefFloat::Save(int index, ofxJSONElement& prefsJson) //this numbering is a silly markup hack to get the json file to save ordered { prefsJson.removeMember(mName); prefsJson["**" + UserPrefsHolder::ToStringLeadingZeroes(index) + "**" + mName] = mValue; } bool UserPrefFloat::DiffersFromSavedValue() const { if (UserPrefs.mUserPrefsFile[mName].isNull()) return mValue != mDefault; return mValue != UserPrefs.mUserPrefsFile[mName].asFloat(); } ```
/content/code_sandbox/Source/UserPrefs.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,935
```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 **/ /* ============================================================================== UserPrefsEditor.h Created: 12 Feb 2021 10:29:53pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "Slider.h" #include "TextEntry.h" #include "DropdownList.h" #include "ClickButton.h" #include "RadioButton.h" #include "UserPrefs.h" class UserPrefsEditor : public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public ITextEntryListener, public IDropdownListener, public IButtonListener, public IRadioButtonListener { public: UserPrefsEditor(); ~UserPrefsEditor(); static IDrawableModule* Create() { return new UserPrefsEditor(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; bool AlwaysOnTop() override { return true; } bool CanMinimize() override { return false; } bool IsSingleton() const override { return true; } void Show(); void CreatePrefsFileIfNonexistent(); void CheckboxUpdated(Checkbox* checkbox, double time) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; void TextEntryComplete(TextEntry* entry) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void ButtonClicked(ClickButton* button, double time) override; void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override; bool IsSaveable() override { return false; } std::vector<IUIControl*> ControlsToNotSetDuringLoadState() const override; std::vector<IUIControl*> ControlsToIgnoreInSaveState() const override; bool IsEnabled() const override { return true; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } void UpdateDropdowns(std::vector<DropdownList*> toUpdate); void DrawRightLabel(IUIControl* control, std::string text, ofColor color, float offsetX = 12); void CleanUpSave(std::string& json); bool PrefRequiresRestart(UserPref* pref) const; void Save(); UserPrefCategory mCategory{ UserPrefCategory::General }; RadioButton* mCategorySelector{ nullptr }; ClickButton* mSaveButton{ nullptr }; ClickButton* mCancelButton{ nullptr }; float mWidth{ 1150 }; float mHeight{ 50 }; }; ```
/content/code_sandbox/Source/UserPrefsEditor.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
701
```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 **/ // // UIGrid.h // modularSynth // // Created by Ryan Challinor on 1/1/13. // // #pragma once #include "IUIControl.h" #include "SynthGlobals.h" #define MAX_GRID_COLS 1024 #define MAX_GRID_ROWS 128 class UIGrid; class UIGridListener { public: virtual ~UIGridListener() {} virtual void GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) = 0; }; struct GridCell { GridCell(int col, int row) : mCol(col) , mRow(row) {} int mCol; int mRow; }; class UIGrid : public IUIControl { public: UIGrid(std::string name, int x, int y, int w, int h, int cols, int rows, IClickable* parent); void Init(int x, int y, int w, int h, int cols, int rows, IClickable* parent); void SetGrid(int cols, int rows); int GetRows() { return mRows; } int GetCols() { return mCols; } void Render() override; 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; float& GetVal(int col, int row); void SetVal(int col, int row, float val, bool notifyListener = true); void SetHighlightCol(double time, int col); int GetHighlightCol(double time) const; void SetMajorColSize(int size) { mMajorCol = size; } int GetMajorColSize() const { return mMajorCol; } void SetSingleColumnMode(bool set) { mSingleColumn = set; } void Clear(); void SetFlip(bool flip) { mFlip = flip; } void SetStrength(float strength) { mStrength = strength; } int CurrentHover() { return mCurrentHover; } void SetListener(UIGridListener* listener) { mListener = listener; } void SetDrawOffset(int row, float amount) { mDrawOffset[row] = amount; } void SetDimensions(float width, float height) { mWidth = width; mHeight = height; } float GetWidth() const { return mWidth; } float GetHeight() const { return mHeight; } void SetRestrictDragToRow(bool set) { mRestrictDragToRow = set; } void SetRequireShiftForMultislider(bool set) { mRequireShiftForMultislider = set; } void SetShouldDrawValue(bool draw) { mShouldDrawValue = draw; } void SetMomentary(bool momentary) { mMomentary = momentary; } const std::array<float, MAX_GRID_COLS * MAX_GRID_ROWS>& GetData() const { return mData; } void SetData(std::array<float, MAX_GRID_COLS * MAX_GRID_ROWS>& data) { mData = data; } void SetClickValueSubdivisions(int subdivisions) { mClickSubdivisions = subdivisions; } float GetSubdividedValue(float position) const; bool GetNoHover() const override { return true; } bool CanBeTargetedBy(PatchCableSource* source) const override; enum GridMode { kNormal, kMultislider, kHorislider, kMultisliderBipolar }; void SetGridMode(GridMode mode) { mGridMode = mode; } GridCell GetGridCellAt(float x, float y, float* clickHeight = nullptr, float* clickWidth = nullptr); ofVec2f GetCellPosition(int col, int row); //IUIControl void SetFromMidiCC(float slider, double time, bool setViaModulator) override {} void SetValue(float value, double time, bool forceUpdate = false) override {} bool IsSliderControl() override { return false; } bool IsButtonControl() override { return false; } void SaveState(FileStreamOut& out) override; void LoadState(FileStreamIn& in, bool shouldSetValue = true) override; protected: ~UIGrid(); //protected so that it can't be created on the stack private: void OnClicked(float x, float y, bool right) override; void GetDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } int GetDataIndex(int col, int row) { return col + row * MAX_GRID_COLS; } float GetX(int col, int row) const; float GetY(int row) const; bool CanAdjustMultislider() const; struct HighlightColBuffer { double time{ 0 }; int col{ -1 }; }; float mWidth{ 200 }; float mHeight{ 200 }; int mRows{ 0 }; int mCols{ 0 }; bool mClick{ false }; float mHoldVal; int mHoldCol{ 0 }; int mHoldRow{ 0 }; bool mLastClickWasClear{ false }; std::array<float, MAX_GRID_COLS * MAX_GRID_ROWS> mData{}; std::array<HighlightColBuffer, 10> mHighlightColBuffer{}; int mNextHighlightColPointer{ 0 }; int mMajorCol{ -1 }; bool mSingleColumn{ false }; bool mFlip{ false }; float mStrength{ 1 }; int mCurrentHover{ -1 }; float mCurrentHoverAmount{ 1 }; UIGridListener* mListener{ nullptr }; std::array<float, MAX_GRID_ROWS> mDrawOffset{}; GridMode mGridMode{ GridMode::kNormal }; bool mRestrictDragToRow{ false }; bool mRequireShiftForMultislider{ false }; bool mShouldDrawValue{ false }; bool mMomentary{ false }; int mClickSubdivisions{ 1 }; }; ```
/content/code_sandbox/Source/UIGrid.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,415
```objective-c // // M185Sequencer.h // modularSynth // // Created by Lionel Landwerlin on 07/22/21. // // #pragma once #include <iostream> #include "ClickButton.h" #include "IDrawableModule.h" #include "INoteReceiver.h" #include "INoteSource.h" #include "IPulseReceiver.h" #include "Slider.h" #include "IDrivableSequencer.h" #define NUM_M185SEQUENCER_STEPS 8 class M185Sequencer : public IDrawableModule, public IButtonListener, public IDropdownListener, public IIntSliderListener, public ITimeListener, public IPulseReceiver, public INoteSource, public IDrivableSequencer { public: M185Sequencer(); virtual ~M185Sequencer(); static IDrawableModule* Create() { return new M185Sequencer(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return true; } void CreateUIControls() override; void Init() override; //IButtonListener void ButtonClicked(ClickButton* button, double time) override; //IDrawableModule void SetEnabled(bool enabled) override { mEnabled = enabled; } //ITimeListener void OnTimeEvent(double time) override; //IPulseReceiver void OnPulse(double time, float velocity, int flags) override; //IDrivableSequencer bool HasExternalPulseSource() const override { return mHasExternalPulseSource; } void ResetExternalPulseSource() override { mHasExternalPulseSource = false; } //IDropdownListener void DropdownUpdated(DropdownList* list, int oldVal, double time) override; //IIntSliderListener void IntSliderUpdated(IntSlider* slider, 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; 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 StepBy(double time, float velocity, int flags); void ResetStep(); void FindNextStep(); enum GateType { kGate_Repeat, kGate_Once, kGate_Hold, kGate_Rest, }; struct Step { Step() {} int mPitch{ 0 }; int mPulseCount{ 0 }; GateType mGate{ GateType::kGate_Repeat }; float xPos{ 0 }, yPos{ 0 }; IntSlider* mPitchSlider{ nullptr }; IntSlider* mPulseCountSlider{ nullptr }; DropdownList* mGateSelector{ nullptr }; }; std::array<Step, NUM_M185SEQUENCER_STEPS> mSteps; float mWidth{ 0 }, mHeight{ 0 }; bool mHasExternalPulseSource{ false }; TransportListenerInfo* mTransportListenerInfo{ nullptr }; // Going through 0..(mSteps.size() - 1) int mStepIdx{ 0 }; int mLastPlayedStepIdx{ 0 }; // Going through 0..(mSteps[X].mPulseCount - 1) int mStepPulseIdx{ 0 }; int mLastPitch{ 0 }; NoteInterval mInterval{ NoteInterval::kInterval_8n }; DropdownList* mIntervalSelector{ nullptr }; ClickButton* mResetStepButton{ nullptr }; }; ```
/content/code_sandbox/Source/M185Sequencer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
852
```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 **/ // // CanvasElement.cpp // Bespoke // // Created by Ryan Challinor on 1/4/15. // // #include "CanvasElement.h" #include "Sample.h" #include "SynthGlobals.h" #include "Slider.h" #include "CanvasControls.h" #include "TextEntry.h" #include "ModularSynth.h" #include "EventCanvas.h" #include "SampleCanvas.h" CanvasElement::CanvasElement(Canvas* canvas, int col, int row, float offset, float length) : mCanvas(canvas) , mOffset(offset) , mLength(length) , mCol(col) , mRow(row) { } void CanvasElement::Draw(ofVec2f offset) { if (offset.x == 0 && offset.y == 0) { DrawElement(K(clamp), !K(wrapped), offset); if (mCanvas->ShouldWrap() && GetEnd() > 1) DrawElement(K(clamp), K(wrapped), offset); } else { ofPushStyle(); ofSetLineWidth(3.0f); ofNoFill(); ofSetColor(255, 255, 255, ofMap(sin(gTime / 500 * PI * 2), -1, 1, 40, 120)); ofRect(GetRectAtDestination(K(clamp), !K(wrapped), offset), 0); if (mCanvas->ShouldWrap() && GetEnd() > 1) ofRect(GetRectAtDestination(K(clamp), K(wrapped), offset), 0); ofPopStyle(); DrawElement(!K(clamp), !K(wrapped), offset); } } void CanvasElement::DrawElement(bool clamp, bool wrapped, ofVec2f offset) { ofRectangle rect = GetRect(clamp, wrapped, offset); ofRectangle fullRect = GetRect(false, wrapped, offset); if (rect.width < 0) { ofPushStyle(); ofFill(); ofSetColor(255, 0, 0); ofRect(rect.x + rect.width, rect.y, -rect.width, rect.height, 0); ofPopStyle(); } ofPushStyle(); DrawContents(clamp, wrapped, offset); ofPopStyle(); if (mHighlighted && mCanvas == gHoveredUIControl) { ofPushStyle(); ofNoFill(); ofSetColor(255, 200, 0); ofSetLineWidth(.75f); ofLine(rect.x, rect.y, rect.x + rect.width, rect.y); ofLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); if (fullRect.x >= 0) { ofPushStyle(); if (mCanvas->GetHighlightEnd() == Canvas::kHighlightEnd_Start && IsResizable()) { ofSetLineWidth(1.5f); ofSetColor(255, 100, 100); } ofLine(rect.x, rect.y, rect.x, rect.y + rect.height); ofPopStyle(); } if (fullRect.x + fullRect.width <= mCanvas->GetLength() * mCanvas->GetWidth()) { ofPushStyle(); if (mCanvas->GetHighlightEnd() == Canvas::kHighlightEnd_End && IsResizable()) { ofSetLineWidth(1.5f); ofSetColor(255, 100, 100); } ofLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); ofPopStyle(); } ofPopStyle(); } } void CanvasElement::DrawOffscreen() { ofPushStyle(); ofSetLineWidth(1); ofSetColor(255, 255, 255); { ofRectangle rect = GetRect(K(clamp), !K(wrapped)); if (rect.y < 0) { rect.y = 0; rect.height = 1; } if (rect.y + rect.height > mCanvas->GetHeight()) { rect.y = mCanvas->GetHeight() - 1; rect.height = 1; } rect.width = MAX(rect.width, 1); ofRect(rect); } if (mCanvas->ShouldWrap() && GetEnd() > 1) { ofRectangle rect = GetRect(K(clamp), K(wrapped)); if (rect.y < 0) { rect.y = 0; rect.height = 1; } if (rect.y > mCanvas->GetHeight()) { rect.y = mCanvas->GetHeight() - 1; rect.height = 1; } rect.width = MAX(rect.width, 1); ofRect(rect); } ofPopStyle(); } float CanvasElement::GetStart(int col, float offset) const { return (col + offset) / mCanvas->GetNumCols(); } float CanvasElement::GetEnd(int col, float offset, float length) const { return (col + offset + length) / mCanvas->GetNumCols(); } float CanvasElement::GetStart() const { return GetStart(mCol, mOffset); } void CanvasElement::SetStart(float start, bool preserveLength) { float end = 0; if (!preserveLength) end = GetEnd(); start *= mCanvas->GetNumCols(); mCol = int(start + .5f); mOffset = start - mCol; if (!preserveLength) SetEnd(end); } float CanvasElement::GetEnd() const { return GetEnd(mCol, mOffset, mLength); } void CanvasElement::SetEnd(float end) { mLength = end * mCanvas->GetNumCols() - mCol - mOffset; } ofRectangle CanvasElement::GetRect(bool clamp, bool wrapped, ofVec2f offset) const { float wrapOffset = wrapped ? -1 : 0; float start = ofMap(GetStart() + wrapOffset, mCanvas->mViewStart / mCanvas->GetLength(), mCanvas->mViewEnd / mCanvas->GetLength(), 0, 1, clamp) * mCanvas->GetWidth(); float end = ofMap(GetEnd() + wrapOffset, mCanvas->mViewStart / mCanvas->GetLength(), mCanvas->mViewEnd / mCanvas->GetLength(), 0, 1, clamp) * mCanvas->GetWidth(); float y = (float(mRow - mCanvas->GetRowOffset()) / mCanvas->GetNumVisibleRows()) * mCanvas->GetHeight(); float height = float(mCanvas->GetHeight()) / mCanvas->GetNumVisibleRows(); return ofRectangle(start + offset.x, y + offset.y, end - start, height); } ofRectangle CanvasElement::GetRectAtDestination(bool clamp, bool wrapped, ofVec2f dragOffset) const { int newRow; int newCol; float newOffset; GetDragDestinationData(dragOffset, newRow, newCol, newOffset); float wrapOffset = wrapped ? -1 : 0; float start = ofMap(GetStart(newCol, newOffset) + wrapOffset, mCanvas->mViewStart / mCanvas->GetLength(), mCanvas->mViewEnd / mCanvas->GetLength(), 0, 1, clamp) * mCanvas->GetWidth(); float end = ofMap(GetEnd(newCol, newOffset, mLength) + wrapOffset, mCanvas->mViewStart / mCanvas->GetLength(), mCanvas->mViewEnd / mCanvas->GetLength(), 0, 1, clamp) * mCanvas->GetWidth(); float y = (float(newRow - mCanvas->GetRowOffset()) / mCanvas->GetNumVisibleRows()) * mCanvas->GetHeight(); float height = float(mCanvas->GetHeight()) / mCanvas->GetNumVisibleRows(); return ofRectangle(start, y, end - start, height); } void CanvasElement::GetDragDestinationData(ofVec2f dragOffset, int& newRow, int& newCol, float& newOffset) const { dragOffset.x *= mCanvas->mViewEnd - mCanvas->mViewStart; float colDrag = (dragOffset.x / mCanvas->GetWidth()) * mCanvas->GetNumCols() / mCanvas->GetLength(); float rowDrag = (dragOffset.y / mCanvas->GetHeight()) * mCanvas->GetNumVisibleRows(); newCol = mCol; if (mCanvas->GetDragMode() & Canvas::kDragHorizontal) newCol = ofClamp(int(mCol + colDrag + .5f), 0, mCanvas->GetNumCols() - 1); newRow = mRow; if (mCanvas->GetDragMode() & Canvas::kDragVertical) newRow = ofClamp(int(mRow + rowDrag + .5f), 0, mCanvas->GetNumRows() - 1); newOffset = mOffset; if (GetKeyModifiers() & kModifier_Alt) //non-snapped drag newOffset = mOffset + colDrag - (newCol - mCol); if (GetKeyModifiers() & kModifier_Command) //quantize newOffset = 0; } void CanvasElement::MoveElementByDrag(ofVec2f dragOffset) { int newRow; int newCol; float newOffset; GetDragDestinationData(dragOffset, newRow, newCol, newOffset); mRow = newRow; mCol = newCol; mOffset = newOffset; } void CanvasElement::AddElementUIControl(IUIControl* control) { mUIControls.push_back(control); // Block modulation cables from targeting these controls. control->SetCableTargetable(false); control->SetShowing(false); } void CanvasElement::CheckboxUpdated(std::string label, bool value, double time) { for (auto* control : mUIControls) { if (control->Name() == label) control->SetValue(value, time); } } void CanvasElement::FloatSliderUpdated(std::string label, float oldVal, float newVal, double time) { for (auto* control : mUIControls) { if (control->Name() == label) control->SetValue(newVal, time); } } void CanvasElement::IntSliderUpdated(std::string label, int oldVal, float newVal, double time) { for (auto* control : mUIControls) { if (control->Name() == label) control->SetValue(newVal, time); } } void CanvasElement::ButtonClicked(std::string label, double time) { } namespace { const int kCESaveStateRev = 1; } void CanvasElement::SaveState(FileStreamOut& out) { out << kCESaveStateRev; out << mOffset; out << mLength; } void CanvasElement::LoadState(FileStreamIn& in) { int rev; in >> rev; LoadStateValidate(rev <= kCESaveStateRev); if (rev < 1) { in >> mRow; in >> mCol; } in >> mOffset; in >> mLength; } //////////////////// NoteCanvasElement::NoteCanvasElement(Canvas* canvas, int col, int row, float offset, float length) : CanvasElement(canvas, col, row, offset, length) { if (canvas != nullptr && canvas->GetControls()) { mElementOffsetSlider = new FloatSlider(dynamic_cast<IFloatSliderListener*>(canvas->GetControls()), "offset", 0, 0, 100, 15, &mOffset, -1, 1); AddElementUIControl(mElementOffsetSlider); mElementLengthSlider = new FloatSlider(dynamic_cast<IFloatSliderListener*>(canvas->GetControls()), "length", 0, 0, 100, 15, &mLength, 0, mCanvas->GetNumCols()); AddElementUIControl(mElementLengthSlider); mElementRowSlider = new IntSlider(dynamic_cast<IIntSliderListener*>(canvas->GetControls()), "row", 0, 0, 100, 15, &mRow, 0, mCanvas->GetNumRows() - 1); AddElementUIControl(mElementRowSlider); mElementColSlider = new IntSlider(dynamic_cast<IIntSliderListener*>(canvas->GetControls()), "step", 0, 0, 100, 15, &mCol, 0, mCanvas->GetNumCols() - 1); AddElementUIControl(mElementColSlider); mVelocitySlider = new FloatSlider(dynamic_cast<IFloatSliderListener*>(canvas->GetControls()), "velocity", 0, 0, 100, 15, &mVelocity, 0, 1); AddElementUIControl(mVelocitySlider); } } CanvasElement* NoteCanvasElement::CreateDuplicate() const { NoteCanvasElement* element = new NoteCanvasElement(mCanvas, mCol, mRow, mOffset, mLength); element->mVelocity = mVelocity; element->mVoiceIdx = mVoiceIdx; return element; } void NoteCanvasElement::DrawContents(bool clamp, bool wrapped, ofVec2f offset) { ofPushStyle(); ofFill(); //DrawTextNormal(ofToString(mVelocity), GetRect(true, false).x, GetRect(true, false).y); ofRectangle rect = GetRect(clamp, wrapped, offset); float fullHeight = rect.height; rect.height *= mVelocity; rect.y += (fullHeight - rect.height) * .5f; if (rect.width > 0) { ofSetColorGradient(ofColor::white, ofColor(210, 210, 210), ofVec2f(ofLerp(rect.getMinX(), rect.getMaxX(), .5f), rect.y), ofVec2f(rect.getMaxX(), rect.y)); ofRect(rect, 0); } /*ofSetLineWidth(1.5f * gDrawScale); rect = GetRect(clamp, wrapped); ofRectangle fullRect = GetRect(false, false); if (wrapped) fullRect.x -= mCanvas->GetWidth(); float length = (GetEnd()-GetStart()) * mCanvas->GetLength(); float start = (float(rect.x-fullRect.x)/fullRect.width); float end = ((float(rect.x+rect.width)-(fullRect.x))/fullRect.width); mPitchBendCurve.SetPosition(rect.x, rect.y - rect.height/2); mPitchBendCurve.SetDimensions(rect.width, rect.height); mPitchBendCurve.SetExtents(start*length, end*length); mPitchBendCurve.SetColor(ofColor::red); mPitchBendCurve.Render(); mModWheelCurve.SetPosition(rect.x, rect.y); mModWheelCurve.SetDimensions(rect.width, rect.height); mModWheelCurve.SetExtents(start*length, end*length); mModWheelCurve.SetColor(ofColor::green); mModWheelCurve.Render(); mPressureCurve.SetPosition(rect.x, rect.y); mPressureCurve.SetDimensions(rect.width, rect.height); mPressureCurve.SetExtents(start*length, end*length); mPressureCurve.SetColor(ofColor::blue); mPressureCurve.Render();*/ ofPopStyle(); } void NoteCanvasElement::UpdateModulation(float pos) { float curveTime = (pos - GetStart()) * mCanvas->GetLength(); curveTime = FloatWrap(curveTime, mCanvas->GetLength()); mPitchBend.SetValue(mPitchBendCurve.Evaluate(curveTime)); mModWheel.SetValue(mModWheelCurve.Evaluate(curveTime)); mPressure.SetValue(mPressureCurve.Evaluate(curveTime)); mPan = mPanCurve.Evaluate(curveTime); } void NoteCanvasElement::WriteModulation(float pos, float pitchBend, float modWheel, float pressure, float pan) { float curveTime = (pos - GetStart()) * mCanvas->GetLength(); curveTime = FloatWrap(curveTime, mCanvas->GetLength()); mPitchBendCurve.AddPoint(CurvePoint(curveTime, pitchBend)); mModWheelCurve.AddPoint(CurvePoint(curveTime, modWheel)); mPressureCurve.AddPoint(CurvePoint(curveTime, pressure)); mPanCurve.AddPoint(CurvePoint(curveTime, pan)); } namespace { const int kNCESaveStateRev = 0; } void NoteCanvasElement::SaveState(FileStreamOut& out) { CanvasElement::SaveState(out); out << kNCESaveStateRev; out << mVelocity; } void NoteCanvasElement::LoadState(FileStreamIn& in) { CanvasElement::LoadState(in); int rev; in >> rev; LoadStateValidate(rev <= kNCESaveStateRev); in >> mVelocity; } ///////////////////// SampleCanvasElement::SampleCanvasElement(Canvas* canvas, int col, int row, float offset, float length) : CanvasElement(canvas, col, row, offset, length) { mElementOffsetSlider = new FloatSlider(dynamic_cast<IFloatSliderListener*>(canvas->GetControls()), "offset", 0, 0, 100, 15, &mOffset, -1, 1); AddElementUIControl(mElementOffsetSlider); mVolumeSlider = new FloatSlider(dynamic_cast<IFloatSliderListener*>(canvas->GetControls()), "volume", 0, 0, 100, 15, &mVolume, 0, 2); AddElementUIControl(mVolumeSlider); mMuteCheckbox = new Checkbox(dynamic_cast<IDrawableModule*>(canvas->GetControls()), "mute", 0, 0, &mMute); AddElementUIControl(mMuteCheckbox); mSplitSampleButton = new ClickButton(dynamic_cast<IButtonListener*>(canvas->GetControls()), "split", 0, 0); AddElementUIControl(mSplitSampleButton); mResetSpeedButton = new ClickButton(dynamic_cast<IButtonListener*>(canvas->GetControls()), "reset speed", 0, 0); AddElementUIControl(mResetSpeedButton); } SampleCanvasElement::~SampleCanvasElement() { delete mSample; } CanvasElement* SampleCanvasElement::CreateDuplicate() const { SampleCanvasElement* element = new SampleCanvasElement(mCanvas, mCol, mRow, mOffset, mLength); element->mSample = new Sample(); element->mSample->Create(mSample->Data()); element->mVolume = mVolume; element->mMute = mMute; return element; } void SampleCanvasElement::SetSample(Sample* sample) { mSample = sample; } void SampleCanvasElement::CheckboxUpdated(std::string label, bool value, double time) { CanvasElement::CheckboxUpdated(label, value, time); } void SampleCanvasElement::ButtonClicked(std::string label, double time) { CanvasElement::ButtonClicked(label, time); if (label == "split") { ChannelBuffer* firstHalf = new ChannelBuffer(mSample->Data()->BufferSize() / 2); ChannelBuffer* secondHalf = new ChannelBuffer(mSample->Data()->BufferSize() / 2); firstHalf->CopyFrom(mSample->Data(), firstHalf->BufferSize(), 0); secondHalf->CopyFrom(mSample->Data(), secondHalf->BufferSize(), mSample->Data()->BufferSize() / 2); SampleCanvasElement* element = new SampleCanvasElement(mCanvas, mCol, mRow, mOffset, mLength); element->mSample = new Sample(); element->mSample->Create(secondHalf); element->mVolume = mVolume; element->mMute = mMute; element->SetStart((GetStart() + GetEnd()) * .5f, false); mCanvas->AddElement(element); mSample->Create(firstHalf); mLength /= 2; } if (label == "reset speed") { SampleCanvas* sampleCanvas = dynamic_cast<SampleCanvas*>(mCanvas->GetParent()); if (sampleCanvas != nullptr) { float lengthMs = mSample->LengthInSamples() / mSample->GetSampleRateRatio() / gSampleRateMs; float lengthOriginalSpeed = lengthMs / TheTransport->GetDuration(sampleCanvas->GetInterval()); mLength = lengthOriginalSpeed; } } } void SampleCanvasElement::DrawContents(bool clamp, bool wrapped, ofVec2f offset) { if (wrapped) return; ofRectangle rect = GetRect(false, false, offset); ofPushMatrix(); ofTranslate(rect.x, rect.y); if (mSample) { float width = rect.width; DrawAudioBuffer(width, rect.height, mSample->Data(), 0, mSample->LengthInSamples(), -1); } else { ofSetColor(0, 0, 0); ofRect(0, 0, rect.width, rect.height); } ofPopMatrix(); if (rect.width < 0) rect.set(rect.x + rect.width, rect.y, -rect.width, rect.height); SampleCanvas* sampleCanvas = dynamic_cast<SampleCanvas*>(mCanvas->GetParent()); if (sampleCanvas != nullptr && mSample != nullptr) { float lengthMs = mSample->LengthInSamples() / mSample->GetSampleRateRatio() / gSampleRateMs; float lengthOriginalSpeed = lengthMs / TheTransport->GetDuration(sampleCanvas->GetInterval()); float speed = lengthOriginalSpeed / mLength; ofSetColor(255, 255, 255); DrawTextBold(ofToString(speed, 2), rect.x + 3, rect.y + 10, 10); } if (mMute) { ofSetColor(0, 0, 0, 140); ofFill(); ofRect(rect); } ofSetColor(255, 255, 255); ofNoFill(); ofRect(rect); } namespace { const int kSCESaveStateRev = 2; } void SampleCanvasElement::SaveState(FileStreamOut& out) { CanvasElement::SaveState(out); out << kSCESaveStateRev; bool hasSample = mSample != nullptr; out << hasSample; if (mSample != nullptr) mSample->SaveState(out); out << mVolume; out << mMute; } void SampleCanvasElement::LoadState(FileStreamIn& in) { CanvasElement::LoadState(in); int rev; in >> rev; LoadStateValidate(rev <= kSCESaveStateRev); bool hasSample; in >> hasSample; if (hasSample) { mSample = new Sample(); mSample->LoadState(in); } if (rev < 2) { int dummy; in >> dummy; in >> dummy; } in >> mVolume; if (rev == 0) { bool dummy; in >> dummy; } if (rev >= 1) in >> mMute; } ///////////////////// EventCanvasElement::EventCanvasElement(Canvas* canvas, int col, int row, float offset) : CanvasElement(canvas, col, row, offset, .5f) { mValueEntry = new TextEntry(dynamic_cast<ITextEntryListener*>(canvas->GetControls()), "value", 60, 2, 7, &mValue, -99999, 99999); AddElementUIControl(mValueEntry); mEventCanvas = dynamic_cast<EventCanvas*>(canvas->GetControls()->GetParent()); assert(mEventCanvas); mUIControl = mEventCanvas->GetUIControlForRow(row); mIsCheckbox = dynamic_cast<Checkbox*>(mUIControl) != nullptr; mIsButton = dynamic_cast<ClickButton*>(mUIControl) != nullptr; if (mUIControl) mValue = mUIControl->GetValue(); if (mIsButton) mValue = 1; } EventCanvasElement::~EventCanvasElement() { } CanvasElement* EventCanvasElement::CreateDuplicate() const { EventCanvasElement* element = new EventCanvasElement(mCanvas, mCol, mRow, mOffset); element->mUIControl = mUIControl; element->mIsCheckbox = mIsCheckbox; element->mIsButton = mIsButton; element->mValue = mValue; return element; } void EventCanvasElement::DrawContents(bool clamp, bool wrapped, ofVec2f offset) { if (wrapped) return; if (GetRect(false, false, offset).width != GetRect(clamp, false, offset).width) return; //only draw text for fully visible elements ofSetColor(mEventCanvas->GetRowColor(mRow)); ofFill(); ofRect(GetRect(clamp, wrapped, offset), 0); std::string text; if (mIsCheckbox) { text = mUIControl->Name(); ofRectangle rect = GetRect(clamp, false, offset); ofSetColor(0, 0, 0); DrawTextNormal(text, rect.x + 4, rect.y + 11); ofSetColor(255, 255, 255); DrawTextNormal(text, rect.x + 3, rect.y + 10); } else if (mUIControl) { text += mUIControl->Name(); text += ":"; text += mUIControl->GetDisplayValue(mValue); ofRectangle rect = GetRect(clamp, false, offset); ofSetColor(0, 0, 0); DrawTextNormal(text, rect.x + rect.width + 1, rect.y + 11); ofSetColor(255, 255, 255); DrawTextNormal(text, rect.x + rect.width, rect.y + 10); } } void EventCanvasElement::SetUIControl(IUIControl* control) { bool hadUIControl = mUIControl != nullptr; mUIControl = dynamic_cast<IUIControl*>(control); mIsCheckbox = dynamic_cast<Checkbox*>(control) != nullptr; mIsButton = dynamic_cast<ClickButton*>(control) != nullptr; if (mUIControl && !hadUIControl) mValue = mUIControl->GetValue(); if (mIsButton) mValue = 1; } void EventCanvasElement::Trigger(double time) { if (mUIControl) { if (mIsCheckbox) mUIControl->SetValue(1, time); else mUIControl->SetValue(mValue, time); } } void EventCanvasElement::TriggerEnd(double time) { if (mUIControl && mIsCheckbox) mUIControl->SetValue(0, time); } float EventCanvasElement::GetEnd() const { if (mIsCheckbox) //normal resizable element return CanvasElement::GetEnd(); float size = 4; float span = mCanvas->mViewEnd - mCanvas->mViewStart; return GetStart() + size * span / mCanvas->GetWidth(); } namespace { const int kECESaveStateRev = 1; } void EventCanvasElement::SaveState(FileStreamOut& out) { CanvasElement::SaveState(out); out << kECESaveStateRev; out << mValue; } void EventCanvasElement::LoadState(FileStreamIn& in) { CanvasElement::LoadState(in); int rev; in >> rev; LoadStateValidate(rev <= kECESaveStateRev); in >> mValue; if (rev < 1) { std::string dummy; in >> dummy; } } ```
/content/code_sandbox/Source/CanvasElement.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
6,122
```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 **/ // // FFTtoAdditive.cpp // modularSynth // // Created by Ryan Challinor on 4/24/13. // // #include "FFTtoAdditive.h" #include "ModularSynth.h" #include "Profiler.h" #include <cstring> namespace { const int fftWindowSize = 1024; const int fftFreqDomainSize = fftWindowSize / 2 + 1; const int numPartials = fftFreqDomainSize - 1; double sineBuffer[514] = { 0, 0.012268, 0.024536, 0.036804, 0.049042, 0.06131, 0.073547, 0.085785, 0.097992, 0.1102, 0.12241, 0.13455, 0.1467, 0.15884, 0.17093, 0.18301, 0.19507, 0.20709, 0.21909, 0.23105, 0.24295, 0.25485, 0.26669, 0.2785, 0.29025, 0.30197, 0.31366, 0.32529, 0.33685, 0.34839, 0.35986, 0.37128, 0.38266, 0.39395, 0.40521, 0.41641, 0.42752, 0.4386, 0.44958, 0.46051, 0.47137, 0.48215, 0.49286, 0.50351, 0.51407, 0.52457, 0.53497, 0.54529, 0.55554, 0.5657, 0.57578, 0.58575, 0.59567, 0.60547, 0.6152, 0.62482, 0.63437, 0.6438, 0.65314, 0.66238, 0.67151, 0.68057, 0.68951, 0.69833, 0.70706, 0.7157, 0.72421, 0.7326, 0.74091, 0.74908, 0.75717, 0.76514, 0.77298, 0.7807, 0.7883, 0.79581, 0.80316, 0.81042, 0.81754, 0.82455, 0.83142, 0.8382, 0.84482, 0.85132, 0.8577, 0.86392, 0.87006, 0.87604, 0.88187, 0.8876, 0.89319, 0.89862, 0.90396, 0.90912, 0.91415, 0.91907, 0.92383, 0.92847, 0.93295, 0.93729, 0.9415, 0.94556, 0.94949, 0.95325, 0.95691, 0.96039, 0.96375, 0.96692, 0.97, 0.9729, 0.97565, 0.97827, 0.98074, 0.98306, 0.98523, 0.98724, 0.98914, 0.99084, 0.99243, 0.99387, 0.99515, 0.99628, 0.99725, 0.99808, 0.99875, 0.99927, 0.99966, 0.99988, 0.99997, 0.99988, 0.99966, 0.99927, 0.99875, 0.99808, 0.99725, 0.99628, 0.99515, 0.99387, 0.99243, 0.99084, 0.98914, 0.98724, 0.98523, 0.98306, 0.98074, 0.97827, 0.97565, 0.9729, 0.97, 0.96692, 0.96375, 0.96039, 0.95691, 0.95325, 0.94949, 0.94556, 0.9415, 0.93729, 0.93295, 0.92847, 0.92383, 0.91907, 0.91415, 0.90912, 0.90396, 0.89862, 0.89319, 0.8876, 0.88187, 0.87604, 0.87006, 0.86392, 0.8577, 0.85132, 0.84482, 0.8382, 0.83142, 0.82455, 0.81754, 0.81042, 0.80316, 0.79581, 0.7883, 0.7807, 0.77298, 0.76514, 0.75717, 0.74908, 0.74091, 0.7326, 0.72421, 0.7157, 0.70706, 0.69833, 0.68951, 0.68057, 0.67151, 0.66238, 0.65314, 0.6438, 0.63437, 0.62482, 0.6152, 0.60547, 0.59567, 0.58575, 0.57578, 0.5657, 0.55554, 0.54529, 0.53497, 0.52457, 0.51407, 0.50351, 0.49286, 0.48215, 0.47137, 0.46051, 0.44958, 0.4386, 0.42752, 0.41641, 0.40521, 0.39395, 0.38266, 0.37128, 0.35986, 0.34839, 0.33685, 0.32529, 0.31366, 0.30197, 0.29025, 0.2785, 0.26669, 0.25485, 0.24295, 0.23105, 0.21909, 0.20709, 0.19507, 0.18301, 0.17093, 0.15884, 0.1467, 0.13455, 0.12241, 0.1102, 0.097992, 0.085785, 0.073547, 0.06131, 0.049042, 0.036804, 0.024536, 0.012268, 0, -0.012268, -0.024536, -0.036804, -0.049042, -0.06131, -0.073547, -0.085785, -0.097992, -0.1102, -0.12241, -0.13455, -0.1467, -0.15884, -0.17093, -0.18301, -0.19507, -0.20709, -0.21909, -0.23105, -0.24295, -0.25485, -0.26669, -0.2785, -0.29025, -0.30197, -0.31366, -0.32529, -0.33685, -0.34839, -0.35986, -0.37128, -0.38266, -0.39395, -0.40521, -0.41641, -0.42752, -0.4386, -0.44958, -0.46051, -0.47137, -0.48215, -0.49286, -0.50351, -0.51407, -0.52457, -0.53497, -0.54529, -0.55554, -0.5657, -0.57578, -0.58575, -0.59567, -0.60547, -0.6152, -0.62482, -0.63437, -0.6438, -0.65314, -0.66238, -0.67151, -0.68057, -0.68951, -0.69833, -0.70706, -0.7157, -0.72421, -0.7326, -0.74091, -0.74908, -0.75717, -0.76514, -0.77298, -0.7807, -0.7883, -0.79581, -0.80316, -0.81042, -0.81754, -0.82455, -0.83142, -0.8382, -0.84482, -0.85132, -0.8577, -0.86392, -0.87006, -0.87604, -0.88187, -0.8876, -0.89319, -0.89862, -0.90396, -0.90912, -0.91415, -0.91907, -0.92383, -0.92847, -0.93295, -0.93729, -0.9415, -0.94556, -0.94949, -0.95325, -0.95691, -0.96039, -0.96375, -0.96692, -0.97, -0.9729, -0.97565, -0.97827, -0.98074, -0.98306, -0.98523, -0.98724, -0.98914, -0.99084, -0.99243, -0.99387, -0.99515, -0.99628, -0.99725, -0.99808, -0.99875, -0.99927, -0.99966, -0.99988, -0.99997, -0.99988, -0.99966, -0.99927, -0.99875, -0.99808, -0.99725, -0.99628, -0.99515, -0.99387, -0.99243, -0.99084, -0.98914, -0.98724, -0.98523, -0.98306, -0.98074, -0.97827, -0.97565, -0.9729, -0.97, -0.96692, -0.96375, -0.96039, -0.95691, -0.95325, -0.94949, -0.94556, -0.9415, -0.93729, -0.93295, -0.92847, -0.92383, -0.91907, -0.91415, -0.90912, -0.90396, -0.89862, -0.89319, -0.8876, -0.88187, -0.87604, -0.87006, -0.86392, -0.8577, -0.85132, -0.84482, -0.8382, -0.83142, -0.82455, -0.81754, -0.81042, -0.80316, -0.79581, -0.7883, -0.7807, -0.77298, -0.76514, -0.75717, -0.74908, -0.74091, -0.7326, -0.72421, -0.7157, -0.70706, -0.69833, -0.68951, -0.68057, -0.67151, -0.66238, -0.65314, -0.6438, -0.63437, -0.62482, -0.6152, -0.60547, -0.59567, -0.58575, -0.57578, -0.5657, -0.55554, -0.54529, -0.53497, -0.52457, -0.51407, -0.50351, -0.49286, -0.48215, -0.47137, -0.46051, -0.44958, -0.4386, -0.42752, -0.41641, -0.40521, -0.39395, -0.38266, -0.37128, -0.35986, -0.34839, -0.33685, -0.32529, -0.31366, -0.30197, -0.29025, -0.2785, -0.26669, -0.25485, -0.24295, -0.23105, -0.21909, -0.20709, -0.19507, -0.18301, -0.17093, -0.15884, -0.1467, -0.13455, -0.12241, -0.1102, -0.097992, -0.085785, -0.073547, -0.06131, -0.049042, -0.036804, -0.024536, -0.012268, 0, 0.012268 }; } FFTtoAdditive::FFTtoAdditive() : IAudioProcessor(gBufferSize) , mFFT(fftWindowSize) , mRollingInputBuffer(fftWindowSize) , mRollingOutputBuffer(fftWindowSize) , mFFTData(fftWindowSize, fftFreqDomainSize) { // Generate a window with a single raised cosine from N/4 to 3N/4 mWindower = new float[fftWindowSize]; for (int i = 0; i < fftWindowSize; ++i) mWindower[i] = -.5 * cos(FTWO_PI * i / fftWindowSize) + .5; mPhaseInc = new float[numPartials]; for (int i = 0; i < numPartials; ++i) { float freq = i / float(fftFreqDomainSize) * (gNyquistLimit / 2); mPhaseInc[i] = GetPhaseInc(freq); } for (int i = 0; i < fftFreqDomainSize; ++i) { mFFTData.mRealValues[i] = 0; mFFTData.mImaginaryValues[i] = 0; } } void FFTtoAdditive::CreateUIControls() { IDrawableModule::CreateUIControls(); mInputSlider = new FloatSlider(this, "input", 5, 29, 100, 15, &mInputPreamp, 0, 2); mValue1Slider = new FloatSlider(this, "value 1", 5, 47, 100, 15, &mValue1, 0, 2); mVolumeSlider = new FloatSlider(this, "volume", 5, 65, 100, 15, &mVolume, 0, 2); mDryWetSlider = new FloatSlider(this, "dry/wet", 5, 83, 100, 15, &mDryWet, 0, 1); mValue2Slider = new FloatSlider(this, "value 2", 5, 101, 100, 15, &mValue2, 0, 1); mValue3Slider = new FloatSlider(this, "value 3", 5, 119, 100, 15, &mValue3, 0, 1); mPhaseOffsetSlider = new FloatSlider(this, "phase off", 5, 137, 100, 15, &mPhaseOffset, 0, FTWO_PI); } FFTtoAdditive::~FFTtoAdditive() { delete[] mWindower; } void FFTtoAdditive::Process(double time) { PROFILER(FFTtoAdditive); IAudioReceiver* target = GetTarget(); if (target == nullptr || !mEnabled) return; ComputeSliders(0); SyncBuffers(); float inputPreampSq = mInputPreamp * mInputPreamp; float volSq = mVolume * mVolume; int bufferSize = GetBuffer()->BufferSize(); mRollingInputBuffer.WriteChunk(GetBuffer()->GetChannel(0), bufferSize, 0); //copy rolling input buffer into working buffer and window it mRollingInputBuffer.ReadChunk(mFFTData.mTimeDomain, fftWindowSize, 0, 0); Mult(mFFTData.mTimeDomain, mWindower, fftWindowSize); Mult(mFFTData.mTimeDomain, inputPreampSq, fftWindowSize); mFFT.Forward(mFFTData.mTimeDomain, mFFTData.mRealValues, mFFTData.mImaginaryValues); for (int i = 0; i < fftFreqDomainSize; ++i) { float real = mFFTData.mRealValues[i]; float imag = mFFTData.mImaginaryValues[i]; //cartesian to polar float amp = 2. * sqrtf(real * real + imag * imag); float phase = atan2(imag, real); mFFTData.mRealValues[i] = amp / (fftWindowSize / 2); mFFTData.mImaginaryValues[i] = phase; } float* out = target->GetBuffer()->GetChannel(0); for (int i = 0; i < bufferSize; ++i) { float write = 0; for (int j = 1; j < numPartials; ++j) { float phase = ((mFFTData.mImaginaryValues[j + 1] + i * mPhaseInc[j]) / FTWO_PI) * 512; float sample = SinSample(phase) * mFFTData.mRealValues[j + 1] * volSq * .4f; write += sample; } GetVizBuffer()->Write(write, 0); out[i] += write; time += gInvSampleRateMs; } GetBuffer()->Reset(); } float FFTtoAdditive::SinSample(float phase) { int intPhase = int(phase) % 512; if (intPhase < 0) intPhase += 512; float remainder = phase - int(phase); float retVal = ((1 - remainder) * sineBuffer[intPhase] + remainder * sineBuffer[1 + intPhase]); return retVal; } void FFTtoAdditive::DrawModule() { if (Minimized() || IsVisible() == false) return; mInputSlider->Draw(); mValue1Slider->Draw(); mVolumeSlider->Draw(); mDryWetSlider->Draw(); mValue2Slider->Draw(); mValue3Slider->Draw(); mPhaseOffsetSlider->Draw(); DrawViz(); } void FFTtoAdditive::DrawViz() { ofPushStyle(); int zeroHeight = 240; for (int i = 1; i < RAZOR_HISTORY - 1; ++i) { float age = 1 - float(i) / RAZOR_HISTORY; ofSetColor(0, 200 * age, 255 * age); for (int x = 0; x < VIZ_WIDTH; ++x) { int intHeight = mPeakHistory[(i + mHistoryPtr) % RAZOR_HISTORY][x]; int intHeightNext = mPeakHistory[(i + mHistoryPtr + 1) % RAZOR_HISTORY][x]; if (intHeight != 0) { int xpos = 10 + x + i; int ypos = zeroHeight - intHeight - i; int xposNext = xpos; int yposNext = ypos; if (intHeightNext != 0) { xposNext = 10 + x + i + 1; yposNext = zeroHeight - intHeightNext - i + 1; } if (xpos < 1020) ofLine(xpos, ypos, xposNext, yposNext); } } } std::memset(mPeakHistory[mHistoryPtr], 0, sizeof(float) * VIZ_WIDTH); for (int i = 1; i <= numPartials; ++i) { float height = mFFTData.mRealValues[i - 1]; int intHeight = int(height * 100.0f); if (intHeight == 0) { if (height > 0) intHeight = 1; if (height < 0) intHeight = -1; } if (intHeight < 0) { ofSetColor(255, 0, 0); intHeight *= -1; } else { ofSetColor(255, 255, 255); } int x = int(ofMap(i, 4, numPartials, 0, VIZ_WIDTH, true)); ofLine(10 + x, zeroHeight, 10 + x, zeroHeight - intHeight); mPeakHistory[mHistoryPtr][x] = intHeight; } mHistoryPtr = (mHistoryPtr - 1 + RAZOR_HISTORY) % RAZOR_HISTORY; ofPopStyle(); } void FFTtoAdditive::CheckboxUpdated(Checkbox* checkbox, double time) { } void FFTtoAdditive::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void FFTtoAdditive::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); } ```
/content/code_sandbox/Source/FFTtoAdditive.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
5,123
```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 **/ /* ============================================================================== SignalClamp.cpp Created: 1 Dec 2019 3:24:55pm Author: Ryan Challinor ============================================================================== */ #include "SignalClamp.h" #include "ModularSynth.h" #include "Profiler.h" SignalClamp::SignalClamp() : IAudioProcessor(gBufferSize) { } void SignalClamp::CreateUIControls() { IDrawableModule::CreateUIControls(); mMinSlider = new FloatSlider(this, "min", 5, 2, 110, 15, &mMin, -2, 2); mMaxSlider = new FloatSlider(this, "max", mMinSlider, kAnchor_Below, 110, 15, &mMax, -2, 2); } SignalClamp::~SignalClamp() { } void SignalClamp::Process(double time) { PROFILER(SignalClamp); IAudioReceiver* target = GetTarget(); if (target == nullptr) return; ComputeSliders(0); SyncBuffers(); int bufferSize = GetBuffer()->BufferSize(); ChannelBuffer* out = target->GetBuffer(); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { float* buffer = GetBuffer()->GetChannel(ch); if (mEnabled) for (int i = 0; i < bufferSize; ++i) { ComputeSliders(i); buffer[i] = ofClamp(buffer[i], mMin, mMax); } Add(out->GetChannel(ch), buffer, bufferSize); GetVizBuffer()->WriteChunk(buffer, bufferSize, ch); } GetBuffer()->Reset(); } void SignalClamp::DrawModule() { if (Minimized() || IsVisible() == false) return; mMinSlider->Draw(); mMaxSlider->Draw(); } void SignalClamp::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void SignalClamp::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); } ```
/content/code_sandbox/Source/SignalClamp.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
570
```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 **/ // // LabelDisplay.h // Bespoke // // Created by Noxy Nixie on 03/19/2024. // // #pragma once #include <iostream> #include <utility> #include "IDrawableModule.h" #include "OpenFrameworksPort.h" #include "TextEntry.h" #include "Slider.h" #include "DropdownList.h" #include "Checkbox.h" #include "UIControlMacros.h" class LabelDisplay : public IDrawableModule, public ITextEntryListener, public IIntSliderListener, public IDropdownListener { public: LabelDisplay(); virtual ~LabelDisplay(); static IDrawableModule* Create() { return new LabelDisplay(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return false; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; void TextEntryComplete(TextEntry* entry) 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; bool IsEnabled() const override { return true; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; float mWidth{ 200 }; float mHeight{ 20 }; Checkbox* mShowControlsCheckbox{ nullptr }; bool mShowControls{ true }; char mLabel[MAX_TEXTENTRY_LENGTH]{ "Label" }; TextEntry* mLabelEntry{ nullptr }; int mLabelSize{ 40 }; IntSlider* mLabelSizeSlider{ nullptr }; RetinaTrueTypeFont mLabelFont{ gFont }; int mLabelFontIndex{ 0 }; DropdownList* mLabelFontDropdown{ nullptr }; struct LabelFont { LabelFont(std::string _name, RetinaTrueTypeFont _font) { name = std::move(_name); font = std::move(_font); } std::string name{ "Normal" }; RetinaTrueTypeFont font{ gFont }; }; std::vector<LabelFont> mFonts{}; ofColor mLabelColor{ ofColor::white }; int mLabelColorIndex{ 0 }; DropdownList* mLabelColorDropdown{ nullptr }; struct LabelColor { LabelColor(std::string _name, const ofColor _color) { name = std::move(_name); color = _color; } std::string name{ "White" }; ofColor color{ ofColor::white }; }; std::vector<LabelColor> mColors{}; }; ```
/content/code_sandbox/Source/LabelDisplay.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
692
```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 **/ // // LFOController.cpp // modularSynth // // Created by Ryan Challinor on 10/22/13. // // #include "LFOController.h" #include "ModularSynth.h" #include "SynthGlobals.h" #include "FloatSliderLFOControl.h" LFOController* TheLFOController = nullptr; LFOController::LFOController() { assert(TheLFOController == nullptr); TheLFOController = this; } void LFOController::CreateUIControls() { IDrawableModule::CreateUIControls(); mIntervalSelector = new DropdownList(this, "interval", 5, 40, &dummy); mOscSelector = new DropdownList(this, "osc", 50, 40, &dummy); mMinSlider = new FloatSlider(this, "low", 5, 4, 120, 15, &dummy2, 0, 1); mMaxSlider = new FloatSlider(this, "high", 5, 22, 120, 15, &dummy2, 0, 1); mBindButton = new ClickButton(this, "bind", 5, 60); mIntervalSelector->AddLabel("free", kInterval_Free); mIntervalSelector->AddLabel("64", kInterval_64); mIntervalSelector->AddLabel("32", kInterval_32); mIntervalSelector->AddLabel("16", kInterval_16); mIntervalSelector->AddLabel("8", kInterval_8); 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("2nt", kInterval_2nt); 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); mOscSelector->AddLabel("sin", kOsc_Sin); mOscSelector->AddLabel("saw", kOsc_Saw); mOscSelector->AddLabel("-saw", kOsc_NegSaw); mOscSelector->AddLabel("squ", kOsc_Square); mOscSelector->AddLabel("tri", kOsc_Tri); mOscSelector->AddLabel("rand", kOsc_Random); } LFOController::~LFOController() { assert(TheLFOController == this || TheLFOController == nullptr); TheLFOController = nullptr; } bool LFOController::WantsBinding(FloatSlider* slider) { if (slider == mMinSlider || slider == mMaxSlider) return false; return mWantBind; } void LFOController::SetSlider(FloatSlider* slider) { mSlider = slider; mLFO = slider->AcquireLFO(); if (mLFO == nullptr) return; LFOSettings* lfoSettings = mLFO->GetLFOSettings(); assert(lfoSettings); mMinSlider->MatchExtents(slider); mMaxSlider->MatchExtents(slider); mMinSlider->SetVar(&mLFO->GetMin()); mMaxSlider->SetVar(&mLFO->GetMax()); mIntervalSelector->SetVar((int*)(&lfoSettings->mInterval)); mOscSelector->SetVar((int*)(&lfoSettings->mOscType)); mLFO->SetEnabled(true); mStopBindTime = gTime + 1000; } void LFOController::Poll() { if (mWantBind && mStopBindTime != -1 && gTime > mStopBindTime) { mWantBind = false; mStopBindTime = -1; } } void LFOController::DrawModule() { if (Minimized() || IsVisible() == false) return; mIntervalSelector->Draw(); mOscSelector->Draw(); mMinSlider->Draw(); mMaxSlider->Draw(); mBindButton->Draw(); if (mSlider && mLFO && mLFO->IsEnabled()) { DrawTextNormal(mSlider->Name(), 50, 70); DrawConnection(mSlider); } } void LFOController::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (mLFO == nullptr) return; mLFO->UpdateFromSettings(); } void LFOController::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (mLFO == nullptr) return; LFOSettings* lfoSettings = mLFO->GetLFOSettings(); assert(lfoSettings); if (slider == mMinSlider) mLFO->GetMax() = MAX(mLFO->GetMax(), mLFO->GetMin()); if (slider == mMaxSlider) mLFO->GetMin() = MIN(mLFO->GetMax(), mLFO->GetMin()); } void LFOController::ButtonClicked(ClickButton* button, double time) { if (button == mBindButton) mWantBind = true; } ```
/content/code_sandbox/Source/LFOController.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,347
```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 **/ // // NoteToMs.cpp // Bespoke // // Created by Ryan Challinor on 12/17/15. // // #include "NoteToMs.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "ModulationChain.h" NoteToMs::NoteToMs() { } NoteToMs::~NoteToMs() { } void NoteToMs::CreateUIControls() { IDrawableModule::CreateUIControls(); mTargetCable = new PatchCableSource(this, kConnectionType_Modulator); mTargetCable->SetModulatorOwner(this); AddPatchCableSource(mTargetCable); } void NoteToMs::DrawModule() { if (Minimized() || IsVisible() == false) return; } void NoteToMs::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { OnModulatorRepatch(); } void NoteToMs::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled && velocity > 0) { mPitch = pitch; mPitchBend = modulation.pitchBend; } } float NoteToMs::Value(int samplesIn) { float bend = mPitchBend ? mPitchBend->GetValue(samplesIn) : 0; return 1000 / TheScale->PitchToFreq(mPitch + bend); } void NoteToMs::SaveLayout(ofxJSONElement& moduleInfo) { } void NoteToMs::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void NoteToMs::SetUpFromSaveData() { } ```
/content/code_sandbox/Source/NoteToMs.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
471
```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 **/ // // MultitrackRecorder.cpp // Bespoke // // Created by Ryan Challinor on 5/13/14. // // #include "MultitrackRecorder.h" #include "ModularSynth.h" #include "Profiler.h" #include "SynthGlobals.h" #include "Transport.h" #include "Sample.h" #include "UIControlMacros.h" #include "PatchCableSource.h" #include "UserPrefs.h" MultitrackRecorder::MultitrackRecorder() { mModuleContainer.SetOwner(this); } void MultitrackRecorder::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); CHECKBOX(mRecordCheckbox, "record", &mRecord); UIBLOCK_SHIFTRIGHT(); BUTTON(mClearButton, "clear"); UIBLOCK_NEWLINE(); BUTTON(mAddTrackButton, "add track"); UIBLOCK_SHIFTRIGHT(); BUTTON(mBounceButton, "bounce"); ENDUIBLOCK0(); } MultitrackRecorder::~MultitrackRecorder() { } void MultitrackRecorder::DrawModule() { if (Minimized() || IsVisible() == false) return; mAddTrackButton->SetShowing(!mRecord); mBounceButton->SetShowing(!mRecord); mRecordCheckbox->Draw(); mClearButton->Draw(); mAddTrackButton->Draw(); mBounceButton->Draw(); if (mStatusStringTime + 5000 > gTime) DrawTextNormal(mStatusString, 120, 33); float posX = 5; float posY = 42; for (auto* track : mTracks) { track->SetPosition(posX, posY); posY += 100; } mHeight = posY; mModuleContainer.DrawModules(); } void MultitrackRecorder::AddTrack() { int recordingLength = GetRecordingLength(); ModuleFactory::Spawnable spawnable; spawnable.mLabel = "multitrackrecordertrack"; MultitrackRecorderTrack* track = dynamic_cast<MultitrackRecorderTrack*>(TheSynth->SpawnModuleOnTheFly(spawnable, 0, 0, true)); track->Setup(this, recordingLength); track->SetName(GetUniqueName("track", mModuleContainer.GetModuleNames<MultitrackRecorderTrack*>()).c_str()); mModuleContainer.TakeModule(track); mTracks.push_back(track); } void MultitrackRecorder::RemoveTrack(MultitrackRecorderTrack* track) { if (!mRecord) { RemoveFromVector(track, mTracks); RemoveChild(track); mModuleContainer.DeleteModule(track); } } int MultitrackRecorder::GetRecordingLength() { int recordingLength = 0; for (auto* track : mTracks) { if (track->GetRecordingLength() > recordingLength) recordingLength = track->GetRecordingLength(); } return recordingLength; } void MultitrackRecorder::ButtonClicked(ClickButton* button, double time) { if (button == mAddTrackButton) { AddTrack(); } if (button == mBounceButton) { std::string save_prefix = "multitrack_"; if (!TheSynth->GetLastSavePath().empty()) { // This assumes that mCurrentSaveStatePath always has a valid filename at the end std::string filename = juce::File(TheSynth->GetLastSavePath()).getFileNameWithoutExtension().toStdString(); save_prefix = filename + "_"; } // Crude way of checking if the filename does not have a date/time in it. if (std::count(save_prefix.begin(), save_prefix.end(), '-') < 3) { save_prefix += "%Y-%m-%d_%H-%M_"; } std::string filenamePrefix = ofGetTimestampString(UserPrefs.recordings_path.Get() + save_prefix); int numFiles = 0; for (int i = 0; i < (int)mTracks.size(); ++i) { Sample* sample = mTracks[i]->BounceRecording(); if (sample) { std::string filename = filenamePrefix + ofToString(i + 1) + ".wav"; sample->Write(filename.c_str()); ++numFiles; } } if (numFiles > 0) { mStatusString = "wrote " + ofToString(numFiles) + " files to " + filenamePrefix + "*.wav"; mStatusStringTime = gTime; } } if (button == mClearButton) { for (auto* track : mTracks) track->Clear(); } } void MultitrackRecorder::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mRecordCheckbox) { for (auto* track : mTracks) track->SetRecording(mRecord); } } void MultitrackRecorder::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["modules"] = mModuleContainer.WriteModules(); } void MultitrackRecorder::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleContainer.LoadModules(moduleInfo["modules"]); for (auto* child : mModuleContainer.GetModules()) { MultitrackRecorderTrack* track = dynamic_cast<MultitrackRecorderTrack*>(child); if (!VectorContains(track, mTracks)) { track->Setup(this, GetRecordingLength()); mTracks.push_back(track); } } if (mTracks.size() == 0) AddTrack(); SetUpFromSaveData(); } void MultitrackRecorder::SetUpFromSaveData() { mRecord = false; for (auto* track : mTracks) track->SetRecording(false); } void MultitrackRecorder::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); out << mWidth; //preserve order out << (int)mTracks.size(); for (auto* track : mTracks) out << (std::string)track->Name(); } void MultitrackRecorder::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); in >> mWidth; //preserve order int numTracks; in >> numTracks; std::vector<std::string> sortOrder; for (int i = 0; i < numTracks; ++i) { std::string name; in >> name; sortOrder.push_back(name); } std::vector<MultitrackRecorderTrack*> sortedTracks; for (auto& name : sortOrder) { for (auto& track : mTracks) { if (track->Name() == name) { sortedTracks.push_back(track); break; } } } mTracks = sortedTracks; } ////////////////////////////////////////////////////////////////////////////////////////////// namespace { const int kRecordingChunkSize = 48000 * 5; const int kMinRecordingChunks = 2; }; MultitrackRecorderTrack::MultitrackRecorderTrack() : IAudioProcessor(gBufferSize) { } MultitrackRecorderTrack::~MultitrackRecorderTrack() { } void MultitrackRecorderTrack::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); BUTTON(mDeleteButton, " X "); ENDUIBLOCK0(); GetPatchCableSource()->SetManualSide(PatchCableSource::Side::kRight); } void MultitrackRecorderTrack::Process(double time) { int numChannels = GetBuffer()->NumActiveChannels(); for (size_t i = 0; i < mRecordChunks.size(); ++i) { if (mRecordChunks[i]->NumActiveChannels() > numChannels) numChannels = mRecordChunks[i]->NumActiveChannels(); } ComputeSliders(0); SyncBuffers(numChannels); if (mDoRecording) { for (size_t i = 0; i < mRecordChunks.size(); ++i) mRecordChunks[i]->SetNumActiveChannels(numChannels); for (int i = 0; i < GetBuffer()->BufferSize(); ++i) { int chunkIndex = mRecordingLength / kRecordingChunkSize; int chunkPos = mRecordingLength % kRecordingChunkSize; for (int ch = 0; ch < numChannels; ++ch) mRecordChunks[chunkIndex]->GetChannel(ch)[chunkPos] = GetBuffer()->GetChannel(MIN(ch, GetBuffer()->NumActiveChannels() - 1))[i]; ++mRecordingLength; } } if (GetTarget()) { for (int ch = 0; ch < GetTarget()->GetBuffer()->NumActiveChannels(); ++ch) { float* buffer = GetBuffer()->GetChannel(MIN(ch, GetBuffer()->NumActiveChannels() - 1)); Add(GetTarget()->GetBuffer()->GetChannel(ch), buffer, GetBuffer()->BufferSize()); GetVizBuffer()->WriteChunk(buffer, GetBuffer()->BufferSize(), MIN(ch, GetVizBuffer()->NumChannels() - 1)); } } GetBuffer()->Reset(); } void MultitrackRecorderTrack::Poll() { IDrawableModule::Poll(); int chunkIndex = mRecordingLength / kRecordingChunkSize; if (chunkIndex >= (int)mRecordChunks.size() - 1) { mRecordChunks.push_back(new ChannelBuffer(kRecordingChunkSize)); mRecordChunks[mRecordChunks.size() - 1]->GetChannel(0); //set up buffer } } void MultitrackRecorderTrack::DrawModule() { mDeleteButton->Draw(); float width, height; GetModuleDimensions(width, height); ofPushMatrix(); ofTranslate(5, 3); float sampleWidth = width - 10; ofSetColor(255, 255, 255, 30); ofFill(); ofRect(0, 0, sampleWidth, height - 6); if (mDoRecording) { ofSetColor(255, 0, 0, 100); ofNoFill(); ofRect(0, 0, sampleWidth, height - 6); } ofPushMatrix(); int numChunks = mRecordingLength / kRecordingChunkSize + 1; float chunkWidth = sampleWidth / numChunks; for (int i = 0; i < numChunks; ++i) { if (i < (int)mRecordChunks.size()) DrawAudioBuffer(chunkWidth, height - 6, mRecordChunks[i], 0, kRecordingChunkSize, -1); ofTranslate(chunkWidth, 0); } ofPopMatrix(); ofPopMatrix(); } void MultitrackRecorderTrack::Setup(MultitrackRecorder* recorder, int minLength) { mRecorder = recorder; mRecordingLength = minLength; } void MultitrackRecorderTrack::SetRecording(bool record) { if (record) { if (mRecordingLength == 0) { mRecordingLength = 0; for (size_t i = mRecordChunks.size(); i < kMinRecordingChunks; ++i) { mRecordChunks.push_back(new ChannelBuffer(kRecordingChunkSize)); mRecordChunks[i]->GetChannel(0); //set up buffer } for (size_t i = 0; i < mRecordChunks.size(); ++i) mRecordChunks[i]->Clear(); } mDoRecording = true; } else { mDoRecording = false; } } Sample* MultitrackRecorderTrack::BounceRecording() { Sample* sample = nullptr; if (mRecordingLength > 0) { sample = new Sample(); sample->Create(mRecordingLength); ChannelBuffer* data = sample->Data(); int channelCount = mRecordChunks[0]->NumActiveChannels(); data->SetNumActiveChannels(channelCount); int numChunks = mRecordingLength / kRecordingChunkSize + 1; for (int i = 0; i < numChunks; ++i) { int samplesLeftToRecord = mRecordingLength - i * kRecordingChunkSize; int samplesToCopy; if (samplesLeftToRecord > kRecordingChunkSize) samplesToCopy = kRecordingChunkSize; else samplesToCopy = samplesLeftToRecord; for (int ch = 0; ch < channelCount; ++ch) BufferCopy(data->GetChannel(ch) + i * kRecordingChunkSize, mRecordChunks[i]->GetChannel(ch), samplesToCopy); } } return sample; } void MultitrackRecorderTrack::Clear() { for (auto* recordChunk : mRecordChunks) delete recordChunk; mRecordChunks.clear(); mRecordingLength = 0; } void MultitrackRecorderTrack::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void MultitrackRecorderTrack::CheckboxUpdated(Checkbox* checkbox, double time) { } void MultitrackRecorderTrack::ButtonClicked(ClickButton* button, double time) { if (button == mDeleteButton) mRecorder->RemoveTrack(this); } void MultitrackRecorderTrack::LoadLayout(const ofxJSONElement& moduleInfo) { SetUpFromSaveData(); } void MultitrackRecorderTrack::SetUpFromSaveData() { } void MultitrackRecorderTrack::GetModuleDimensions(float& width, float& height) { if (mRecorder) { float parentWidth, parentHeight; mRecorder->GetDimensions(parentWidth, parentHeight); width = parentWidth - 15; height = 95; } else { width = 10; height = 10; } } ```
/content/code_sandbox/Source/MultitrackRecorder.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
3,134
```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 **/ // // DelayEffect.cpp // modularSynth // // Created by Ryan Challinor on 11/25/12. // // #include "DelayEffect.h" #include "SynthGlobals.h" #include "Transport.h" #include "Profiler.h" #include "UIControlMacros.h" #include "ModularSynth.h" #include "juce_core/juce_core.h" DelayEffect::DelayEffect() : mDelayBuffer(DELAY_BUFFER_SIZE) { } void DelayEffect::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); FLOATSLIDER(mDelaySlider, "delay", &mDelay, GetMinDelayMs(), 1000); FLOATSLIDER(mFeedbackSlider, "amount", &mFeedback, 0, 1); DROPDOWN(mIntervalSelector, "interval", (int*)(&mInterval), 45); UIBLOCK_SHIFTRIGHT(); CHECKBOX(mShortTimeCheckbox, "short", &mShortTime); UIBLOCK_NEWLINE(); CHECKBOX(mDryCheckbox, "dry", &mDry); UIBLOCK_SHIFTRIGHT(); CHECKBOX(mEchoCheckbox, "feedback", &mEcho); UIBLOCK_NEWLINE(); CHECKBOX(mAcceptInputCheckbox, "input", &mAcceptInput); UIBLOCK_SHIFTRIGHT(); CHECKBOX(mInvertCheckbox, "invert", &mInvert); ENDUIBLOCK(mWidth, mHeight); mIntervalSelector->AddLabel("2", kInterval_2); mIntervalSelector->AddLabel("1n", kInterval_1n); mIntervalSelector->AddLabel("2n", kInterval_2n); mIntervalSelector->AddLabel("4n", kInterval_4n); mIntervalSelector->AddLabel("8nd", kInterval_8nd); mIntervalSelector->AddLabel("8n", kInterval_8n); mIntervalSelector->AddLabel("16nd", kInterval_16nd); mIntervalSelector->AddLabel("16n", kInterval_16n); mIntervalSelector->AddLabel("32n", kInterval_32n); } void DelayEffect::ProcessAudio(double time, ChannelBuffer* buffer) { PROFILER(DelayEffect); if (!mEnabled) return; float bufferSize = buffer->BufferSize(); mDelayBuffer.SetNumChannels(buffer->NumActiveChannels()); if (mInterval != kInterval_None) { mDelay = TheTransport->GetDuration(mInterval) + .1f; //+1 to avoid perfect sample collision mDelayRamp.Start(time, mDelay, time + 10); } mAmountRamp.Start(time, mFeedback, time + 3); for (int i = 0; i < bufferSize; ++i) { mFeedback = mAmountRamp.Value(time); ComputeSliders(i); float delay = MAX(mDelayRamp.Value(time), GetMinDelayMs()); float delaySamps = delay / gInvSampleRateMs; if (mFeedbackModuleMode) delaySamps -= gBufferSize; delaySamps = ofClamp(delaySamps, 0.1f, DELAY_BUFFER_SIZE - 2); int sampsAgoA = int(delaySamps); int sampsAgoB = sampsAgoA + 1; for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) { float sample = mDelayBuffer.GetSample(sampsAgoA, ch); float nextSample = mDelayBuffer.GetSample(sampsAgoB, ch); float a = delaySamps - sampsAgoA; float delayedSample = (1 - a) * sample + a * nextSample; //interpolate float in = buffer->GetChannel(ch)[i]; if (!mEcho && mAcceptInput) //single delay, no continuous feedback so do it pre mDelayBuffer.Write(buffer->GetChannel(ch)[i], ch); float delayInput = delayedSample * mFeedback * (mInvert ? -1 : 1); JUCE_UNDENORMALISE(delayInput); if (!std::isnan(delayInput)) buffer->GetChannel(ch)[i] += delayInput; if (mEcho && mAcceptInput) //continuous feedback so do it post mDelayBuffer.Write(buffer->GetChannel(ch)[i], ch); if (!mAcceptInput) mDelayBuffer.Write(delayInput, ch); if (!mDry) buffer->GetChannel(ch)[i] -= in; } time += gInvSampleRateMs; } } void DelayEffect::DrawModule() { if (!mEnabled) return; mDelaySlider->Draw(); mFeedbackSlider->Draw(); mIntervalSelector->Draw(); mShortTimeCheckbox->Draw(); mDryCheckbox->Draw(); mEchoCheckbox->Draw(); mAcceptInputCheckbox->Draw(); mInvertCheckbox->Draw(); } float DelayEffect::GetEffectAmount() { if (!mEnabled || !mAcceptInput) return 0; return mFeedback; } void DelayEffect::SetDelay(float delay) { mDelay = delay; mDelayRamp.Start(gTime, mDelay, gTime + 10); mInterval = kInterval_None; } void DelayEffect::SetShortMode(bool on) { mShortTime = on; mDelaySlider->SetExtents(GetMinDelayMs(), mShortTime ? 20 : 1000); } void DelayEffect::SetFeedbackModuleMode() { mFeedbackModuleMode = true; mDry = false; mEcho = false; mInvert = true; SetShortMode(true); SetDelay(20); mDryCheckbox->SetShowing(false); mEchoCheckbox->SetShowing(false); mAcceptInputCheckbox->SetPosition(mAcceptInputCheckbox->GetPosition(true).x, mAcceptInputCheckbox->GetPosition(true).y - 17); mInvertCheckbox->SetPosition(mInvertCheckbox->GetPosition(true).x, mInvertCheckbox->GetPosition(true).y - 17); mHeight -= 17; } float DelayEffect::GetMinDelayMs() const { if (mFeedbackModuleMode) return (gBufferSize + 1) * gInvSampleRateMs; return .1f; } void DelayEffect::SetEnabled(bool enabled) { mEnabled = enabled; if (!enabled) mDelayBuffer.ClearBuffer(); } void DelayEffect::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mShortTimeCheckbox) SetShortMode(mShortTime); if (checkbox == mEnabledCheckbox) { if (!mEnabled) mDelayBuffer.ClearBuffer(); } } void DelayEffect::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mDelaySlider) { mInterval = kInterval_None; mDelayRamp.Start(time, mDelay, time + 30); } } void DelayEffect::DropdownUpdated(DropdownList* list, int oldVal, double time) { } void DelayEffect::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); mDelayBuffer.SaveState(out); } void DelayEffect::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); mDelayBuffer.LoadState(in); } ```
/content/code_sandbox/Source/DelayEffect.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,752
```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 **/ /* ============================================================================== PulseButton.cpp Created: 20 Jun 2020 2:46:02pm Author: Ryan Challinor ============================================================================== */ #include "PulseButton.h" #include "SynthGlobals.h" #include "UIControlMacros.h" #include "Transport.h" PulseButton::PulseButton() { } PulseButton::~PulseButton() { } void PulseButton::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); BUTTON(mButton, "pulse"); ENDUIBLOCK(mWidth, mHeight); } void PulseButton::DrawModule() { if (Minimized() || IsVisible() == false) return; mButton->Draw(); } void PulseButton::ButtonClicked(ClickButton* button, double time) { if (button == mButton) { double scheduledTime = NextBufferTime(true); if (mForceImmediate) scheduledTime = time; DispatchPulse(GetPatchCableSource(), scheduledTime, 1, 0); } } void PulseButton::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadBool("force_immediate", moduleInfo); SetUpFromSaveData(); } void PulseButton::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); mForceImmediate = mModuleSaveData.GetBool("force_immediate"); } ```
/content/code_sandbox/Source/PulseButton.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
417
```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 **/ // // IPollable.h // modularSynth // // Created by Ryan Challinor on 11/2/13. // // #pragma once class IPollable { public: virtual ~IPollable() {} virtual void Poll() {} }; ```
/content/code_sandbox/Source/IPollable.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
153
```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 **/ // // Razor.h // modularSynth // // Created by Ryan Challinor on 12/3/12. // // #pragma once #include <iostream> #include "IAudioSource.h" #include "INoteReceiver.h" #include "ADSR.h" #include "IDrawableModule.h" #include "Checkbox.h" #include "Slider.h" #include "ClickButton.h" #define NUM_PARTIALS 320 #define VIZ_WIDTH 1000 #define RAZOR_HISTORY 100 #define NUM_BUMPS 3 #define NUM_AMP_SLIDERS 16 struct RazorBump { float mFreq{ 100 }; float mAmt{ 0 }; float mDecay{ .005 }; }; class Razor : public IAudioSource, public INoteReceiver, public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public IButtonListener { public: Razor(); ~Razor(); static IDrawableModule* Create() { return new Razor(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return false; } void CreateUIControls() override; //IAudioSource void Process(double time) override; void SetEnabled(bool enabled) 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 {} void CheckboxUpdated(Checkbox* checkbox, double time) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override; void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; void ButtonClicked(ClickButton* button, double time) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: float SinSample(float phase); //phase 0-512 void CalcAmp(); void DrawViz(); //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& w, float& h) override { w = 1020; h = 420; } float mVol{ .05 }; float mPhase{ 0 }; ::ADSR mAdsr[NUM_PARTIALS]{}; float mAmp[NUM_PARTIALS]{}; float mPhases[NUM_PARTIALS]{}; float mDetune[NUM_PARTIALS]{}; int mPitch{ -1 }; int mUseNumPartials{ NUM_PARTIALS }; IntSlider* mNumPartialsSlider{ nullptr }; RazorBump mBumps[NUM_BUMPS]; FloatSlider* mBumpAmpSlider{ nullptr }; FloatSlider* mBumpAmpAmtSlider{ nullptr }; FloatSlider* mBumpAmpDecaySlider{ nullptr }; FloatSlider* mBumpAmpSlider2{ nullptr }; FloatSlider* mBumpAmpAmtSlider2{ nullptr }; FloatSlider* mBumpAmpDecaySlider2{ nullptr }; FloatSlider* mBumpAmpSlider3{ nullptr }; FloatSlider* mBumpAmpAmtSlider3{ nullptr }; FloatSlider* mBumpAmpDecaySlider3{ nullptr }; FloatSlider* mASlider{ nullptr }; FloatSlider* mDSlider{ nullptr }; FloatSlider* mSSlider{ nullptr }; FloatSlider* mRSlider{ nullptr }; int mHarmonicSelector{ 1 }; IntSlider* mHarmonicSelectorSlider{ nullptr }; float mPowFalloff{ 1 }; FloatSlider* mPowFalloffSlider{ nullptr }; int mNegHarmonics{ 0 }; IntSlider* mNegHarmonicsSlider{ nullptr }; float mHarshnessCut{ 0 }; FloatSlider* mHarshnessCutSlider{ nullptr }; bool mManualControl{ false }; Checkbox* mManualControlCheckbox{ nullptr }; FloatSlider* mAmpSliders[NUM_AMP_SLIDERS]{ nullptr }; FloatSlider* mDetuneSliders[NUM_AMP_SLIDERS]{ nullptr }; ClickButton* mResetDetuneButton{ nullptr }; float mA{ 1 }; float mD{ 0 }; float mS{ 1 }; float mR{ 1 }; ModulationChain* mPitchBend{ nullptr }; ModulationChain* mModWheel{ nullptr }; ModulationChain* mPressure{ nullptr }; float mPeakHistory[RAZOR_HISTORY][VIZ_WIDTH + 1]{}; int mHistoryPtr{ 0 }; }; ```
/content/code_sandbox/Source/Razor.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,147
```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 **/ /* ============================================================================== PulseDelayer.h Created: 15 Feb 2020 2:53:22pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "IPulseReceiver.h" #include "Checkbox.h" #include "Slider.h" #include "Transport.h" class PulseDelayer : public IDrawableModule, public IPulseSource, public IPulseReceiver, public IFloatSliderListener, public IAudioPoller { public: PulseDelayer(); ~PulseDelayer(); static IDrawableModule* Create() { return new PulseDelayer(); } 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 OnTransportAdvanced(float amount) 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 mEnabled; } private: struct PulseInfo { float mVelocity{ 0 }; int mFlags{ 0 }; double mTriggerTime{ 0 }; }; //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = 108; height = 22; } float mDelay{ .25 }; FloatSlider* mDelaySlider{ nullptr }; float mLastPulseTime{ 0 }; static const int kQueueSize = 50; PulseInfo mInputPulses[kQueueSize]{}; int mConsumeIndex{ 0 }; int mAppendIndex{ 0 }; }; ```
/content/code_sandbox/Source/PulseDelayer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
557
```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 **/ // // LoopStorer.cpp // Bespoke // // Created by Ryan Challinor on 1/22/15. // // #include "LoopStorer.h" #include "IAudioReceiver.h" #include "Sample.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Looper.h" #include "FillSaveDropdown.h" #include "PatchCableSource.h" #include "ChannelBuffer.h" LoopStorer::LoopStorer() { } void LoopStorer::Init() { IDrawableModule::Init(); TheTransport->AddListener(this, kInterval_None, OffsetInfo(0, true), false); } void LoopStorer::CreateUIControls() { IDrawableModule::CreateUIControls(); mRewriteToSelectionCheckbox = new Checkbox(this, "rewrite", 4, 2, &mRewriteToSelection); mQuantizationDropdown = new DropdownList(this, "quantization", 135, 2, ((int*)&mQuantization)); mClearButton = new ClickButton(this, "clear", 70, 2); mQuantizationDropdown->AddLabel("none", kInterval_None); mQuantizationDropdown->AddLabel("4n", kInterval_4n); mQuantizationDropdown->AddLabel("1n", kInterval_1n); mLooperCable = new PatchCableSource(this, kConnectionType_Special); mLooperCable->AddTypeFilter("looper"); AddPatchCableSource(mLooperCable); } LoopStorer::~LoopStorer() { for (int i = 0; i < mSamples.size(); ++i) delete mSamples[i]; TheTransport->RemoveListener(this); } void LoopStorer::Poll() { if (mLooper == nullptr) return; assert(mSamples[0]->mBuffer != mSamples[1]->mBuffer); for (int i = 0; i < mSamples.size(); ++i) mSamples[i]->mIsCurrentBuffer = (i == mCurrentBufferIdx); if (mIsSwapping) { int loopLength; ChannelBuffer* buffer = mLooper->GetLoopBuffer(loopLength); if (buffer == mSamples[mCurrentBufferIdx]->mBuffer) //finished swap mIsSwapping = false; } if (!mIsSwapping) { mSwapMutex.lock(); int loopLength; mSamples[mCurrentBufferIdx]->mBuffer = mLooper->GetLoopBuffer(loopLength); mSamples[mCurrentBufferIdx]->mNumBars = mLooper->GetNumBars(); mSamples[mCurrentBufferIdx]->mBufferLength = loopLength; mSwapMutex.unlock(); } assert(mSamples[0]->mBuffer != mSamples[1]->mBuffer); } void LoopStorer::DrawModule() { if (Minimized() || IsVisible() == false) return; mRewriteToSelectionCheckbox->Draw(); mQuantizationDropdown->Draw(); mClearButton->Draw(); mSwapMutex.lock(); mLoadMutex.lock(); assert(mSamples[0]->mBuffer != mSamples[1]->mBuffer); for (int i = 0; i < mSamples.size(); ++i) mSamples[i]->Draw(); assert(mSamples[0]->mBuffer != mSamples[1]->mBuffer); mLoadMutex.unlock(); mSwapMutex.unlock(); } void LoopStorer::PostRepatch(PatchCableSource* cableSource, bool fromUserClick) { mLooper = dynamic_cast<Looper*>(cableSource->GetTarget()); } int LoopStorer::GetRowY(int idx) { return 20 + idx * 40; } void LoopStorer::OnTimeEvent(double time) { if (mQueuedSwapBufferIdx != -1) { SwapBuffer(mQueuedSwapBufferIdx); mQueuedSwapBufferIdx = -1; } } void LoopStorer::SwapBuffer(int swapToIdx) { if (mLooper == nullptr) return; mSwapMutex.lock(); assert(mSamples[0]->mBuffer != mSamples[1]->mBuffer); //TODO(Ryan) make loopstorer actually use ChannelBuffers //mLooper->SetLoopBuffer(mSamples[swapToIdx]->mBuffer); if (mRewriteToSelection) { mSamples[swapToIdx]->mNumBars = mLooper->GetRecorderNumBars(); mLooper->Rewrite(); mRewriteToSelection = false; } else { mLooper->SetNumBars(mSamples[swapToIdx]->mNumBars); } mCurrentBufferIdx = swapToIdx; mIsSwapping = true; assert(mSamples[0]->mBuffer != mSamples[1]->mBuffer); mSwapMutex.unlock(); } void LoopStorer::DropdownClicked(DropdownList* list) { } void LoopStorer::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mQuantizationDropdown) { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) transportListenerInfo->mInterval = mQuantization; } } void LoopStorer::ButtonClicked(ClickButton* button, double time) { if (button == mClearButton) { mSwapMutex.lock(); if (mLooper) mLooper->LockBufferMutex(); for (int i = 0; i < mSamples.size(); ++i) { mSamples[i]->mBuffer->Clear(); } if (mLooper) mLooper->UnlockBufferMutex(); mSwapMutex.unlock(); } } void LoopStorer::CheckboxUpdated(Checkbox* checkbox, double time) { for (int i = 0; i < mSamples.size(); ++i) { if (checkbox == mSamples[i]->mSelectCheckbox) { if (mQuantization == kInterval_None) SwapBuffer(i); else mQueuedSwapBufferIdx = i; } } } void LoopStorer::GetModuleDimensions(float& width, float& height) { width = 180; height = GetRowY((int)mSamples.size()); } void LoopStorer::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void LoopStorer::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void LoopStorer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("looper", moduleInfo, "", FillDropdown<Looper*>); mModuleSaveData.LoadInt("numclips", moduleInfo, 4, 1, 16); mModuleSaveData.LoadEnum<NoteInterval>("quantization", moduleInfo, kInterval_None, mQuantizationDropdown); SetUpFromSaveData(); } void LoopStorer::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["looper"] = mLooper ? mLooper->Name() : ""; } void LoopStorer::SetUpFromSaveData() { mLooperCable->SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("looper"), false)); for (int i = 0; i < mSamples.size(); ++i) delete mSamples[i]; mSamples.resize(mModuleSaveData.GetInt("numclips")); for (int i = 0; i < mSamples.size(); ++i) { mSamples[i] = new SampleData(); mSamples[i]->Init(this, i); } mQuantization = mModuleSaveData.GetEnum<NoteInterval>("quantization"); TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) transportListenerInfo->mInterval = mQuantization; } void LoopStorer::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); IDrawableModule::SaveState(out); out << mCurrentBufferIdx; for (auto* sampleData : mSamples) { if (!sampleData->mIsCurrentBuffer) { out << sampleData->mNumBars; out << sampleData->mBufferLength; if (sampleData->mBufferLength != -1) sampleData->mBuffer->Save(out, sampleData->mBufferLength); } } } void LoopStorer::LoadState(FileStreamIn& in, int rev) { IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); in >> mCurrentBufferIdx; mQueuedSwapBufferIdx = -1; for (int i = 0; i < mSamples.size(); ++i) mSamples[i]->mIsCurrentBuffer = (i == mCurrentBufferIdx); if (mCurrentBufferIdx != 0) { mSamples[0]->mBuffer = mSamples[mCurrentBufferIdx]->mBuffer; int loopLength; mSamples[mCurrentBufferIdx]->mBuffer = mLooper->GetLoopBuffer(loopLength); mSamples[mCurrentBufferIdx]->mNumBars = mLooper->GetNumBars(); mSamples[mCurrentBufferIdx]->mBufferLength = loopLength; } mLoadMutex.lock(); for (auto* sampleData : mSamples) { if (!sampleData->mIsCurrentBuffer) { in >> sampleData->mNumBars; in >> sampleData->mBufferLength; if (sampleData->mBufferLength != -1) { int readLength; sampleData->mBuffer->Load(in, readLength, ChannelBuffer::LoadMode::kAnyBufferSize); assert(sampleData->mBufferLength == sampleData->mBuffer->BufferSize()); } } } mLoadMutex.unlock(); } LoopStorer::SampleData::SampleData() { } LoopStorer::SampleData::~SampleData() { if (mIsCurrentBuffer == false) delete mBuffer; if (mSelectCheckbox) { mLoopStorer->RemoveUIControl(mSelectCheckbox); mSelectCheckbox->Delete(); } } void LoopStorer::SampleData::Init(LoopStorer* storer, int index) { mLoopStorer = storer; mIndex = index; if (mIsCurrentBuffer == false) delete mBuffer; if (index == 0) //we're the first one, grab our buffer from the looper { Looper* looper = storer->GetLooper(); if (looper) { mBuffer = looper->GetLoopBuffer(mBufferLength); mNumBars = looper->GetNumBars(); } mIsCurrentBuffer = true; } else { mBuffer = new ChannelBuffer(MAX_BUFFER_SIZE); mNumBars = 1; mIsCurrentBuffer = false; } if (mSelectCheckbox) { storer->RemoveUIControl(mSelectCheckbox); mSelectCheckbox->Delete(); } std::string indexStr = ofToString(index + 1); int y = storer->GetRowY(index); mSelectCheckbox = new Checkbox(storer, ("select " + indexStr).c_str(), 110, y + 20, &mIsCurrentBuffer); } void LoopStorer::SampleData::Draw() { ofPushMatrix(); ofTranslate(5, mLoopStorer->GetRowY(mIndex)); ChannelBuffer* buffer = mBuffer; int bufferLength = mBufferLength; bool useLooper = mIsCurrentBuffer && mLoopStorer && mLoopStorer->GetLooper(); if (useLooper) { mLoopStorer->GetLooper()->LockBufferMutex(); buffer = mLoopStorer->GetLooper()->GetLoopBuffer(bufferLength); //make sure we have the latest and greatest } DrawAudioBuffer(100, 36, buffer, 0, bufferLength, -1); if (useLooper) mLoopStorer->GetLooper()->UnlockBufferMutex(); DrawTextNormal(ofToString(mNumBars), 4, 12); if (mLoopStorer->GetQueuedBufferIdx() == mIndex) { ofPushStyle(); ofSetColor(255, 100, 0); ofFill(); ofRect(107, 24, 8, 8); ofPopStyle(); } ofPopMatrix(); mSelectCheckbox->Draw(); } ```
/content/code_sandbox/Source/LoopStorer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,847
```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 **/ // // ModuleFactory.cpp // modularSynth // // Created by Ryan Challinor on 1/20/14. // // #if BESPOKE_MAC #include <CoreFoundation/CoreFoundation.h> #endif #include "ModuleFactory.h" #include "LaunchpadKeyboard.h" #include "DrumPlayer.h" #include "EffectChain.h" #include "LooperRecorder.h" #include "Chorder.h" #include "Arpeggiator.h" #include "Razor.h" #include "Monophonify.h" #include "StepSequencer.h" #include "InputChannel.h" #include "OutputChannel.h" #include "WaveformViewer.h" #include "FMSynth.h" #include "MidiController.h" #include "PSMoveController.h" #include "Autotalent.h" #include "ScaleDetect.h" #include "KarplusStrong.h" #include "WhiteKeys.h" #include "RingModulator.h" #include "Neighborhooder.h" #include "Polyrhythms.h" #include "Looper.h" #include "Rewriter.h" #include "Metronome.h" #include "NoteRouter.h" #include "NoteLooper.h" #include "AudioRouter.h" #include "LaunchpadNoteDisplayer.h" #include "Vocoder.h" #include "VocoderCarrierInput.h" #include "FreqDomainBoilerplate.h" #include "FFTtoAdditive.h" #include "FreqDelay.h" #include "VelocitySetter.h" #include "NoteSinger.h" #include "NoteOctaver.h" #include "SampleFinder.h" #include "FourOnTheFloor.h" #include "Amplifier.h" #include "Snapshots.h" #include "LFOController.h" #include "NoteStepSequencer.h" #include "BeatBloks.h" #include "Producer.h" #include "ChaosEngine.h" #include "SingleOscillator.h" #include "BandVocoder.h" #include "Capo.h" #include "ControlTactileFeedback.h" //#include "Eigenharp.h" #include "Beats.h" #include "Sampler.h" #include "SliderSequencer.h" #include "MultibandCompressor.h" #include "ControllingSong.h" #include "PanicButton.h" #include "VelocityStepSequencer.h" #include "SustainPedal.h" #include "MultitrackRecorder.h" //#include "MidiPlayer.h" #include "SamplerGrid.h" #include "SignalGenerator.h" #include "Lissajous.h" #include "DebugAudioSource.h" #include "TimerDisplay.h" #include "DrumSynth.h" //#include "EigenChorder.h" #include "PitchBender.h" //#include "EigenharpNoteSource.h" #include "FollowingSong.h" #include "SeaOfGrain.h" #include "VinylTempoControl.h" #include "NoteFlusher.h" #include "FilterViz.h" #include "NoteCanvas.h" #include "SlowLayers.h" #include "ClipLauncher.h" #include "LoopStorer.h" #include "CommentDisplay.h" #include "ComboGridController.h" #include "StutterControl.h" #include "CircleSequencer.h" #ifdef BESPOKE_MAC #include "KompleteKontrol.h" #endif #include "MidiOutput.h" #include "FloatSliderLFOControl.h" #include "NoteDisplayer.h" #include "AudioMeter.h" #include "NoteSustain.h" #include "PitchChorus.h" #include "SampleCanvas.h" #include "ControlSequencer.h" #include "PitchSetter.h" #include "NoteFilter.h" #include "RandomNoteGenerator.h" #include "NoteToFreq.h" #include "MacroSlider.h" #include "NoteVibrato.h" #include "ModulationVisualizer.h" #include "PitchDive.h" #include "EventCanvas.h" #include "NoteCreator.h" #include "ValueSetter.h" #include "PreviousNote.h" #include "PressureToVibrato.h" #include "ModwheelToVibrato.h" #include "Pressure.h" #include "ModWheel.h" #include "PressureToModwheel.h" #include "ModwheelToPressure.h" #include "VSTPlugin.h" #include "FeedbackModule.h" #include "NoteToMs.h" #include "Selector.h" #include "GroupControl.h" #include "CurveLooper.h" #include "ScaleDegree.h" #include "NoteChainNode.h" #include "NoteDelayer.h" #include "TimelineControl.h" #include "VelocityScaler.h" #include "KeyboardDisplay.h" #include "Ramper.h" #include "NoteGate.h" #include "Prefab.h" #include "NoteHumanizer.h" #include "VolcaBeatsControl.h" #include "RadioSequencer.h" #include "TakeRecorder.h" #include "Splitter.h" #include "Panner.h" #include "SamplePlayer.h" #include "AudioSend.h" #include "EnvelopeEditor.h" #include "EnvelopeModulator.h" #include "AudioToCV.h" #include "ModulatorAdd.h" #include "ModulatorAddCentered.h" #include "PitchToCV.h" #include "VelocityToCV.h" #include "PressureToCV.h" #include "ModWheelToCV.h" #include "ModulatorMult.h" #include "ModulatorCurve.h" #include "ModulatorSmoother.h" #include "NotePanner.h" #include "PitchPanner.h" #include "NotePanAlternator.h" #include "ChordDisplayer.h" #include "NoteStrummer.h" #include "PitchToSpeed.h" #include "NoteToPulse.h" #include "OSCOutput.h" #include "AudioLevelToCV.h" #include "Pulser.h" #include "PulseSequence.h" #include "LinnstrumentControl.h" #include "MultitapDelay.h" #include "MidiCapturer.h" #include "Inverter.h" #include "SpectralDisplay.h" #include "DCOffset.h" #include "SignalClamp.h" #include "Waveshaper.h" #include "ModulatorSubtract.h" #include "NoteHocket.h" #include "NoteRangeFilter.h" #include "NoteChance.h" #include "PulseChance.h" #include "PulseDelayer.h" #include "NotePanRandom.h" #include "PulseGate.h" #include "PulseHocket.h" #include "Push2Control.h" #include "PulseTrain.h" #include "NoteLatch.h" #include "ScriptModule.h" #include "ScriptStatus.h" #include "ModulatorGravity.h" #include "NoteStreamDisplay.h" #include "PulseButton.h" #include "GridModule.h" #include "FubbleModule.h" #include "GlobalControls.h" #include "ValueStream.h" #include "EQModule.h" #include "SampleCapturer.h" #include "NoteQuantizer.h" #include "PlaySequencer.h" #include "UnstablePitch.h" #include "UnstableModWheel.h" #include "UnstablePressure.h" #include "ChordHolder.h" #include "LooperGranulator.h" #include "AudioToPulse.h" #include "NoteCounter.h" #include "PitchRemap.h" #include "ModulatorExpression.h" #include "SampleBrowser.h" #include "TransposeFrom.h" #include "NoteStepper.h" #include "M185Sequencer.h" #include "ModulatorAccum.h" #include "GridSliders.h" #include "NoteRatchet.h" #include "NoteSorter.h" #include "MPESmoother.h" #include "MidiControlChange.h" #include "MPETweaker.h" #include "NoteExpressionRouter.h" #include "NoteToggle.h" #include "NoteTable.h" #include "AbletonLink.h" #include "MidiClockIn.h" #include "MidiClockOut.h" #include "VelocityToChance.h" #include "NoteEcho.h" #include "VelocityCurve.h" #include "BoundsToPulse.h" #include "SongBuilder.h" #include "PulseFlag.h" #include "PulseDisplayer.h" #include "BufferShuffler.h" #include "PitchToValue.h" #include "RhythmSequencer.h" #include "DotSequencer.h" #include "VoiceSetter.h" #include "LabelDisplay.h" #include "ControlRecorder.h" #include "EuclideanSequencer.h" #include "SaveStateLoader.h" #include <juce_core/juce_core.h> #include "PulseRouter.h" #define REGISTER(class, name, type) Register(#name, &(class ::Create), &(class ::CanCreate), type, false, false, class ::AcceptsAudio(), class ::AcceptsNotes(), class ::AcceptsPulses()); #define REGISTER_HIDDEN(class, name, type) Register(#name, &(class ::Create), &(class ::CanCreate), type, true, false, class ::AcceptsAudio(), class ::AcceptsNotes(), class ::AcceptsPulses()); #define REGISTER_EXPERIMENTAL(class, name, type) Register(#name, &(class ::Create), &(class ::CanCreate), type, false, true, class ::AcceptsAudio(), class ::AcceptsNotes(), class ::AcceptsPulses()); ModuleFactory::ModuleFactory() { REGISTER(LooperRecorder, looperrecorder, kModuleCategory_Audio); REGISTER(WaveformViewer, waveformviewer, kModuleCategory_Audio); REGISTER(EffectChain, effectchain, kModuleCategory_Audio); REGISTER(DrumPlayer, drumplayer, kModuleCategory_Synth); REGISTER(Chorder, chorder, kModuleCategory_Note); REGISTER(Arpeggiator, arpeggiator, kModuleCategory_Note); REGISTER(Monophonify, portamento, kModuleCategory_Note); REGISTER(StepSequencer, drumsequencer, kModuleCategory_Instrument); REGISTER(LaunchpadKeyboard, gridkeyboard, kModuleCategory_Instrument); REGISTER(FMSynth, fmsynth, kModuleCategory_Synth); REGISTER(MidiController, midicontroller, kModuleCategory_Instrument); REGISTER(ScaleDetect, scaledetect, kModuleCategory_Note); REGISTER(KarplusStrong, karplusstrong, kModuleCategory_Synth); REGISTER(WhiteKeys, whitekeys, kModuleCategory_Note); //REGISTER(Kicker, kicker, kModuleCategory_Note); REGISTER(RingModulator, ringmodulator, kModuleCategory_Audio); REGISTER(Neighborhooder, notewrap, kModuleCategory_Note); REGISTER(Polyrhythms, polyrhythms, kModuleCategory_Instrument); REGISTER(Looper, looper, kModuleCategory_Audio); REGISTER(Rewriter, looperrewriter, kModuleCategory_Audio); REGISTER(Metronome, metronome, kModuleCategory_Synth); REGISTER(NoteRouter, noterouter, kModuleCategory_Note); REGISTER(AudioRouter, audiorouter, kModuleCategory_Audio); REGISTER(LaunchpadNoteDisplayer, gridnotedisplayer, kModuleCategory_Note); REGISTER(Vocoder, fftvocoder, kModuleCategory_Audio); REGISTER(FreqDelay, freqdelay, kModuleCategory_Audio); REGISTER(VelocitySetter, velocitysetter, kModuleCategory_Note); REGISTER(NoteSinger, notesinger, kModuleCategory_Instrument); REGISTER(NoteOctaver, noteoctaver, kModuleCategory_Note); REGISTER(FourOnTheFloor, fouronthefloor, kModuleCategory_Instrument); REGISTER(Amplifier, gain, kModuleCategory_Audio); REGISTER(Snapshots, snapshots, kModuleCategory_Other); REGISTER(NoteStepSequencer, notesequencer, kModuleCategory_Instrument); REGISTER(SingleOscillator, oscillator, kModuleCategory_Synth); REGISTER(BandVocoder, vocoder, kModuleCategory_Audio); REGISTER(Capo, capo, kModuleCategory_Note); REGISTER(VocoderCarrierInput, vocodercarrier, kModuleCategory_Audio); REGISTER(InputChannel, input, kModuleCategory_Audio); REGISTER(OutputChannel, output, kModuleCategory_Audio); //REGISTER(Eigenharp, eigenharp, kModuleCategory_Synth); REGISTER(Beats, beats, kModuleCategory_Synth); REGISTER(Sampler, sampler, kModuleCategory_Synth); //REGISTER(NoteTransformer, notetransformer, kModuleCategory_Note); REGISTER(SliderSequencer, slidersequencer, kModuleCategory_Instrument); REGISTER(VelocityStepSequencer, velocitystepsequencer, kModuleCategory_Note); REGISTER(SustainPedal, sustainpedal, kModuleCategory_Note); REGISTER(SamplerGrid, samplergrid, kModuleCategory_Audio); REGISTER(SignalGenerator, signalgenerator, kModuleCategory_Synth); REGISTER(Lissajous, lissajous, kModuleCategory_Audio); REGISTER(TimerDisplay, timerdisplay, kModuleCategory_Other); REGISTER(DrumSynth, drumsynth, kModuleCategory_Synth); //REGISTER(EigenChorder, eigenchorder, kModuleCategory_Note); REGISTER(PitchBender, pitchbender, kModuleCategory_Note); //REGISTER(EigenharpNoteSource, eigenharpnotesource, kModuleCategory_Instrument); REGISTER(VinylTempoControl, vinylcontrol, kModuleCategory_Modulator); REGISTER(NoteFlusher, noteflusher, kModuleCategory_Note); REGISTER(NoteCanvas, notecanvas, kModuleCategory_Instrument); REGISTER(CommentDisplay, comment, kModuleCategory_Other); REGISTER(LabelDisplay, label, kModuleCategory_Other); REGISTER(StutterControl, stutter, kModuleCategory_Audio); REGISTER(CircleSequencer, circlesequencer, kModuleCategory_Instrument); REGISTER(MidiOutputModule, midioutput, kModuleCategory_Note); REGISTER(NoteDisplayer, notedisplayer, kModuleCategory_Note); REGISTER(AudioMeter, audiometer, kModuleCategory_Audio); REGISTER(NoteSustain, noteduration, kModuleCategory_Note); REGISTER(ControlSequencer, controlsequencer, kModuleCategory_Modulator); REGISTER(PitchSetter, pitchsetter, kModuleCategory_Note); REGISTER(NoteFilter, notefilter, kModuleCategory_Note); REGISTER(PulseRouter, pulserouter, kModuleCategory_Pulse); REGISTER(RandomNoteGenerator, randomnote, kModuleCategory_Instrument); REGISTER(NoteToFreq, notetofreq, kModuleCategory_Modulator); REGISTER(MacroSlider, macroslider, kModuleCategory_Modulator); REGISTER(NoteVibrato, vibrato, kModuleCategory_Note); REGISTER(ModulationVisualizer, modulationvizualizer, kModuleCategory_Note); REGISTER(PitchDive, pitchdive, kModuleCategory_Note); REGISTER(EventCanvas, eventcanvas, kModuleCategory_Other); REGISTER(NoteCreator, notecreator, kModuleCategory_Instrument); REGISTER(ValueSetter, valuesetter, kModuleCategory_Modulator); REGISTER(PreviousNote, previousnote, kModuleCategory_Note); REGISTER(PressureToVibrato, pressuretovibrato, kModuleCategory_Note); REGISTER(ModwheelToVibrato, modwheeltovibrato, kModuleCategory_Note); REGISTER(Pressure, pressure, kModuleCategory_Note); REGISTER(ModWheel, modwheel, kModuleCategory_Note); REGISTER(PressureToModwheel, pressuretomodwheel, kModuleCategory_Note); REGISTER(ModwheelToPressure, modwheeltopressure, kModuleCategory_Note); REGISTER(FeedbackModule, feedback, kModuleCategory_Audio); REGISTER(NoteToMs, notetoms, kModuleCategory_Modulator); REGISTER(Selector, selector, kModuleCategory_Other); REGISTER(GroupControl, groupcontrol, kModuleCategory_Other); REGISTER(CurveLooper, curvelooper, kModuleCategory_Modulator); REGISTER(ScaleDegree, scaledegree, kModuleCategory_Note); REGISTER(NoteChainNode, notechain, kModuleCategory_Instrument); REGISTER(NoteDelayer, notedelayer, kModuleCategory_Note); REGISTER(VelocityScaler, velocityscaler, kModuleCategory_Note); REGISTER(KeyboardDisplay, keyboarddisplay, kModuleCategory_Instrument); REGISTER(Ramper, ramper, kModuleCategory_Modulator); REGISTER(NoteGate, notegate, kModuleCategory_Note); REGISTER(Prefab, prefab, kModuleCategory_Other); REGISTER(NoteHumanizer, notehumanizer, kModuleCategory_Note); REGISTER(VolcaBeatsControl, volcabeatscontrol, kModuleCategory_Note); REGISTER(RadioSequencer, radiosequencer, kModuleCategory_Other); REGISTER(Splitter, splitter, kModuleCategory_Audio); REGISTER(Panner, panner, kModuleCategory_Audio); REGISTER(SamplePlayer, sampleplayer, kModuleCategory_Synth); REGISTER(AudioSend, send, kModuleCategory_Audio); REGISTER(EnvelopeModulator, envelope, kModuleCategory_Modulator); REGISTER(AudioToCV, audiotocv, kModuleCategory_Modulator); REGISTER(ModulatorAdd, add, kModuleCategory_Modulator); REGISTER(ModulatorAddCentered, addcentered, kModuleCategory_Modulator); REGISTER(ModulatorSubtract, subtract, kModuleCategory_Modulator); REGISTER(PitchToCV, pitchtocv, kModuleCategory_Modulator); REGISTER(VelocityToCV, velocitytocv, kModuleCategory_Modulator); REGISTER(PressureToCV, pressuretocv, kModuleCategory_Modulator); REGISTER(ModWheelToCV, modwheeltocv, kModuleCategory_Modulator); REGISTER(ModulatorMult, mult, kModuleCategory_Modulator); REGISTER(ModulatorCurve, curve, kModuleCategory_Modulator); REGISTER(ModulatorSmoother, smoother, kModuleCategory_Modulator); REGISTER(NotePanner, notepanner, kModuleCategory_Note); REGISTER(PitchPanner, pitchpanner, kModuleCategory_Note); REGISTER(NotePanAlternator, notepanalternator, kModuleCategory_Note); REGISTER(ChordDisplayer, chorddisplayer, kModuleCategory_Note); REGISTER(NoteStrummer, notestrummer, kModuleCategory_Note); REGISTER(SeaOfGrain, seaofgrain, kModuleCategory_Synth); REGISTER(PitchToSpeed, pitchtospeed, kModuleCategory_Modulator); REGISTER(NoteToPulse, notetopulse, kModuleCategory_Pulse); REGISTER(OSCOutput, oscoutput, kModuleCategory_Other); REGISTER(AudioLevelToCV, leveltocv, kModuleCategory_Modulator); REGISTER(Pulser, pulser, kModuleCategory_Pulse); REGISTER(PulseSequence, pulsesequence, kModuleCategory_Pulse); REGISTER(LinnstrumentControl, linnstrumentcontrol, kModuleCategory_Note); REGISTER(MultitapDelay, multitapdelay, kModuleCategory_Audio); REGISTER(Inverter, inverter, kModuleCategory_Audio); REGISTER(SpectralDisplay, spectrum, kModuleCategory_Audio); REGISTER(DCOffset, dcoffset, kModuleCategory_Audio); REGISTER(SignalClamp, signalclamp, kModuleCategory_Audio); REGISTER(Waveshaper, waveshaper, kModuleCategory_Audio); REGISTER(NoteHocket, notehocket, kModuleCategory_Note); REGISTER(NoteRangeFilter, noterangefilter, kModuleCategory_Note); REGISTER(NoteChance, notechance, kModuleCategory_Note); REGISTER(PulseChance, pulsechance, kModuleCategory_Pulse); REGISTER(PulseDelayer, pulsedelayer, kModuleCategory_Pulse); REGISTER(NotePanRandom, notepanrandom, kModuleCategory_Note); REGISTER(PulseGate, pulsegate, kModuleCategory_Pulse); REGISTER(PulseHocket, pulsehocket, kModuleCategory_Pulse); REGISTER(Push2Control, push2control, kModuleCategory_Other); REGISTER(PulseTrain, pulsetrain, kModuleCategory_Pulse); REGISTER(NoteLatch, notelatch, kModuleCategory_Note); REGISTER(ScriptModule, script, kModuleCategory_Other); REGISTER(ScriptStatus, scriptstatus, kModuleCategory_Other); REGISTER(ModulatorGravity, gravity, kModuleCategory_Modulator); REGISTER(NoteStreamDisplay, notestream, kModuleCategory_Note); REGISTER(PulseButton, pulsebutton, kModuleCategory_Pulse); REGISTER(GridModule, grid, kModuleCategory_Other); REGISTER(FubbleModule, fubble, kModuleCategory_Modulator); REGISTER(GlobalControls, globalcontrols, kModuleCategory_Other); REGISTER(ValueStream, valuestream, kModuleCategory_Other); REGISTER(EQModule, eq, kModuleCategory_Audio); REGISTER(SampleCapturer, samplecapturer, kModuleCategory_Audio); REGISTER(NoteQuantizer, quantizer, kModuleCategory_Note); REGISTER(NoteLooper, notelooper, kModuleCategory_Instrument); REGISTER(PlaySequencer, playsequencer, kModuleCategory_Instrument); REGISTER(UnstablePitch, unstablepitch, kModuleCategory_Note); REGISTER(UnstableModWheel, unstablemodwheel, kModuleCategory_Note); REGISTER(UnstablePressure, unstablepressure, kModuleCategory_Note); REGISTER(ChordHolder, chordholder, kModuleCategory_Note); REGISTER(LooperGranulator, loopergranulator, kModuleCategory_Other); REGISTER(AudioToPulse, audiotopulse, kModuleCategory_Pulse); REGISTER(NoteCounter, notecounter, kModuleCategory_Instrument); REGISTER(PitchRemap, pitchremap, kModuleCategory_Note); REGISTER(ModulatorExpression, expression, kModuleCategory_Modulator); REGISTER(SampleCanvas, samplecanvas, kModuleCategory_Synth); REGISTER(SampleBrowser, samplebrowser, kModuleCategory_Other); REGISTER(TransposeFrom, transposefrom, kModuleCategory_Note); REGISTER(NoteStepper, notestepper, kModuleCategory_Note); REGISTER(M185Sequencer, m185sequencer, kModuleCategory_Instrument); REGISTER(ModulatorAccum, accum, kModuleCategory_Modulator); REGISTER(NoteSorter, notesorter, kModuleCategory_Note); REGISTER(NoteRatchet, noteratchet, kModuleCategory_Note); REGISTER(MPESmoother, mpesmoother, kModuleCategory_Note); REGISTER(MidiControlChange, midicc, kModuleCategory_Note); REGISTER(MPETweaker, mpetweaker, kModuleCategory_Note); REGISTER(GridSliders, gridsliders, kModuleCategory_Modulator); REGISTER(MultitrackRecorder, multitrackrecorder, kModuleCategory_Other); REGISTER(NoteExpressionRouter, noteexpression, kModuleCategory_Note); REGISTER(FloatSliderLFOControl, lfo, kModuleCategory_Modulator); REGISTER(NoteToggle, notetoggle, kModuleCategory_Other); REGISTER(NoteTable, notetable, kModuleCategory_Note); REGISTER(AbletonLink, abletonlink, kModuleCategory_Other); REGISTER(MidiClockIn, clockin, kModuleCategory_Other); REGISTER(MidiClockOut, clockout, kModuleCategory_Other); REGISTER(VelocityToChance, velocitytochance, kModuleCategory_Note); REGISTER(NoteEcho, noteecho, kModuleCategory_Note); REGISTER(VelocityCurve, velocitycurve, kModuleCategory_Note); REGISTER(BoundsToPulse, boundstopulse, kModuleCategory_Pulse); REGISTER(SongBuilder, songbuilder, kModuleCategory_Other); REGISTER(TimelineControl, timelinecontrol, kModuleCategory_Other); REGISTER(PulseFlag, pulseflag, kModuleCategory_Pulse); REGISTER(PulseDisplayer, pulsedisplayer, kModuleCategory_Pulse); REGISTER(BufferShuffler, buffershuffler, kModuleCategory_Audio); REGISTER(PitchToValue, pitchtovalue, kModuleCategory_Modulator); REGISTER(RhythmSequencer, rhythmsequencer, kModuleCategory_Note); REGISTER(DotSequencer, dotsequencer, kModuleCategory_Instrument); REGISTER(VoiceSetter, voicesetter, kModuleCategory_Note); REGISTER(ControlRecorder, controlrecorder, kModuleCategory_Modulator); REGISTER(EuclideanSequencer, euclideansequencer, kModuleCategory_Instrument); REGISTER(SaveStateLoader, savestateloader, kModuleCategory_Other); //REGISTER_EXPERIMENTAL(MidiPlayer, midiplayer, kModuleCategory_Instrument); REGISTER_HIDDEN(Autotalent, autotalent, kModuleCategory_Audio); REGISTER_HIDDEN(TakeRecorder, takerecorder, kModuleCategory_Audio); REGISTER_HIDDEN(LoopStorer, loopstorer, kModuleCategory_Other); REGISTER_HIDDEN(PitchChorus, pitchchorus, kModuleCategory_Audio); REGISTER_HIDDEN(ComboGridController, combogrid, kModuleCategory_Other); REGISTER_HIDDEN(VSTPlugin, plugin, kModuleCategory_Synth); REGISTER_HIDDEN(SampleFinder, samplefinder, kModuleCategory_Audio); REGISTER_HIDDEN(Producer, producer, kModuleCategory_Audio); REGISTER_HIDDEN(ChaosEngine, chaosengine, kModuleCategory_Other); REGISTER_HIDDEN(MultibandCompressor, multiband, kModuleCategory_Audio); REGISTER_HIDDEN(ControllingSong, controllingsong, kModuleCategory_Synth); REGISTER_HIDDEN(PanicButton, panicbutton, kModuleCategory_Other); REGISTER_HIDDEN(DebugAudioSource, debugaudiosource, kModuleCategory_Synth); REGISTER_HIDDEN(FollowingSong, followingsong, kModuleCategory_Synth); REGISTER_HIDDEN(BeatBloks, beatbloks, kModuleCategory_Synth); REGISTER_HIDDEN(FilterViz, filterviz, kModuleCategory_Other); REGISTER_HIDDEN(FreqDomainBoilerplate, freqdomainboilerplate, kModuleCategory_Audio); REGISTER_HIDDEN(FFTtoAdditive, ffttoadditive, kModuleCategory_Audio); REGISTER_HIDDEN(SlowLayers, slowlayers, kModuleCategory_Audio); REGISTER_HIDDEN(ClipLauncher, cliplauncher, kModuleCategory_Synth); #ifdef BESPOKE_MAC REGISTER_HIDDEN(KompleteKontrol, kompletekontrol, kModuleCategory_Note); #endif REGISTER_HIDDEN(PSMoveController, psmove, kModuleCategory_Other); REGISTER_HIDDEN(ControlTactileFeedback, controltactilefeedback, kModuleCategory_Synth); REGISTER_HIDDEN(EnvelopeEditor, envelopeeditor, kModuleCategory_Other); REGISTER_HIDDEN(LFOController, lfocontroller, kModuleCategory_Other); //old, probably irrelevant REGISTER_HIDDEN(Razor, razor, kModuleCategory_Synth); REGISTER_HIDDEN(MidiCapturer, midicapturer, kModuleCategory_Note); REGISTER_HIDDEN(ScriptReferenceDisplay, scriptingreference, kModuleCategory_Other); REGISTER_HIDDEN(ScriptWarningPopup, scriptwarning, kModuleCategory_Other); REGISTER_HIDDEN(MultitrackRecorderTrack, multitrackrecordertrack, kModuleCategory_Audio); } void ModuleFactory::Register(std::string type, CreateModuleFn creator, CanCreateModuleFn canCreate, ModuleCategory moduleCategory, bool hidden, bool experimental, bool canReceiveAudio, bool canReceiveNotes, bool canReceivePulses) { ModuleInfo moduleInfo; moduleInfo.mCreatorFn = creator; moduleInfo.mCanCreateFn = canCreate; moduleInfo.mCategory = moduleCategory; moduleInfo.mIsHidden = hidden; moduleInfo.mIsExperimental = experimental; moduleInfo.mCanReceiveAudio = canReceiveAudio; moduleInfo.mCanReceiveNotes = canReceiveNotes; moduleInfo.mCanReceivePulses = canReceivePulses; mFactoryMap[type] = moduleInfo; } IDrawableModule* ModuleFactory::MakeModule(std::string type) { auto moduleInfo = mFactoryMap.find(type); if (moduleInfo != mFactoryMap.end()) { if (moduleInfo->second.mCanCreateFn()) return moduleInfo->second.mCreatorFn(); } return nullptr; } std::vector<ModuleFactory::Spawnable> ModuleFactory::GetSpawnableModules(ModuleCategory moduleCategory) { std::vector<ModuleFactory::Spawnable> modules{}; for (auto iter = mFactoryMap.begin(); iter != mFactoryMap.end(); ++iter) { if (iter->second.mCategory == moduleCategory && (!iter->second.mIsHidden || gShowDevModules)) { ModuleFactory::Spawnable spawnable{}; spawnable.mLabel = iter->first; modules.push_back(spawnable); } } if (moduleCategory == kModuleCategory_Audio) { std::vector<std::string> effects = TheSynth->GetEffectFactory()->GetSpawnableEffects(); for (auto effect : effects) { ModuleFactory::Spawnable spawnable{}; spawnable.mLabel = effect; spawnable.mDecorator = kEffectChainSuffix; spawnable.mSpawnMethod = SpawnMethod::EffectChain; modules.push_back(spawnable); } } std::sort(modules.begin(), modules.end(), Spawnable::CompareAlphabetical); return modules; } namespace { bool CheckHeldKeysMatch(juce::String name, std::string heldKeys, bool continuous) { name = name.toLowerCase(); if (name.isEmpty() || heldKeys.empty()) return false; if (continuous) return name.contains(heldKeys); if (name[0] != heldKeys[0]) return false; int stringPos = 0; int end = name.indexOfChar('.'); if (end == -1) end = name.indexOfChar(' '); if (end == -1) end = name.length() - 1; for (size_t j = 1; j < heldKeys.length(); ++j) { stringPos = name.substring(stringPos + 1, end + 1).indexOfChar(heldKeys[j]); if (stringPos == -1) //couldn't find key in remaining string return false; } return true; } } std::vector<ModuleFactory::Spawnable> ModuleFactory::GetSpawnableModules(std::string keys, bool continuousString) { std::vector<ModuleFactory::Spawnable> modules{}; for (auto iter = mFactoryMap.begin(); iter != mFactoryMap.end(); ++iter) { if ((!iter->second.mIsHidden || gShowDevModules) && CheckHeldKeysMatch(iter->first, keys, continuousString)) { ModuleFactory::Spawnable spawnable{}; spawnable.mLabel = iter->first; modules.push_back(spawnable); } } std::vector<juce::PluginDescription> vsts; VSTLookup::GetAvailableVSTs(vsts); std::vector<juce::PluginDescription> matchingVsts; for (auto& pluginDesc : vsts) { std::string pluginName = pluginDesc.name.toStdString(); if (CheckHeldKeysMatch(pluginName, keys, continuousString)) matchingVsts.push_back(pluginDesc); } const int kMaxQuickspawnVstCount = 10; if ((int)matchingVsts.size() > kMaxQuickspawnVstCount) VSTLookup::SortByLastUsed(matchingVsts); for (int i = 0; i < (int)matchingVsts.size() && i < kMaxQuickspawnVstCount; ++i) { ModuleFactory::Spawnable spawnable{}; auto& pluginDesc = matchingVsts[i]; spawnable.mLabel = pluginDesc.name.toStdString(); spawnable.mDecorator = "[" + ModuleFactory::Spawnable::GetPluginLabel(pluginDesc) + "]"; spawnable.mPluginDesc = pluginDesc; spawnable.mSpawnMethod = SpawnMethod::Plugin; modules.push_back(spawnable); } std::vector<Spawnable> prefabs; ModuleFactory::GetPrefabs(prefabs); for (auto prefab : prefabs) { if (CheckHeldKeysMatch(prefab.mLabel, keys, continuousString) || keys[0] == ';') modules.push_back(prefab); } std::vector<std::string> midicontrollers = MidiController::GetAvailableInputDevices(); for (auto midicontroller : midicontrollers) { if (CheckHeldKeysMatch(midicontroller, keys, continuousString)) { ModuleFactory::Spawnable spawnable{}; spawnable.mLabel = midicontroller; spawnable.mDecorator = kMidiControllerSuffix; spawnable.mSpawnMethod = SpawnMethod::MidiController; modules.push_back(spawnable); } } std::vector<std::string> effects = TheSynth->GetEffectFactory()->GetSpawnableEffects(); for (auto effect : effects) { if (CheckHeldKeysMatch(effect, keys, continuousString)) { ModuleFactory::Spawnable spawnable{}; spawnable.mLabel = effect; spawnable.mDecorator = kEffectChainSuffix; spawnable.mSpawnMethod = SpawnMethod::EffectChain; modules.push_back(spawnable); } } std::vector<Spawnable> presets; ModuleFactory::GetPresets(presets); for (auto preset : presets) { if (CheckHeldKeysMatch(preset.mLabel, keys, continuousString) || keys[0] == ';') modules.push_back(preset); } sort(modules.begin(), modules.end(), Spawnable::CompareAlphabetical); std::vector<ModuleFactory::Spawnable> ret; for (size_t i = 0; i < modules.size(); ++i) ret.push_back(modules[i]); return ret; } ModuleCategory ModuleFactory::GetModuleCategory(std::string typeName) { if (mFactoryMap.find(typeName) != mFactoryMap.end()) return mFactoryMap[typeName].mCategory; if (juce::String(typeName).endsWith(kPluginSuffix)) return kModuleCategory_Synth; if (juce::String(typeName).endsWith(kMidiControllerSuffix)) return kModuleCategory_Instrument; if (juce::String(typeName).endsWith(kEffectChainSuffix)) return kModuleCategory_Audio; return kModuleCategory_Other; } ModuleCategory ModuleFactory::GetModuleCategory(Spawnable spawnable) { if (spawnable.mSpawnMethod == SpawnMethod::Module && mFactoryMap.find(spawnable.mLabel) != mFactoryMap.end()) return mFactoryMap[spawnable.mLabel].mCategory; if (spawnable.mSpawnMethod == SpawnMethod::Plugin) return kModuleCategory_Synth; if (spawnable.mSpawnMethod == SpawnMethod::MidiController) return kModuleCategory_Instrument; if (spawnable.mSpawnMethod == SpawnMethod::EffectChain) return kModuleCategory_Audio; if (spawnable.mSpawnMethod == SpawnMethod::Prefab) return kModuleCategory_Other; if (spawnable.mSpawnMethod == SpawnMethod::Preset) return mFactoryMap[spawnable.mPresetModuleType].mCategory; return kModuleCategory_Other; } ModuleFactory::ModuleInfo ModuleFactory::GetModuleInfo(std::string typeName) { if (mFactoryMap.find(typeName) != mFactoryMap.end()) return mFactoryMap[typeName]; return ModuleInfo(); } bool ModuleFactory::IsExperimental(std::string typeName) { if (mFactoryMap.find(typeName) != mFactoryMap.end()) return mFactoryMap[typeName].mIsExperimental; return false; } //static void ModuleFactory::GetPrefabs(std::vector<ModuleFactory::Spawnable>& prefabs) { using namespace juce; File dir(ofToDataPath("prefabs")); Array<File> files; dir.findChildFiles(files, File::findFiles, false); for (auto file : files) { if (file.getFileExtension() == ".pfb") { ModuleFactory::Spawnable spawnable; spawnable.mLabel = file.getFileName().toStdString(); spawnable.mDecorator = kPrefabSuffix; spawnable.mSpawnMethod = SpawnMethod::Prefab; prefabs.push_back(spawnable); } } } //static void ModuleFactory::GetPresets(std::vector<ModuleFactory::Spawnable>& presets) { using namespace juce; File dir(ofToDataPath("presets")); Array<File> directories; dir.findChildFiles(directories, File::findDirectories, false); for (auto moduleDir : directories) { std::string moduleTypeName = moduleDir.getFileName().toStdString(); Array<File> files; moduleDir.findChildFiles(files, File::findFiles, false); for (auto file : files) { if (file.getFileExtension() == ".preset") { ModuleFactory::Spawnable spawnable; spawnable.mLabel = file.getFileName().toStdString(); spawnable.mDecorator = "[" + moduleTypeName + "]"; spawnable.mPresetModuleType = moduleTypeName; spawnable.mSpawnMethod = SpawnMethod::Preset; presets.push_back(spawnable); } } } } //static std::string ModuleFactory::FixUpTypeName(std::string name) { if (name == "siggen") return "signalgenerator"; if (name == "eqmodule") return "eq"; if (name == "bandvocoder") return "vocoder"; if (name == "vstplugin") return "plugin"; if (name == "presets") return "snapshots"; if (name == "arpsequencer") return "rhythmsequencer"; return name; } ```
/content/code_sandbox/Source/ModuleFactory.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
8,177
```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 **/ // // PitchAssigner.cpp // Bespoke // // Created by Ryan Challinor on 11/27/15. // // #include "PitchSetter.h" #include "OpenFrameworksPort.h" #include "SynthGlobals.h" #include "ModularSynth.h" PitchSetter::PitchSetter() { } void PitchSetter::CreateUIControls() { IDrawableModule::CreateUIControls(); mPitchSlider = new IntSlider(this, "pitch", 5, 2, 80, 15, &mPitch, 0, 127); } void PitchSetter::DrawModule() { if (Minimized() || IsVisible() == false) return; mPitchSlider->Draw(); } void PitchSetter::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) mNoteOutput.Flush(time); } void PitchSetter::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mPitchSlider) mNoteOutput.Flush(time); } void PitchSetter::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { ComputeSliders(0); if (mEnabled) PlayNoteOutput(time, mPitch, velocity, voiceIdx, modulation); else PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void PitchSetter::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void PitchSetter::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/PitchSetter.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
452
```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.cpp Created: 2 Mar 2021 7:48:14pm Author: Ryan Challinor ============================================================================== */ #include "UnstablePitch.h" #include "OpenFrameworksPort.h" #include "ModularSynth.h" #include "UIControlMacros.h" UnstablePitch::UnstablePitch() { for (int voice = 0; voice < kNumVoices; ++voice) mModulation.GetPitchBend(voice)->CreateBuffer(); } void UnstablePitch::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } UnstablePitch::~UnstablePitch() { TheTransport->RemoveAudioPoller(this); } void UnstablePitch::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK(3, 40, 140); FLOATSLIDER(mAmountSlider, "amount", &mPerlin.mPerlinAmount, 0, 1); FLOATSLIDER(mWarbleSlider, "warble", &mPerlin.mPerlinWarble, 0, 1); FLOATSLIDER(mNoiseSlider, "noise", &mPerlin.mPerlinNoise, 0, 1); ENDUIBLOCK(mWidth, mHeight); mWarbleSlider->SetMode(FloatSlider::kSquare); mNoiseSlider->SetMode(FloatSlider::kSquare); } void UnstablePitch::DrawModule() { if (Minimized() || IsVisible() == false) return; ofPushStyle(); ofRectangle rect(3, 3, mWidth - 6, 34); const int kGridSize = 30; ofFill(); for (int col = 0; col < kGridSize; ++col) { float x = rect.x + col * (rect.width / kGridSize); float y = rect.y; float val = mPerlin.GetValue(gTime, x / rect.width * 10, 0) * ofClamp(mPerlin.mPerlinAmount * 5, 0, 1); ofSetColor(val * 255, 0, val * 255); ofRect(x, y, (rect.width / kGridSize) + .5f, rect.height + .5f, 0); } ofNoFill(); ofSetColor(0, 255, 0, 90); for (int voice = 0; voice < kNumVoices; ++voice) { if (mIsVoiceUsed[voice]) { ofBeginShape(); for (int i = 0; i < gBufferSize; ++i) { float sample = ofClamp(mModulation.GetPitchBend(voice)->GetBufferValue(i) * 5, -1, 1); ofVertex((i * rect.width) / gBufferSize + rect.x, rect.y + (-sample * .5f + .5f) * rect.height); } ofEndShape(); } } ofPopStyle(); mAmountSlider->Draw(); mWarbleSlider->Draw(); mNoiseSlider->Draw(); } void UnstablePitch::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mEnabled) { if (voiceIdx == -1) { if (velocity > 0) { bool foundVoice = false; for (size_t i = 0; i < mIsVoiceUsed.size(); ++i) { int voiceToCheck = (i + mVoiceRoundRobin) % kNumVoices; if (mIsVoiceUsed[voiceToCheck] == false) { voiceIdx = voiceToCheck; mVoiceRoundRobin = (mVoiceRoundRobin + 1) % kNumVoices; foundVoice = true; break; } } if (!foundVoice) { voiceIdx = mVoiceRoundRobin; mVoiceRoundRobin = (mVoiceRoundRobin + 1) % kNumVoices; } } else { voiceIdx = mPitchToVoice[pitch]; } } if (voiceIdx < 0 || voiceIdx >= kNumVoices) voiceIdx = 0; mIsVoiceUsed[voiceIdx] = velocity > 0; mPitchToVoice[pitch] = (velocity > 0) ? voiceIdx : -1; mModulation.GetPitchBend(voiceIdx)->AppendTo(modulation.pitchBend); modulation.pitchBend = mModulation.GetPitchBend(voiceIdx); } FillModulationBuffer(time, voiceIdx); PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void UnstablePitch::OnTransportAdvanced(float amount) { ComputeSliders(0); for (int voice = 0; voice < kNumVoices; ++voice) { if (mIsVoiceUsed[voice]) FillModulationBuffer(gTime, voice); } } void UnstablePitch::FillModulationBuffer(double time, int voiceIdx) { for (int i = 0; i < gBufferSize; ++i) gWorkBuffer[i] = ofMap(mPerlin.GetValue(time + i * gInvSampleRateMs, (time + i * gInvSampleRateMs) / 1000, voiceIdx), 0, 1, -mPerlin.mPerlinAmount, mPerlin.mPerlinAmount); mModulation.GetPitchBend(voiceIdx)->FillBuffer(gWorkBuffer); } void UnstablePitch::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void UnstablePitch::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) { if (!mEnabled) { for (size_t i = 0; i < mIsVoiceUsed.size(); ++i) mIsVoiceUsed[i] = false; } } } void UnstablePitch::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void UnstablePitch::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/UnstablePitch.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,475
```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 **/ // // Oscillator.h // Bespoke // // Created by Ryan Challinor on 7/3/14. // // #pragma once #include <iostream> #include "SynthGlobals.h" #include "ADSR.h" class Oscillator { public: Oscillator(OscillatorType type) : mType(type) {} enum class SyncMode { None, Ratio, Frequency }; OscillatorType GetType() const { return mType; } void SetType(OscillatorType type) { mType = type; } float Value(float phase) const; float GetPulseWidth() const { return mPulseWidth; } void SetPulseWidth(float width) { mPulseWidth = width; } float GetShuffle() const { return mShuffle; } void SetShuffle(float shuffle) { mShuffle = MIN(shuffle, .999f); } float GetSoften() const { return mSoften; } void SetSoften(float soften) { mSoften = ofClamp(soften, 0, 1); } OscillatorType mType{ OscillatorType::kOsc_Sin }; private: float SawSample(float phase) const; float mPulseWidth{ .5 }; float mShuffle{ 0 }; float mSoften{ 0 }; }; ```
/content/code_sandbox/Source/Oscillator.h
objective-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 **/ /* ============================================================================== MidiControlChange.cpp Created: 5 Aug 2021 9:32:14pm Author: Ryan Challinor ============================================================================== */ #include "MidiControlChange.h" #include "OpenFrameworksPort.h" #include "ModularSynth.h" #include "UIControlMacros.h" MidiControlChange::MidiControlChange() { } void MidiControlChange::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); TEXTENTRY_NUM(mControlEntry, "control", 4, &mControl, 0, 127); FLOATSLIDER(mValueSlider, "value", &mValue, 0, 127); ENDUIBLOCK(mWidth, mHeight); } void MidiControlChange::DrawModule() { if (Minimized() || IsVisible() == false) return; mControlEntry->Draw(); mValueSlider->Draw(); } void MidiControlChange::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void MidiControlChange::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mValueSlider && mEnabled) { if (int(oldVal) != int(mValue) || mResendDuplicateValue) SendCCOutput(mControl, int(mValue)); } } void MidiControlChange::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadBool("resend_duplicate_value", moduleInfo, false); SetUpFromSaveData(); } void MidiControlChange::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); mResendDuplicateValue = mModuleSaveData.GetBool("resend_duplicate_value"); } ```
/content/code_sandbox/Source/MidiControlChange.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
508
```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 **/ /* ============================================================================== NoteQuantizer.h Created: 6 Dec 2020 7:36:30pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "IDrawableModule.h" #include "NoteEffectBase.h" #include "DropdownList.h" #include "Transport.h" #include "IPulseReceiver.h" class NoteQuantizer : public NoteEffectBase, public IDrawableModule, public IDropdownListener, public ITimeListener, public IPulseReceiver { public: NoteQuantizer(); virtual ~NoteQuantizer(); static IDrawableModule* Create() { return new NoteQuantizer(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return true; } 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; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void OnTimeEvent(double time) override; void OnPulse(double time, float velocity, int flags) 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 = 80; height = 40; } void OnEvent(double time, float strength); struct InputInfo { int velocity{ 0 }; int voiceIdx{ -1 }; bool held{ false }; bool hasPlayedYet{ false }; ModulationParameters modulation; }; bool mNoteRepeat{ false }; Checkbox* mNoteRepeatCheckbox{ nullptr }; NoteInterval mQuantizeInterval{ NoteInterval::kInterval_16n }; DropdownList* mQuantizeIntervalSelector{ nullptr }; std::array<InputInfo, 128> mInputInfos{}; std::array<bool, 128> mScheduledOffs{}; std::array<bool, 128> mPreScheduledOffs{}; bool mHasReceivedPulse{ false }; }; ```
/content/code_sandbox/Source/NoteQuantizer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
621
```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 **/ /* ============================================================================== CodeEntry.cpp Created: 19 Apr 2020 9:26:55am Author: Ryan Challinor ============================================================================== */ #include "ModularSynth.h" #ifdef _MSC_VER #define ssize_t ssize_t_undef_hack //fixes conflict with ssize_t typedefs between python and juce #endif #include "IDrawableModule.h" #include "CodeEntry.h" #include "Transport.h" #include "ScriptModule.h" #ifdef _MSC_VER #undef ssize_t #endif #include "leathers/push" #include "leathers/unused-value" #include "leathers/range-loop-analysis" #include "pybind11/embed.h" #include "pybind11/stl.h" #include "leathers/pop" #include "juce_gui_basics/juce_gui_basics.h" namespace py = pybind11; //static bool CodeEntry::sWarnJediNotInstalled = false; bool CodeEntry::sDoPythonAutocomplete = false; bool CodeEntry::sDoSyntaxHighlighting = false; CodeEntry::CodeEntry(ICodeEntryListener* owner, const char* name, int x, int y, float w, float h) : mListener(owner) { SetName(name); SetPosition(x, y); mWidth = w; mHeight = h; IDrawableModule* module = dynamic_cast<IDrawableModule*>(owner); assert(module); module->AddUIControl(this); SetParent(dynamic_cast<IClickable*>(owner)); } CodeEntry::~CodeEntry() { } void CodeEntry::Poll() { if (mCodeUpdated) { if (mDoSyntaxHighlighting && sDoSyntaxHighlighting) { try { py::globals()["syntax_highlight_code"] = GetVisibleCode(); py::object ret = py::eval("syntax_highlight_basic()", py::globals()); mSyntaxHighlightMapping = ret.cast<std::vector<int> >(); } catch (const std::exception& e) { ofLog() << "syntax highlight execution exception: " << e.what(); } } else { mSyntaxHighlightMapping.clear(); } if (mListener) mListener->OnCodeUpdated(); mCodeUpdated = false; } if (mAutocompleteUpdateTimer > 0) { mAutocompleteUpdateTimer -= 1.0 / ofGetFrameRate(); if (mAutocompleteUpdateTimer <= 0) { if (sDoPythonAutocomplete) { mAutocompleteCaretCoords = GetCaretCoords(mCaretPosition); if (!GetVisibleCode().empty()) { try { std::string prefix = ScriptModule::GetBootstrapImportString() + "; import me\n"; py::exec("jediScript = jedi.Script('''" + prefix + GetVisibleCode() + "''', project=jediProject)", py::globals()); //py::exec("jediScript = jedi.Script('''" + prefix + GetVisibleCode() + "''')", py::globals()); //py::exec("jediScript = jedi.Interpreter('''" + prefix + GetVisibleCode() + "''', [locals(), globals()])", py::globals()); auto coords = GetCaretCoords(mCaretPosition); { py::object ret = py::eval("jediScript.get_signatures(" + ofToString(coords.y + 2) + "," + ofToString(coords.x) + ")", py::globals()); auto signatures = ret.cast<std::list<py::object> >(); size_t i = 0; for (auto signature : signatures) { mWantToShowAutocomplete = true; if (i < mAutocompleteSignatures.size()) { mAutocompleteSignatures[i].valid = true; mAutocompleteSignatures[i].entryIndex = signature.attr("index").cast<int>(); auto params = signature.attr("params").cast<std::vector<py::object> >(); mAutocompleteSignatures[i].params.resize(params.size()); for (size_t j = 0; j < params.size(); ++j) mAutocompleteSignatures[i].params[j] = juce::String(py::str(params[j].attr("description"))).replace("param ", "").toStdString(); auto bracket_start = signature.attr("bracket_start").cast<std::tuple<int, int> >(); mAutocompleteSignatures[i].caretPos = GetCaretPosition(std::get<1>(bracket_start), std::get<0>(bracket_start) - 2); ++i; } else { break; } } for (; i < mAutocompleteSignatures.size(); ++i) mAutocompleteSignatures[i].valid = false; } { py::object ret = py::eval("jediScript.complete(" + ofToString(coords.y + 2) + "," + ofToString(coords.x) + ")", py::globals()); auto autocompletes = ret.cast<std::list<py::object> >(); //ofLog() << "autocompletes:"; size_t i = 0; if (autocompletes.size() < 100) { mWantToShowAutocomplete = true; mAutocompleteHighlightIndex = 0; bool isPathAutocomplete = false; if (mAutocompleteSignatures.size() > 0 && mAutocompleteSignatures[0].valid && mAutocompleteSignatures[0].params.size() > 0 && mAutocompleteSignatures[0].params[0] == "path") isPathAutocomplete = true; if (!isPathAutocomplete) //normal autocomplete { for (auto autocomplete : autocompletes) { //ofLog() << " --" << autocomplete; std::string full = py::str(autocomplete.attr("name")); std::string rest = py::str(autocomplete.attr("complete")); if (!((juce::String)full).startsWith("__") && i < mAutocompletes.size()) { mAutocompletes[i].valid = true; mAutocompletes[i].autocompleteFull = full; mAutocompletes[i].autocompleteRest = rest; ++i; } else { break; } } } else //we're autocompleting a path, look for matching instantiated module names { int stringStart = mAutocompleteSignatures[0].caretPos + 2; std::string writtenSoFar = mString.substr(stringStart, mCaretPosition - stringStart); std::vector<IDrawableModule*> modules; TheSynth->GetAllModules(modules); for (auto module : modules) { juce::String modulePath = module->Path(); if (modulePath.startsWith(writtenSoFar)) { std::string full = modulePath.toStdString(); std::string rest = full; ofStringReplace(rest, writtenSoFar, "", true); if (i < mAutocompletes.size()) { mAutocompletes[i].valid = true; mAutocompletes[i].autocompleteFull = full; mAutocompletes[i].autocompleteRest = rest; ++i; } else { break; } } } } } for (; i < mAutocompletes.size(); ++i) mAutocompletes[i].valid = false; } } catch (const std::exception& e) { ofLog() << "autocomplete exception: " << e.what(); } } else { for (size_t i = 0; i < mAutocompleteSignatures.size(); ++i) mAutocompleteSignatures[i].valid = false; for (size_t i = 0; i < mAutocompletes.size(); ++i) mAutocompletes[i].valid = false; } } } } } void CodeEntry::Render() { ofPushStyle(); ofPushMatrix(); ofSetLineWidth(.5f); float w, h; GetDimensions(w, h); ofClipWindow(mX, mY, w, h, true); bool isCurrent = IKeyboardFocusListener::GetActiveKeyboardFocus() == this; ofColor color = ofColor::white; ofFill(); bool hasUnpublishedCode = (mString != mPublishedString); if (isCurrent) { ofSetColor(currentBg); } else { if (hasUnpublishedCode) ofSetColor(unpublishedBg); else ofSetColor(publishedBg); } ofRect(mX, mY, w, h); double timeSincePublished = gTime - mLastPublishTime; if (TheSynth->IsAudioPaused()) timeSincePublished = 99999; if (timeSincePublished < 400) { ofSetColor(0, 255, 0, 150 * (1 - timeSincePublished / 400)); ofRect(mX, mLastPublishedLineStart * mCharHeight + mY + 3 - mScroll.y, mWidth, mCharHeight * (mLastPublishedLineEnd + 1 - mLastPublishedLineStart), L(corner, 2)); } ofPushStyle(); ofNoFill(); if (mHasError) { ofSetColor(255, 0, 0, gModuleDrawAlpha); ofSetLineWidth(2); } else if (hasUnpublishedCode) { float highlight = 1 - ofClamp(timeSincePublished / 150, 0, 1); ofSetColor(ofLerp(170, 255, highlight), 255, ofLerp(170, 255, highlight), gModuleDrawAlpha); ofSetLineWidth(2 + highlight * 3); } else { ofSetColor(color, gModuleDrawAlpha); } ofRect(mX, mY, w, h); ofPopStyle(); if (mHasError && mErrorLine >= 0) { ofPushStyle(); ofFill(); ofSetColor(255, 0, 0, gModuleDrawAlpha * .5f); ofRect(mX, mErrorLine * mCharHeight + mY + 3 - mScroll.y, mWidth, mCharHeight, L(corner, 2)); ofFill(); } mCharWidth = gFontFixedWidth.GetStringWidth("x", mFontSize); mCharHeight = gFontFixedWidth.GetStringHeight("x", mFontSize); if (hasUnpublishedCode) { ofSetColor(color, gModuleDrawAlpha * .05f); gFontFixedWidth.DrawString(mPublishedString, mFontSize, mX + 2 - mScroll.x, mY + mCharHeight - mScroll.y); } ofSetColor(color, gModuleDrawAlpha); std::string drawString = GetVisibleCode(); ofPushStyle(); const float dim = .7f; DrawSyntaxHighlight(drawString, stringColor * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, 3, -1); DrawSyntaxHighlight(drawString, numberColor * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, 2, -1); DrawSyntaxHighlight(drawString, name1Color * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, 1, -1); DrawSyntaxHighlight(drawString, name2Color * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, 90, -1); DrawSyntaxHighlight(drawString, name3Color * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, 91, -1); DrawSyntaxHighlight(drawString, definedColor * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, 92, -1); DrawSyntaxHighlight(drawString, equalsColor * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, 22, -1); DrawSyntaxHighlight(drawString, parenColor * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, 7, 8); DrawSyntaxHighlight(drawString, braceColor * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, 25, 26); DrawSyntaxHighlight(drawString, bracketColor * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, 9, 10); DrawSyntaxHighlight(drawString, opColor * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, 51, -1); DrawSyntaxHighlight(drawString, commaColor * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, 12, -1); DrawSyntaxHighlight(drawString, commentColor * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, 53, -1); DrawSyntaxHighlight(drawString, unknownColor * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, 52, 59); //"error" token (like incomplete quotes) DrawSyntaxHighlight(drawString, unknownColor * (isCurrent ? 1 : dim), mSyntaxHighlightMapping, -1, -1); ofPopStyle(); /*for (int i = 0; i<60; ++i) { for (int j=0; j<15; ++j) ofRect(mX + 2 + mCharWidth * i, mY + 2 + mCharHeight * j, mCharWidth, mCharHeight, L(corner,2)); }*/ if (IKeyboardFocusListener::GetActiveKeyboardFocus() == this) { ofVec2f coords = GetCaretCoords(mCaretPosition); ofVec2f caretPos = ofVec2f(coords.x * mCharWidth + mX + 1.5f - mScroll.x, coords.y * mCharHeight + mY + 2 - mScroll.y); if (mCaretBlink) { ofFill(); ofRect(caretPos.x, caretPos.y, 1, mCharHeight, L(corner, 1)); } mCaretBlinkTimer += ofGetLastFrameTime(); if (mCaretBlinkTimer > .3f) { mCaretBlinkTimer -= .3f; mCaretBlink = !mCaretBlink; } if (mCaretPosition != mCaretPosition2) { ofPushStyle(); ofFill(); ofSetColor(selectedOverlay); int caretStart = MIN(mCaretPosition, mCaretPosition2); int caretEnd = MAX(mCaretPosition, mCaretPosition2); ofVec2f coordsStart = GetCaretCoords(caretStart); ofVec2f coordsEnd = GetCaretCoords(caretEnd); int startLineNum = (int)round(coordsStart.y); int endLineNum = (int)round(coordsEnd.y); int startCol = (int)round(coordsStart.x); int endCol = (int)round(coordsEnd.x); auto lines = GetLines(false); for (int i = startLineNum; i <= endLineNum; ++i) { int begin = 0; int end = 0; if (i < (int)lines.size()) end = (int)lines[i].length(); if (i == startLineNum) begin = startCol; if (i == endLineNum) end = endCol; ofRect(begin * mCharWidth + mX + 1.5f - mScroll.x, i * mCharHeight + mY + 3 - mScroll.y, (end - begin) * mCharWidth, mCharHeight, L(corner, 2)); } ofPopStyle(); } } /*if (mHovered) { ofSetColor(100, 100, 100, .8f*gModuleDrawAlpha); ofFill(); ofRect(mX,mY-12,GetStringWidth(Name()),12); ofSetColor(255, 255, 255, gModuleDrawAlpha); DrawTextNormal(Name(), mX, mY); }*/ ofPopMatrix(); ofPopStyle(); } void CodeEntry::RenderOverlay() { if (IKeyboardFocusListener::GetActiveKeyboardFocus() != this) return; if (!IsAutocompleteShowing()) return; ofVec2f caretPos = ofVec2f(mAutocompleteCaretCoords.x * mCharWidth + mX + 1.5f - mScroll.x, mAutocompleteCaretCoords.y * mCharHeight + mY + 2 - mScroll.y); ofFill(); for (size_t i = 0; i < mAutocompletes.size(); ++i) { if (mAutocompletes[i].valid) { int charactersLeft = (int)mAutocompletes[i].autocompleteFull.length() - (int)mAutocompletes[i].autocompleteRest.length(); float x = caretPos.x - charactersLeft * mCharWidth; float y = caretPos.y + mCharHeight * (i + 2) - 2; if (i == mAutocompleteHighlightIndex) ofSetColor(jediIndexBg); else ofSetColor(jediBg); ofRect(x, y - mCharHeight + 2, gFontFixedWidth.GetStringWidth(mAutocompletes[i].autocompleteFull, mFontSize), mCharHeight); ofSetColor(jediAutoComplete); gFontFixedWidth.DrawString(mAutocompletes[i].autocompleteFull, mFontSize, x, y); ofSetColor(jediAutoCompleteRest); std::string prefix = ""; for (size_t j = 0; j < charactersLeft; ++j) prefix += " "; gFontFixedWidth.DrawString(prefix + mAutocompletes[i].autocompleteRest, mFontSize, x, y); } } for (size_t i = 0; i < mAutocompleteSignatures.size(); ++i) { if (mAutocompleteSignatures[i].valid && mAutocompleteSignatures[i].params.size() > 0) { std::string params = "("; std::string highlightParamString = " "; for (size_t j = 0; j < mAutocompleteSignatures[i].params.size(); ++j) { std::string param = mAutocompleteSignatures[i].params[j]; std::string placeholder = ""; for (size_t k = 0; k < param.length(); ++k) placeholder += " "; if (j == mAutocompleteSignatures[i].entryIndex) { params += placeholder; highlightParamString += mAutocompleteSignatures[i].params[j]; } else { params += mAutocompleteSignatures[i].params[j]; highlightParamString += placeholder; } if (j < mAutocompleteSignatures[i].params.size() - 1) { params += ", "; highlightParamString += " "; } } params += ")"; highlightParamString += " "; float x = GetLinePos(mAutocompleteCaretCoords.y, K(end), !K(published)).x + 10; float y = caretPos.y + mCharHeight * (i + 1) - 2; ofSetColor(jediBg); ofRect(x, y - mCharHeight + 2, gFontFixedWidth.GetStringWidth(params, mFontSize), mCharHeight + 2); ofSetColor(jediParams); gFontFixedWidth.DrawString(params, mFontSize, x, y); ofSetColor(jediParamsHighlight); gFontFixedWidth.DrawString(highlightParamString, mFontSize, x, y); } } } std::string CodeEntry::GetVisibleCode() { std::string visible; std::vector<std::string> lines = GetLines(false); if (lines.empty()) return ""; int firstVisibleLine = -1; int lastVisibleLine = -1; for (int i = 0; i < (int)lines.size(); ++i) { if ((i + 1) * mCharHeight >= mScroll.y && i * mCharHeight <= mScroll.y + mHeight) { if (firstVisibleLine == -1) firstVisibleLine = i; lastVisibleLine = i; } } while (firstVisibleLine > 0) { if (lines[firstVisibleLine][0] != ' ') break; --firstVisibleLine; } for (int i = 0; i < (int)lines.size(); ++i) { if (i >= firstVisibleLine && i <= lastVisibleLine) visible += lines[i] + "\n"; else visible += "\n"; } return visible; } void CodeEntry::DrawSyntaxHighlight(std::string input, ofColor color, std::vector<int> mapping, int filter1, int filter2) { std::string filtered = FilterText(input, mapping, filter1, filter2); ofSetColor(color, gModuleDrawAlpha); float shake = (1 - ofClamp((gTime - mLastPublishTime) / 150, 0, 1)) * 3.0f; if (TheSynth->IsAudioPaused()) shake = 0; float offsetX = ofRandom(-shake, shake); float offsetY = ofRandom(-shake, shake); gFontFixedWidth.DrawString(filtered, mFontSize, mX + 2 - mScroll.x + offsetX, mY + mCharHeight - mScroll.y + offsetY); } std::string CodeEntry::FilterText(std::string input, std::vector<int> mapping, int filter1, int filter2) { for (size_t i = 0; i < input.size(); ++i) { if (input[i] != '\n') { if (i < mapping.size()) { if (mapping[i] != filter1 && mapping[i] != filter2) input[i] = ' '; } else { bool showLeftovers = (filter1 == -1 && filter2 == -1); if (!showLeftovers) input[i] = ' '; } } } return input; } //static void CodeEntry::OnPythonInit() { const std::string syntaxHighlightCode = R"(def syntax_highlight_basic(): #this uses the built in lexer/tokenizer in python to identify part of code #will return a meaningful lookuptable for index colours per character import tokenize import io import token import sys isPython3 = False if sys.version_info[0] >= 3: isPython3 = True if isPython3: text = str(syntax_highlight_code) else: text = unicode(syntax_highlight_code) tok_name = token.tok_name #print(tok_name) # <--- dict of token-kinds. output = [] defined = [] lastCharEnd = 0 lastRowEnd = 0 with io.StringIO(text) as f: try: tokens = tokenize.generate_tokens(f.readline) for token in tokens: #print(token) if token.type in (0, 5, 56, 256): continue if not token.string or (token.start == token.end): continue token_type = token.type if token.type == 1: if token.string in {'print', 'def', 'class', 'break', 'continue', 'return', 'while', 'or', 'and', 'dir', 'if', 'elif', 'else', 'is', 'in', 'as', 'out', 'with', 'from', 'import', 'with', 'for'}: token_type = 90 elif token.string in {'False', 'True', 'yield', 'repr', 'range', 'enumerate', 'len', 'type', 'list', 'tuple', 'int', 'str', 'float'}: token_type = 91 elif token.string in globals() or token.string in defined: token_type = 92 #else: # defined.append(token.string) don't do this one, it makes for confusing highlighting elif isPython3 and token.type == 54: # OPS # 7: 'LPAR', 8: 'RPAR' # 9: 'LSQB', 10: 'RSQB' # 25: 'LBRACE', 26: 'RBRACE' if token.exact_type in {7, 8, 9, 10, 25, 26}: token_type = token.exact_type else: token_type = 51 elif token.type == 51: # OPS # 7: 'LPAR', 8: 'RPAR # 9: 'LSQB', 10: 'RSQB' # 25: 'LBRACE', 26: 'RBRACE' if token.string in {'(', ')'}: token_type = 7 elif token.string in {'[', ']'}: token_type = 9 elif token.string in {'{', '}'}: token_type = 25 elif token.string in {'='}: token_type = 22 elif token.string in {','}: token_type = 12 elif isPython3 and tok_name[token.type] == 'COMMENT': token_type = 53 if not token_type in [3, 2, 1, 90, 91, 92, 22, 7, 8, 25, 26, 9, 10, 51, 12, 53, 52, 59]: #this list matches the list of matches we use for the DrawSyntaxHighlight() calls token_type = -1 row_start, char_start = token.start[0]-1, token.start[1] row_end, char_end = token.end[0]-1, token.end[1] if lastRowEnd != row_end: lastCharEnd = 0 output = output + [99]*(char_start - lastCharEnd) + [token_type]*(char_end - char_start) lastCharEnd = char_end lastRowEnd = row_end #print(token_type) except Exception as e: exceptionText = str(e) if not 'EOF' in exceptionText: print("exception when syntax highlighting: "+exceptionText) pass #print(output) return output)"; try { py::exec(syntaxHighlightCode, py::globals()); sDoSyntaxHighlighting = true; } catch (const std::exception& e) { ofLog() << "syntax highlight initialization exception: " << e.what(); } //autocomplete try { py::exec("import jedi", py::globals()); try { //py::exec("jedi.preload_module(['bespoke','module','scriptmodule','random','math'])", py::globals()); py::exec("jediProject = jedi.get_default_project()", py::globals()); py::exec("jediProject.added_sys_path = [\"" + ofToResourcePath("python_stubs") + "\"]", py::globals()); //py::eval_file(ofToResourcePath("bespoke_stubs.pyi"), py::globals()); //py::exec("import sys;sys.path.append(\""+ ofToResourcePath("python_stubs")+"\")", py::globals()); sDoPythonAutocomplete = true; } catch (const std::exception& e) { ofLog() << "autocomplete setup exception: " << e.what(); } } catch (const std::exception& e) { ofLog() << "autocomplete initialization exception: " << e.what(); ofLog() << "maybe jedi is not installed? if you want autocompletion, use \"python -m pip install jedi\" in your system console to install"; sWarnJediNotInstalled = true; } } void CodeEntry::OnCodeUpdated() { mCodeUpdated = true; } bool CodeEntry::IsAutocompleteShowing() { if (!mWantToShowAutocomplete || mCaretPosition != mCaretPosition2 || mString == mPublishedString) return false; if (mAutocompletes[0].valid == false && mAutocompleteSignatures[0].valid == false) return false; if (mAutocompleteUpdateTimer <= 0) { ofVec2f coords = GetCaretCoords(mCaretPosition); return coords.x == mAutocompleteCaretCoords.x && coords.y == mAutocompleteCaretCoords.y; } return true; } void CodeEntry::SetError(bool error, int errorLine) { mHasError = error; mErrorLine = errorLine; } void CodeEntry::OnClicked(float x, float y, bool right) { if (right) return; float col = GetColForX(x); float row = GetRowForY(y); MoveCaret(GetCaretPosition(col, row)); MakeActive(); } void CodeEntry::MakeActive() { SetActiveKeyboardFocus(this); mCaretBlink = true; mCaretBlinkTimer = 0; } namespace { const int kTabSize = 3; } void CodeEntry::OnKeyPressed(int key, bool isRepeat) { if (key == juce::KeyPress::backspaceKey) { if (mCaretPosition != mCaretPosition2) { RemoveSelectedText(); } else if (mCaretPosition > 0) { MoveCaret(mCaretPosition - 1, false); if (mCaretPosition < mString.length() - 1) UpdateString(mString.substr(0, mCaretPosition) + mString.substr(mCaretPosition + 1)); else UpdateString(mString.substr(0, mCaretPosition)); } } else if (key == juce::KeyPress::deleteKey) { if (mCaretPosition != mCaretPosition2) { RemoveSelectedText(); } else { if (mCaretPosition == 0) UpdateString(mString.substr(1)); if (mCaretPosition < mString.length() - 1) UpdateString(mString.substr(0, mCaretPosition) + mString.substr(mCaretPosition + 1)); } } else if (key == OF_KEY_TAB) { if (mCaretPosition != mCaretPosition2 || (GetKeyModifiers() & kModifier_Shift)) { ShiftLines(GetKeyModifiers() & kModifier_Shift); } else { ofVec2f coords = GetCaretCoords(mCaretPosition); int spacesNeeded = kTabSize - (int)coords.x % kTabSize; std::string tab; for (int i = 0; i < spacesNeeded; ++i) tab += " "; AddString(tab); } } else if (key == ']' && GetKeyModifiers() == kModifier_Command) { ShiftLines(false); } else if (key == '[' && GetKeyModifiers() == kModifier_Command) { ShiftLines(true); } else if (key == OF_KEY_ESC) { if (IsAutocompleteShowing()) { mWantToShowAutocomplete = false; } else { IKeyboardFocusListener::ClearActiveKeyboardFocus(K(notifyListeners)); UpdateString(mPublishedString); //revert mCaretPosition2 = mCaretPosition; } } else if (key == OF_KEY_LEFT) { if (GetKeyModifiers() & kModifier_Command) { MoveCaretToStart(); } else if (GetKeyModifiers() & kModifier_Alt) { MoveCaretToNextToken(true); } else { if (!(GetKeyModifiers() & kModifier_Shift) && mCaretPosition != mCaretPosition2) MoveCaret(MIN(mCaretPosition, mCaretPosition2)); else if (mCaretPosition > 0) MoveCaret(mCaretPosition - 1); } } else if (key == OF_KEY_RIGHT) { if (GetKeyModifiers() & kModifier_Command) { MoveCaretToEnd(); } else if (GetKeyModifiers() & kModifier_Alt) { MoveCaretToNextToken(false); } else { if (!(GetKeyModifiers() & kModifier_Shift) && mCaretPosition != mCaretPosition2) MoveCaret(MAX(mCaretPosition, mCaretPosition2)); else if (mCaretPosition < mString.length()) MoveCaret(mCaretPosition + 1); } } else if (key == OF_KEY_UP) { if (IsAutocompleteShowing() && mAutocompleteHighlightIndex > 0) { --mAutocompleteHighlightIndex; } else { ofVec2f coords = GetCaretCoords(mCaretPosition); if (coords.y > 0) --coords.y; MoveCaret(GetCaretPosition(coords.x, coords.y)); } } else if (key == OF_KEY_DOWN) { if (IsAutocompleteShowing() && (mAutocompleteHighlightIndex + 1 < mAutocompletes.size() && mAutocompletes[mAutocompleteHighlightIndex].valid)) { ++mAutocompleteHighlightIndex; } else { ofVec2f coords = GetCaretCoords(mCaretPosition); ++coords.y; MoveCaret(GetCaretPosition(coords.x, coords.y)); } } else if (key == OF_KEY_RETURN) { if (IsAutocompleteShowing()) { AcceptAutocompletion(); } else { if (mCaretPosition != mCaretPosition2) RemoveSelectedText(); ofVec2f coords = GetCaretCoords(mCaretPosition); int lineNum = (int)round(coords.y); auto lines = GetLines(false); int numSpaces = 0; if (mCaretPosition > 0 && mString[mCaretPosition - 1] == ':') //auto-indent numSpaces += kTabSize; if (lineNum < (int)lines.size()) { for (int i = 0; i < lines[lineNum].length(); ++i) { if (lines[lineNum][i] == ' ') ++numSpaces; else break; } } std::string tab = "\n"; for (int i = 0; i < numSpaces; ++i) tab += ' '; AddString(tab); } } else if (toupper(key) == 'V' && GetKeyModifiers() == kModifier_Command) { if (mCaretPosition != mCaretPosition2) RemoveSelectedText(); juce::String clipboard = TheSynth->GetTextFromClipboard(); AddString(clipboard.toStdString()); } else if (toupper(key) == 'V' && (GetKeyModifiers() == (kModifier_Command | kModifier_Shift))) { IClickable* pasteName = nullptr; if (gHoveredUIControl != nullptr) pasteName = gHoveredUIControl; else if (gHoveredModule != nullptr) pasteName = gHoveredModule; if (pasteName != nullptr) { if (mCaretPosition != mCaretPosition2) RemoveSelectedText(); std::string insert = pasteName->Path(); AddString(insert); } } else if ((toupper(key) == 'C' || toupper(key) == 'X') && GetKeyModifiers() == kModifier_Command) { if (mCaretPosition != mCaretPosition2) { int caretStart = MIN(mCaretPosition, mCaretPosition2); int caretEnd = MAX(mCaretPosition, mCaretPosition2); TheSynth->CopyTextToClipboard(mString.substr(caretStart, caretEnd - caretStart)); if (toupper(key) == 'X') RemoveSelectedText(); } } else if (toupper(key) == 'Z' && GetKeyModifiers() == kModifier_Command) { Undo(); } else if (toupper(key) == 'Z' && (GetKeyModifiers() == (kModifier_Command | kModifier_Shift))) { Redo(); } else if (toupper(key) == 'A' && GetKeyModifiers() == kModifier_Command) { mCaretPosition = 0; mCaretPosition2 = (int)mString.size(); } else if (key == juce::KeyPress::endKey) { MoveCaretToEnd(); } else if (key == juce::KeyPress::homeKey) { MoveCaretToStart(); } else if (toupper(key) == 'R' && GetKeyModifiers() == kModifier_Command) { Publish(); mListener->ExecuteCode(); } else if (toupper(key) == 'R' && GetKeyModifiers() == (kModifier_Command | kModifier_Shift)) { Publish(); int lineStart = MIN(GetCaretCoords(mCaretPosition).y, GetCaretCoords(mCaretPosition2).y); int lineEnd = MAX(GetCaretCoords(mCaretPosition).y, GetCaretCoords(mCaretPosition2).y); std::pair<int, int> ranLines = mListener->ExecuteBlock(lineStart, lineEnd); mLastPublishedLineStart = ranLines.first; mLastPublishedLineEnd = ranLines.second; } else if (key < CHAR_MAX) { AddCharacter((char)key); } } void CodeEntry::AcceptAutocompletion() { AddString(mAutocompletes[mAutocompleteHighlightIndex].autocompleteRest); mAutocompleteUpdateTimer = 0; mWantToShowAutocomplete = false; } void CodeEntry::Publish() { mPublishedString = mString; mLastPublishTime = gTime; mLastPublishedLineStart = 0; mLastPublishedLineEnd = (int)GetLines(true).size(); OnCodeUpdated(); } void CodeEntry::Undo() { if (mUndosLeft > 0) { int size = (int)mUndoBuffer.size(); mUndoBufferPos = (mUndoBufferPos - 1 + size) % size; --mUndosLeft; mRedosLeft = MIN(mRedosLeft + 1, size); mString = mUndoBuffer[mUndoBufferPos].mString; mCaretPosition = mUndoBuffer[mUndoBufferPos].mCaretPos; mCaretPosition2 = mUndoBuffer[mUndoBufferPos].mCaretPos; OnCodeUpdated(); } } void CodeEntry::Redo() { if (mRedosLeft > 0) { int size = (int)mUndoBuffer.size(); mUndoBufferPos = (mUndoBufferPos + 1) % size; --mRedosLeft; mUndosLeft = MIN(mUndosLeft + 1, size); mString = mUndoBuffer[mUndoBufferPos].mString; mCaretPosition = mUndoBuffer[mUndoBufferPos].mCaretPos; mCaretPosition2 = mUndoBuffer[mUndoBufferPos].mCaretPos; OnCodeUpdated(); } } void CodeEntry::UpdateString(std::string newString) { mUndoBuffer[mUndoBufferPos].mCaretPos = mCaretPosition; mString = newString; int size = (int)mUndoBuffer.size(); mRedosLeft = 0; mUndosLeft = MIN(mUndosLeft + 1, size); mUndoBufferPos = (mUndoBufferPos + 1) % size; mUndoBuffer[mUndoBufferPos].mString = mString; OnCodeUpdated(); } void CodeEntry::AddCharacter(char c) { if (AllowCharacter(c)) { std::string s; s += c; AddString(s); mAutocompleteUpdateTimer = .2f; } } void CodeEntry::AddString(std::string s) { if (mCaretPosition != mCaretPosition2) RemoveSelectedText(); std::string toAdd; for (int i = 0; i < s.size(); ++i) { if (AllowCharacter(s[i])) toAdd += s[i]; } UpdateString(mString.substr(0, mCaretPosition) + toAdd + mString.substr(mCaretPosition)); MoveCaret(mCaretPosition + (int)toAdd.size(), false); } bool CodeEntry::AllowCharacter(char c) { if (c == '\n') return true; return juce::CharacterFunctions::isPrintable(c); } void CodeEntry::RemoveSelectedText() { int caretStart = MIN(mCaretPosition, mCaretPosition2); int caretEnd = MAX(mCaretPosition, mCaretPosition2); UpdateString(mString.substr(0, caretStart) + mString.substr(caretEnd)); MoveCaret(caretStart, false); } void CodeEntry::ShiftLines(bool backwards) { int caretStart = MIN(mCaretPosition, mCaretPosition2); int caretEnd = MAX(mCaretPosition, mCaretPosition2); ofVec2f coordsStart = GetCaretCoords(caretStart); ofVec2f coordsEnd = GetCaretCoords(caretEnd); auto lines = GetLines(false); std::string newString = ""; for (size_t i = 0; i < lines.size(); ++i) { if (i >= coordsStart.y && i <= coordsEnd.y) { int numSpaces = 0; for (size_t j = 0; j < lines[i].size(); ++j) { if (lines[i][j] != ' ') break; ++numSpaces; } if (backwards) { int charsToRemove = numSpaces % kTabSize; if (charsToRemove == 0) charsToRemove = kTabSize; if (charsToRemove > numSpaces) charsToRemove = numSpaces; lines[i] = lines[i].substr(charsToRemove); if (i == coordsStart.y) caretStart = (int)newString.size() + numSpaces - charsToRemove; if (i == coordsEnd.y) caretEnd = (int)newString.size() + (int)lines[i].size(); } else { int spacesNeeded = kTabSize - (int)numSpaces % kTabSize; for (int j = 0; j < spacesNeeded; ++j) lines[i] = " " + lines[i]; if (i == coordsStart.y) caretStart = (int)newString.size() + numSpaces + spacesNeeded; if (i == coordsEnd.y) caretEnd = (int)newString.size() + (int)lines[i].size(); } } newString += lines[i] + "\n"; } UpdateString(newString); mCaretPosition = caretStart; mCaretPosition2 = caretEnd; } void CodeEntry::MoveCaret(int pos, bool allowSelection /*=true*/) { mCaretPosition = pos; if (!allowSelection || !(GetKeyModifiers() & kModifier_Shift)) mCaretPosition2 = mCaretPosition; mCaretBlink = true; mCaretBlinkTimer = 0; } void CodeEntry::MoveCaretToStart() { ofVec2f coords = GetCaretCoords(mCaretPosition); auto lines = GetLines(false); int x = 0; if (coords.y < lines.size()) { for (size_t i = 0; i < lines[coords.y].size(); ++i) { if (lines[coords.y][i] == ' ') ++x; else break; } } if (x == coords.x) x = 0; MoveCaret(GetCaretPosition(x, coords.y)); } void CodeEntry::MoveCaretToEnd() { ofVec2f coords = GetCaretCoords(mCaretPosition); MoveCaret(GetCaretPosition(9999, coords.y)); } void CodeEntry::MoveCaretToNextToken(bool backwards) { //eh... just move it more for now ofVec2f coords = GetCaretCoords(mCaretPosition); int amount = 5; if (backwards) amount *= -1; MoveCaret(GetCaretPosition(MAX(0, coords.x + amount), coords.y)); } bool CodeEntry::MouseMoved(float x, float y) { mHovered = TestHover(x, y); CheckHover(x, y); return false; } bool CodeEntry::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) { if (fabs(scrollX) > fabsf(scrollY)) scrollY = 0; else scrollX = 0; mScroll.x = MAX(mScroll.x - scrollX * 10, 0); mScroll.y = MAX(mScroll.y - scrollY * 10, 0); OnCodeUpdated(); mWantToShowAutocomplete = false; return false; } void CodeEntry::SetDimensions(float width, float height) { mWidth = width; mHeight = height; OnCodeUpdated(); } int CodeEntry::GetCaretPosition(int col, int row) { auto lines = GetLines(false); int caretPos = 0; for (size_t i = 0; i < row && i < lines.size(); ++i) caretPos += lines[i].length() + 1; if (row >= 0 && row < (int)lines.size()) caretPos += MIN(col, lines[row].length()); return MIN(caretPos, (int)mString.length()); } int CodeEntry::GetColForX(float x) { x -= 2; x += mScroll.x; if (x < 0) x = 0; return round(x / mCharWidth); } int CodeEntry::GetRowForY(float y) { y -= 2; y += mScroll.y; if (y < 0) y = 0; return int(y / mCharHeight); } ofVec2f CodeEntry::GetLinePos(int lineNum, bool end, bool published /*= true*/) { float x = mX - mScroll.x; float y = lineNum * mCharHeight + mY - mScroll.y; if (end) { std::string str = published ? mPublishedString : mString; auto lines = ofSplitString(str, "\n"); if (lineNum < (int)lines.size()) x += lines[lineNum].length() * mCharWidth; } return ofVec2f(x, y); } ofVec2f CodeEntry::GetCaretCoords(int caret) { ofVec2f coords; int caretRemaining = caret; auto lines = GetLines(false); for (size_t i = 0; i < lines.size(); ++i) { if (caretRemaining >= lines[i].length() + 1) { caretRemaining -= lines[i].length() + 1; ++coords.y; } else { coords.x = caretRemaining; break; } } return coords; } namespace { const int kSaveStateRev = 0; } void CodeEntry::SaveState(FileStreamOut& out) { out << kSaveStateRev; out << mString; } void CodeEntry::LoadState(FileStreamIn& in, bool shouldSetValue) { int rev; in >> rev; LoadStateValidate(rev <= kSaveStateRev); std::string var; in >> var; if (shouldSetValue) { UpdateString(var); //Publish(); //if (mListener != nullptr) // mListener->ExecuteCode(mString); } } void CodeEntry::SetStyleFromJSON(const ofxJSONElement& vdict) { auto fs = vdict.get("font-size", 14); auto fsi = fs.asInt(); if (fsi > 4 && fsi < 200) mFontSize = fsi - 2; auto fromRGB = [vdict](const std::string& key, ofColor& onto) { auto def = Json::Value(Json::arrayValue); def[0u] = 255; def[1u] = 0; def[2u] = 0; auto arr = vdict.get(key, def); if (def.size() < 3) { onto.r = 255; onto.g = 0; onto.b = 0; } else { try { onto.r = arr[0u].asInt(); onto.g = arr[1u].asInt(); onto.b = arr[2u].asInt(); if (def.size() > 3) onto.a = arr[3u].asInt(); } catch (Json::LogicError& e) { TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } } }; fromRGB("currentBg", currentBg); fromRGB("publishedBg", publishedBg); fromRGB("unpublishedBg", unpublishedBg); fromRGB("string", stringColor); fromRGB("number", numberColor); fromRGB("name1", name1Color); fromRGB("name2", name2Color); fromRGB("name3", name3Color); fromRGB("defined", definedColor); fromRGB("equals", equalsColor); fromRGB("paren", parenColor); fromRGB("brace", braceColor); fromRGB("bracket", bracketColor); fromRGB("op", opColor); fromRGB("comma", commaColor); fromRGB("comment", commentColor); fromRGB("selectedOverlay", selectedOverlay); fromRGB("jediBg", jediBg); fromRGB("jediIndexBg", jediIndexBg); fromRGB("jediAutoComplete", jediAutoComplete); fromRGB("jediAutoCompleteRest", jediAutoCompleteRest); fromRGB("jediParams", jediParams); fromRGB("jediParamsHighlight", jediParamsHighlight); } ```
/content/code_sandbox/Source/CodeEntry.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
11,326
```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 **/ // // ScaleDegree.h // Bespoke // // Created by Ryan Challinor on 4/5/16. // // #pragma once #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "Checkbox.h" #include "DropdownList.h" class ScaleDegree : public NoteEffectBase, public IDrawableModule, public IDropdownListener { public: ScaleDegree(); static IDrawableModule* Create() { return new ScaleDegree(); } 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 CheckboxUpdated(Checkbox* checkbox, double time) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: struct NoteInfo { int mOn{ false }; int mVelocity{ 0 }; int mVoiceIdx{ -1 }; int mOutputPitch{ 0 }; }; int TransformPitch(int pitch); //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override { width = mWidth; height = mHeight; } float mWidth{ 200 }; float mHeight{ 20 }; int mScaleDegree{ 0 }; DropdownList* mScaleDegreeSelector{ nullptr }; std::array<NoteInfo, 128> mInputNotes{}; Checkbox* mRetriggerCheckbox{ nullptr }; bool mRetrigger{ false }; Checkbox* mDiatonicCheckbox{ nullptr }; bool mDiatonic{ true }; }; ```
/content/code_sandbox/Source/ScaleDegree.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
555
```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 **/ // // MultiBandTracker.cpp // modularSynth // // Created by Ryan Challinor on 2/28/14. // // #include "MultiBandTracker.h" #include "SynthGlobals.h" #include "Profiler.h" MultiBandTracker::MultiBandTracker() { SetNumBands(8); mWorkBuffer = new float[gBufferSize]; } MultiBandTracker::~MultiBandTracker() { delete[] mWorkBuffer; } void MultiBandTracker::SetRange(float minFreq, float maxFreq) { for (int i = 0; i < mNumBands; ++i) { float a = float(i) / mNumBands; float f = mMinFreq * powf(mMaxFreq / mMinFreq, a); mBands[i].SetCrossoverFreq(f); } } void MultiBandTracker::SetNumBands(int numBands) { mMutex.lock(); mNumBands = numBands; mBands.resize(numBands); mPeaks.resize(numBands); SetRange(mMinFreq, mMaxFreq); mMutex.unlock(); } void MultiBandTracker::Process(float* buffer, int bufferSize) { PROFILER(MultiBandTracker); mMutex.lock(); for (int i = 0; i < bufferSize; ++i) { float lower; float highLeftover = buffer[i]; for (int j = 0; j < mNumBands; ++j) { mBands[j].ProcessSample(highLeftover, lower, highLeftover); mPeaks[j].Process(&lower, 1); } } mMutex.unlock(); } float MultiBandTracker::GetBand(int idx) { return mPeaks[idx].GetPeak(); } ```
/content/code_sandbox/Source/MultiBandTracker.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
483
```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 **/ /* ============================================================================== NoteHocket.cpp Created: 19 Dec 2019 10:40:58pm Author: Ryan Challinor ============================================================================== */ #include "NoteHocket.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "ModularSynth.h" #include "PatchCableSource.h" #include "UIControlMacros.h" NoteHocket::NoteHocket() { for (int i = 0; i < 128; ++i) mLastNoteDestinations[i] = -1; for (int i = 0; i < kMaxDestinations; ++i) mWeight[i] = (i == 0) ? 1 : 0; Reseed(); } void NoteHocket::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); for (int i = 0; i < kMaxDestinations; ++i) { FLOATSLIDER(mWeightSlider[i], ("weight " + ofToString(i)).c_str(), &mWeight[i], 0, 1); } 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, ">"); ENDUIBLOCK(mWidth, mHeight); mWidth = 121; GetPatchCableSource()->SetEnabled(false); mSeedEntry->DrawLabel(true); mPrevSeedButton->PositionTo(mSeedEntry, kAnchor_Right); mReseedButton->PositionTo(mPrevSeedButton, kAnchor_Right); mNextSeedButton->PositionTo(mReseedButton, kAnchor_Right); } void NoteHocket::DrawModule() { if (Minimized() || IsVisible() == false) return; for (int i = 0; i < kMaxDestinations; ++i) { mWeightSlider[i]->SetShowing(i < mNumDestinations); mWeightSlider[i]->Draw(); } 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 NoteHocket::AdjustHeight() { float deterministicPad = 45; if (!mDeterministic) deterministicPad = 3; float height = mNumDestinations * 17 + deterministicPad; mLengthSlider->Move(0, height - mHeight); mSeedEntry->Move(0, height - mHeight); mPrevSeedButton->Move(0, height - mHeight); mReseedButton->Move(0, height - mHeight); mNextSeedButton->Move(0, height - mHeight); mHeight = height; } void NoteHocket::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { int selectedDestination = 0; if (velocity > 0) { ComputeSliders(0); float totalWeight = 0; for (int i = 0; i < mNumDestinations; ++i) totalWeight += mWeight[i]; 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, randomIndex)) % 10000) / 10000.0f) * totalWeight; } else { random = ofRandom(totalWeight); } for (selectedDestination = 0; selectedDestination < mNumDestinations; ++selectedDestination) { if (random <= mWeight[selectedDestination] || selectedDestination == mNumDestinations - 1) break; random -= mWeight[selectedDestination]; } 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 NoteHocket::SendNoteToIndex(int index, double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { mDestinationCables[index]->PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); } void NoteHocket::Reseed() { mSeed = gRandom() % 10000; } void NoteHocket::SendCC(int control, int value, int voiceIdx) { SendCCOutput(control, value, voiceIdx); } void NoteHocket::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 NoteHocket::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadInt("num_outputs", moduleInfo, 5, 2, kMaxDestinations, K(isTextField)); mModuleSaveData.LoadBool("deterministic", moduleInfo, false); SetUpFromSaveData(); } void NoteHocket::SetUpFromSaveData() { mNumDestinations = mModuleSaveData.GetInt("num_outputs"); int oldNumItems = (int)mDestinationCables.size(); if (mNumDestinations > oldNumItems) { for (int i = oldNumItems; i < mNumDestinations; ++i) { mDestinationCables.push_back(new AdditionalNoteCable()); mDestinationCables[i]->SetPatchCableSource(new PatchCableSource(this, kConnectionType_Note)); mDestinationCables[i]->GetPatchCableSource()->SetOverrideCableDir(ofVec2f(1, 0), PatchCableSource::Side::kRight); AddPatchCableSource(mDestinationCables[i]->GetPatchCableSource()); ofRectangle rect = mWeightSlider[i]->GetRect(true); mDestinationCables[i]->GetPatchCableSource()->SetManualPosition(rect.getMaxX() + 10, rect.y + rect.height / 2); } } else if (mNumDestinations < oldNumItems) { for (int i = oldNumItems - 1; i >= mNumDestinations; --i) { RemovePatchCableSource(mDestinationCables[i]->GetPatchCableSource()); } mDestinationCables.resize(mNumDestinations); } mDeterministic = mModuleSaveData.GetBool("deterministic"); AdjustHeight(); } void NoteHocket::SaveLayout(ofxJSONElement& moduleInfo) { } ```
/content/code_sandbox/Source/NoteHocket.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,964
```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 **/ // // MidiOutput.cpp // Bespoke // // Created by Ryan Challinor on 5/24/15. // // #include "MidiOutput.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "FillSaveDropdown.h" #include "ModulationChain.h" #include "PolyphonyMgr.h" #include "MidiController.h" namespace { const int kGlobalModulationIdx = 16; } MidiOutputModule::MidiOutputModule() { mChannelModulations.resize(kGlobalModulationIdx + 1); } MidiOutputModule::~MidiOutputModule() { TheTransport->RemoveAudioPoller(this); } void MidiOutputModule::CreateUIControls() { IDrawableModule::CreateUIControls(); mControllerList = new DropdownList(this, "controller", 5, 5, &mControllerIndex); } void MidiOutputModule::Init() { IDrawableModule::Init(); InitController(); TheTransport->AddAudioPoller(this); } void MidiOutputModule::InitController() { MidiController* controller = TheSynth->FindMidiController(mModuleSaveData.GetString("controller")); if (controller) mDevice.ConnectOutput(controller->GetDeviceOut().c_str(), mModuleSaveData.GetInt("channel")); BuildControllerList(); const std::vector<std::string>& devices = mDevice.GetPortList(false); for (int i = 0; i < devices.size(); ++i) { if (strcmp(devices[i].c_str(), mDevice.Name()) == 0) mControllerIndex = i; } } void MidiOutputModule::DrawModule() { if (Minimized() || IsVisible() == false) return; mControllerList->Draw(); } void MidiOutputModule::BuildControllerList() { mControllerList->Clear(); const std::vector<std::string>& devices = mDevice.GetPortList(false); for (int i = 0; i < devices.size(); ++i) mControllerList->AddLabel(devices[i].c_str(), i); } void MidiOutputModule::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { int channel = voiceIdx + 1; if (voiceIdx == -1) channel = 1; channel = mUseVoiceAsChannel ? channel : mChannel; mDevice.SendNote(time, pitch, velocity, false, channel); int modIdx = channel - 1; if (voiceIdx == -1) modIdx = kGlobalModulationIdx; mChannelModulations[modIdx].mModulation = modulation; } void MidiOutputModule::SendCC(int control, int value, int voiceIdx /*=-1*/) { int channel = voiceIdx + 1; if (voiceIdx == -1) channel = 1; mDevice.SendCC(control, value, mUseVoiceAsChannel ? channel : mChannel); } void MidiOutputModule::OnTransportAdvanced(float amount) { for (int i = 0; i < mChannelModulations.size(); ++i) { ChannelModulations& mod = mChannelModulations[i]; int channel = i + 1; if (i == kGlobalModulationIdx) channel = 1; float bend = mod.mModulation.pitchBend ? mod.mModulation.pitchBend->GetValue(0) : 0; if (bend != mod.mLastPitchBend) { mod.mLastPitchBend = bend; mDevice.SendPitchBend((int)ofMap(bend, -mPitchBendRange, mPitchBendRange, 0, 16383, K(clamp)), channel); } float modWheel = mod.mModulation.modWheel ? mod.mModulation.modWheel->GetValue(0) : ModulationParameters::kDefaultModWheel; if (modWheel != mod.mLastModWheel) { mod.mLastModWheel = modWheel; mDevice.SendCC(mModwheelCC, modWheel * 127, channel); } float pressure = mod.mModulation.pressure ? mod.mModulation.pressure->GetValue(0) : ModulationParameters::kDefaultPressure; if (pressure != mod.mLastPressure) { mod.mLastPressure = pressure; mDevice.SendAftertouch(pressure * 127, channel); } } } void MidiOutputModule::DropdownUpdated(DropdownList* list, int oldVal, double time) { mDevice.ConnectOutput(mControllerIndex); } void MidiOutputModule::DropdownClicked(DropdownList* list) { BuildControllerList(); } void MidiOutputModule::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("controller", moduleInfo, "", FillDropdown<MidiController*>); mModuleSaveData.LoadInt("channel", moduleInfo, 1, 1, 16); mModuleSaveData.LoadBool("usevoiceaschannel", moduleInfo, false); mModuleSaveData.LoadFloat("pitchbendrange", moduleInfo, 2, 1, 96, K(isTextField)); mModuleSaveData.LoadInt("modwheelcc(1or74)", moduleInfo, 1, 0, 127, K(isTextField)); SetUpFromSaveData(); } void MidiOutputModule::SetUpFromSaveData() { InitController(); mChannel = mModuleSaveData.GetInt("channel"); mUseVoiceAsChannel = mModuleSaveData.GetBool("usevoiceaschannel"); mPitchBendRange = mModuleSaveData.GetFloat("pitchbendrange"); mModwheelCC = mModuleSaveData.GetInt("modwheelcc(1or74)"); } ```
/content/code_sandbox/Source/MidiOutput.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,339
```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 **/ // // BandVocoder.cpp // modularSynth // // Created by Ryan Challinor on 1/1/14. // // #include "BandVocoder.h" #include "ModularSynth.h" #include "Profiler.h" #include "UIControlMacros.h" BandVocoder::BandVocoder() : IAudioProcessor(gBufferSize) { mCarrierInputBuffer = new float[GetBuffer()->BufferSize()]; Clear(mCarrierInputBuffer, GetBuffer()->BufferSize()); mWorkBuffer = new float[GetBuffer()->BufferSize()]; Clear(mWorkBuffer, GetBuffer()->BufferSize()); mOutBuffer = new float[GetBuffer()->BufferSize()]; Clear(mOutBuffer, GetBuffer()->BufferSize()); for (int i = 0; i < VOCODER_MAX_BANDS; ++i) { mPeaks[i].SetDecayTime(mRingTime); mOutputPeaks[i].SetDecayTime(mRingTime); mPeaks[i].SetLimit(mMaxBand); mOutputPeaks[i].SetLimit(mMaxBand); } CalcFilters(); } void BandVocoder::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK0(); FLOATSLIDER(mInputSlider, "input", &mInputPreamp, 0.1f, 2); FLOATSLIDER(mCarrierSlider, "carrier", &mCarrierPreamp, .1f, 2); FLOATSLIDER(mVolumeSlider, "volume", &mVolume, .1f, 2); FLOATSLIDER(mDryWetSlider, "mix", &mDryWet, 0, 1); FLOATSLIDER(mMaxBandSlider, "max band", &mMaxBand, 0.001f, 1); FLOATSLIDER(mSpacingStyleSlider, "spacing", &mSpacingStyle, -1, 1); UIBLOCK_NEWCOLUMN(); INTSLIDER(mNumBandsSlider, "bands", &mNumBands, 2, VOCODER_MAX_BANDS); FLOATSLIDER(mFBaseSlider, "f base", &mFreqBase, 20, 300); FLOATSLIDER(mFRangeSlider, "f range", &mFreqRange, 0, gSampleRate / 2 - 1000); FLOATSLIDER_DIGITS(mQSlider, "q", &mQ, 20, 80, 3); FLOATSLIDER_DIGITS(mRingTimeSlider, "ring", &mRingTime, .0001f, .1f, 4); ENDUIBLOCK0(); mFRangeSlider->SetMode(FloatSlider::kSquare); } BandVocoder::~BandVocoder() { delete[] mCarrierInputBuffer; delete[] mWorkBuffer; } void BandVocoder::SetCarrierBuffer(float* carrier, int bufferSize) { assert(bufferSize == GetBuffer()->BufferSize()); BufferCopy(mCarrierInputBuffer, carrier, bufferSize); mCarrierDataSet = true; } void BandVocoder::Process(double time) { PROFILER(BandVocoder); 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; } ComputeSliders(0); float inputPreampSq = mInputPreamp * mInputPreamp; float carrierPreampSq = mCarrierPreamp * mCarrierPreamp; float volSq = mVolume * mVolume; int bufferSize = GetBuffer()->BufferSize(); Clear(mOutBuffer, bufferSize); Mult(GetBuffer()->GetChannel(0), inputPreampSq * 5, bufferSize); Mult(mCarrierInputBuffer, carrierPreampSq * 5, bufferSize); for (int i = 0; i < mNumBands; ++i) { //get modulator band BufferCopy(mWorkBuffer, GetBuffer()->GetChannel(0), bufferSize); mBiquadCarrier[i].Filter(mWorkBuffer, bufferSize); float oldPeak = mPeaks[i].GetPeak(); //calculate modulator band level mPeaks[i].Process(mWorkBuffer, bufferSize); //get carrier band BufferCopy(mWorkBuffer, mCarrierInputBuffer, bufferSize); mBiquadOut[i].Filter(mWorkBuffer, bufferSize); //multiply carrier band by modulator band level //Mult(mWorkBuffer, mPeaks[i].GetPeak(), bufferSize); for (int j = 0; j < bufferSize; ++j) mWorkBuffer[j] *= ofMap(j, 0, bufferSize, oldPeak, mPeaks[i].GetPeak()); //don't allow a band to go crazy /*mOutputPeaks[i].Process(mWorkBuffer, bufferSize); if (mOutputPeaks[i].GetPeak() > mMaxBand) Mult(mWorkBuffer, 1/mOutputPeaks[i].GetPeak(), bufferSize);*/ //accumulate output band into total output Add(mOutBuffer, mWorkBuffer, bufferSize); } Mult(mOutBuffer, mDryWet * volSq, bufferSize); Mult(GetBuffer()->GetChannel(0), (1 - mDryWet), bufferSize); Add(mOutBuffer, GetBuffer()->GetChannel(0), bufferSize); Add(target->GetBuffer()->GetChannel(0), mOutBuffer, bufferSize); GetVizBuffer()->WriteChunk(mOutBuffer, bufferSize, 0); GetBuffer()->Reset(); } void BandVocoder::DrawModule() { if (Minimized() || IsVisible() == false) return; mInputSlider->Draw(); mCarrierSlider->Draw(); mVolumeSlider->Draw(); mDryWetSlider->Draw(); mFBaseSlider->Draw(); mFRangeSlider->Draw(); mQSlider->Draw(); mNumBandsSlider->Draw(); mRingTimeSlider->Draw(); mMaxBandSlider->Draw(); mSpacingStyleSlider->Draw(); float w, h; GetModuleDimensions(w, h); auto PosForFreq = [](float freq) { return log2(freq / 20) / 10; }; ofSetColor(0, 255, 0); for (int i = 0; i < mNumBands; ++i) { float x = PosForFreq(mBiquadCarrier[i].mF) * w; ofLine(x, h, x, h - mPeaks[i].GetPeak() * 200); } auto FreqForPos = [](float pos) { return 20.0 * std::pow(2.0, pos * 10); }; ofSetColor(52, 204, 235, 70); ofSetLineWidth(1); for (int i = 0; i < mNumBands; ++i) { ofBeginShape(); const int kPixelStep = 1; for (int x = 0; x < w + kPixelStep; x += kPixelStep) { float freq = FreqForPos(x / w); if (freq < gSampleRate / 2) { float response = mBiquadCarrier[i].GetMagnitudeResponseAt(freq); ofVertex(x, (.5f - .666f * log10(response)) * h); } } ofEndShape(false); } if (!mCarrierDataSet) { ofPushStyle(); ofSetColor(255, 0, 0); DrawTextNormal("no vocodercarrier!", 5, h - 5); ofPopStyle(); } } void BandVocoder::CalcFilters() { for (int i = 0; i < mNumBands; ++i) { float a = float(i) / (mNumBands - 1); float freqMax = ofClamp(mFreqBase + mFreqRange, 0, gSampleRate / 2); float fExp = mFreqBase * powf(freqMax / mFreqBase, a); float fLin = ofLerp(mFreqBase, freqMax, a); float fBass = ofLerp(mFreqBase, freqMax, a * a * a * a); float f; if (mSpacingStyle >= 0) f = ofLerp(fExp, fLin, mSpacingStyle); else f = ofLerp(fExp, fBass, -mSpacingStyle); mBiquadCarrier[i].SetFilterType(kFilterType_Bandpass); mBiquadOut[i].SetFilterType(kFilterType_Bandpass); mBiquadCarrier[i].SetFilterParams(f, mQ); mBiquadOut[i].CopyCoeffFrom(mBiquadCarrier[i]); } } void BandVocoder::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) { for (int i = 0; i < VOCODER_MAX_BANDS; ++i) { mBiquadCarrier[i].Clear(); mBiquadOut[i].Clear(); } } } void BandVocoder::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mNumBandsSlider) { CalcFilters(); } } void BandVocoder::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mFBaseSlider || slider == mFRangeSlider || slider == mQSlider || slider == mSpacingStyleSlider) { CalcFilters(); } if (slider == mRingTimeSlider) { for (int i = 0; i < VOCODER_MAX_BANDS; ++i) { mPeaks[i].SetDecayTime(mRingTime); mOutputPeaks[i].SetDecayTime(mRingTime); } } if (slider == mMaxBandSlider) { for (int i = 0; i < VOCODER_MAX_BANDS; ++i) { mPeaks[i].SetLimit(mMaxBand); mOutputPeaks[i].SetLimit(mMaxBand); } } } void BandVocoder::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void BandVocoder::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); } ```
/content/code_sandbox/Source/BandVocoder.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,468
```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 **/ /* ============================================================================== PulseDisplayer.cpp Created: 26 Jan 2023 Author: Ryan Challinor ============================================================================== */ #include "PulseDisplayer.h" #include "SynthGlobals.h" #include "Transport.h" PulseDisplayer::PulseDisplayer() { } PulseDisplayer::~PulseDisplayer() { } void PulseDisplayer::CreateUIControls() { IDrawableModule::CreateUIControls(); } void PulseDisplayer::DrawModule() { if (Minimized() || IsVisible() == false) return; float brightness = ofLerp(150, 255, 1 - ofClamp(gTime - mLastReceivedFlagTime, 0, 200) / 200.0f); ofPushStyle(); ofSetColor(brightness, brightness, brightness); std::string output; if (mLastReceivedFlags == kPulseFlag_None) output = "none"; if (mLastReceivedFlags & kPulseFlag_Reset) output += "reset "; if (mLastReceivedFlags & kPulseFlag_Random) output += "random "; if (mLastReceivedFlags & kPulseFlag_SyncToTransport) output += "sync "; if (mLastReceivedFlags & kPulseFlag_Backward) output += "backward "; if (mLastReceivedFlags & kPulseFlag_Align) output += "align "; if (mLastReceivedFlags & kPulseFlag_Repeat) output += "repeat "; DrawTextNormal(output, 5, 18); ofPopStyle(); } void PulseDisplayer::OnPulse(double time, float velocity, int flags) { mLastReceivedFlags = flags; mLastReceivedFlagTime = gTime; DispatchPulse(GetPatchCableSource(), time, velocity, flags); } void PulseDisplayer::GetModuleDimensions(float& width, float& height) { width = mWidth; height = mHeight; } void PulseDisplayer::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void PulseDisplayer::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/PulseDisplayer.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
590
```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 **/ /* ============================================================================== SpaceMouseControl.cpp Created: 25 Jan 2021 9:12:45pm Author: Ryan Challinor ============================================================================== */ #include "SpaceMouseControl.h" #if BESPOKE_SPACEMOUSE_SUPPORT #include "OpenFrameworksPort.h" #include "ModularSynth.h" #include <Windows.h> #include "3dxware/spwmacro.h" /* Common macros used by SpaceWare functions. */ #include "3dxware/si.h" /* Required for any SpaceWare support within an app.*/ #include "3dxware/siapp.h" /* Required for siapp.lib symbols */ #include "juce_core/juce_core.h" #ifdef _MSC_VER #pragma warning(disable : 4700) #endif struct SpaceMouseMessageWindow::Impl { Impl(ModularSynth& synth); ~Impl(); static LRESULT CALLBACK MyWndCBProc(HWND hwnd, UINT wm, WPARAM wParam, LPARAM lParam); int SbInit(HWND hwndC); void ApplyDeadZone(float& var, float deadzone); void SbMotionEvent(SiSpwEvent* pEvent); void SbZeroEvent(); void SbButtonPressEvent(int buttonnumber); void SbButtonReleaseEvent(int buttonnumber); void HandleDeviceChangeEvent(SiSpwEvent* pEvent); LPCTSTR getClassNameFromAtom() const noexcept; ATOM atom; HWND hwnd; SiHdl devHdl; /* Handle to 3D Mouse Device */ SiOpenData oData; ModularSynth& mSynth; bool mIsPanningOrZooming; bool mIsTwisting; static inline Impl* sInstance = nullptr; }; SpaceMouseMessageWindow::SpaceMouseMessageWindow(ModularSynth& theSynth) : d(std::make_unique<Impl>(theSynth)) { } SpaceMouseMessageWindow::Impl::Impl(ModularSynth& theSynth) : mSynth(theSynth) , mIsPanningOrZooming(false) , mIsTwisting(false) { for (int i = 0; i < juce::JUCEApplication::getCommandLineParameterArray().size(); ++i) { juce::String element = juce::JUCEApplication::getCommandLineParameterArray()[i]; if (element == "-nospacemouse") return; } sInstance = this; juce::String className("JUCE_"); className << juce::String::toHexString(juce::Time::getHighResolutionTicks()); HMODULE moduleHandle = (HMODULE)juce::Process::getCurrentModuleInstanceHandle(); WNDCLASSEX wc = { 0 }; wc.cbSize = sizeof(wc); wc.lpfnWndProc = MyWndCBProc; wc.cbWndExtra = 4; wc.hInstance = moduleHandle; wc.lpszClassName = (LPCSTR)className.toWideCharPointer(); atom = RegisterClassEx(&wc); jassert(atom != 0); hwnd = CreateWindow(getClassNameFromAtom(), "SpaceMouseReader", 0, 0, 0, 0, 0, 0, 0, moduleHandle, 0); jassert(hwnd != 0); /* Initialise 3DxWare access / call to SbInit() */ SbInit(hwnd); /* Implement message loop */ /*int bRet; MSG msg; //incoming message to be evaluated while (bRet = GetMessage(&msg, NULL, 0, 0)) { if (bRet == -1) { //handle the error and possibly exit return; } else { TranslateMessage(&msg); DispatchMessage(&msg); } }*/ } SpaceMouseMessageWindow::Impl::~Impl() { DestroyWindow(hwnd); UnregisterClass(getClassNameFromAtom(), 0); } //static LRESULT CALLBACK SpaceMouseMessageWindow::Impl::MyWndCBProc(HWND hwnd, UINT wm, WPARAM wParam, LPARAM lParam) { SiSpwEvent Event; // SpaceWare Event SiGetEventData EData; // SpaceWare Event Data // initialize Window platform specific data for a call to SiGetEvent SiGetEventWinInit(&EData, wm, wParam, lParam); // check whether wm was a 3D mouse event and process it //if (SiGetEvent (devHdl, SI_AVERAGE_EVENTS, &EData, &Event) == SI_IS_EVENT) SpwRetVal retval = SiGetEvent(sInstance->devHdl, 0, &EData, &Event); if (retval == SI_IS_EVENT) { if (Event.type == SI_MOTION_EVENT) { sInstance->SbMotionEvent(&Event); // process 3D mouse motion event } else if (Event.type == SI_ZERO_EVENT) { sInstance->SbZeroEvent(); // process 3D mouse zero event } else if (Event.type == SI_BUTTON_PRESS_EVENT) { sInstance->SbButtonPressEvent(Event.u.hwButtonEvent.buttonNumber); // process button press event } else if (Event.type == SI_BUTTON_RELEASE_EVENT) { sInstance->SbButtonReleaseEvent(Event.u.hwButtonEvent.buttonNumber); // process button release event } else if (Event.type == SI_DEVICE_CHANGE_EVENT) { //SbHandleDeviceChangeEvent(&Event); // process 3D mouse device change event } } return DefWindowProc(hwnd, wm, wParam, lParam); } int SpaceMouseMessageWindow::Impl::SbInit(HWND hwndC) { int res; /* result of SiOpen, to be returned */ /*init the SpaceWare input library */ if (SiInitialize() == SPW_DLL_LOAD_ERROR) { std::cout << "Error: Could not load SiAppDll dll files" << std::endl; } else { //std::cout << "SiInitialize() done " << std::endl; } SiOpenWinInit(&oData, hwndC); /* init Win. platform specific data */ /* open data, which will check for device type and return the device handle to be used by this function */ if ((devHdl = SiOpen("AppSpaceMouse.exe", SI_ANY_DEVICE, SI_NO_MASK, SI_EVENT, &oData)) == NULL) { std::cout << "SiOpen error:" << std::endl; SiTerminate(); /* called to shut down the SpaceWare input library */ std::cout << "SiTerminate()" << std::endl; res = 0; /* could not open device */ return res; } SiDeviceName pname; SiGetDeviceName(devHdl, &pname); //std::cout << "devicename = " << pname.name << std::endl; //SiSetUiMode(devHdl, SI_UI_ALL_CONTROLS); /* Config SoftButton Win Display */ SiGrabDevice(devHdl, SPW_TRUE); /* PREVENTS OTHER APPLICATIONS FROM RECEIVING 3D CONNEXION DATA !!! */ res = 1; /* opened device successfully */ return res; } void SpaceMouseMessageWindow::Impl::ApplyDeadZone(float& var, float deadzone) { if (abs(var) < deadzone) var = 0; else var -= (var > 0 ? 1 : -1) * deadzone; } void SpaceMouseMessageWindow::Impl::SbMotionEvent(SiSpwEvent* pEvent) { const float kMax = 2100.0f; float tx = ofClamp(pEvent->u.spwData.mData[SI_TX] / kMax, -1, 1); float ty = ofClamp(pEvent->u.spwData.mData[SI_TY] / kMax, -1, 1); float tz = ofClamp(pEvent->u.spwData.mData[SI_TZ] / kMax, -1, 1); float rx = ofClamp(pEvent->u.spwData.mData[SI_RX] / kMax, -1, 1); float ry = ofClamp(pEvent->u.spwData.mData[SI_RY] / kMax, -1, 1); float rz = ofClamp(pEvent->u.spwData.mData[SI_RZ] / kMax, -1, 1); float rawTwist = ry; float rawZoom = ty; ofVec2f rawPan(rz + tx, rx - tz); float panMag = sqrtf(tx * tx + tz * tz); float panAngle = atan2(-tz, tx); float tiltMag = sqrtf(rz * rz + rx * rx); float tiltAngle = atan2(rx, rz); const float kPanDeadZone = .15f; const float kTiltDeadZone = .15f; const float kTwistDeadZone = .15f; const float kZoomDownDeadZone = .2f; const float kZoomUpDeadZone = .05f; ApplyDeadZone(panMag, kPanDeadZone); ApplyDeadZone(tiltMag, kTiltDeadZone); ApplyDeadZone(ry, kTwistDeadZone); if (ty < 0) ApplyDeadZone(ty, kZoomDownDeadZone); else ApplyDeadZone(ty, kZoomUpDeadZone); const float kPow = 1.5f; panMag = pow(abs(panMag), kPow) * (panMag > 0 ? 1 : -1); tiltMag = pow(abs(tiltMag), kPow) * (tiltMag > 0 ? 1 : -1); ry = pow(abs(ry), kPow) * (ry > 0 ? 1 : -1); ty = pow(abs(ty), kPow) * (ty > 0 ? 1 : -1); tx = cos(panAngle) * panMag; tz = -sin(panAngle) * panMag; rz = cos(tiltAngle) * tiltMag; rx = sin(tiltAngle) * tiltMag; if (mIsTwisting) //if twisting, allow nothing else tx = ty = tz = rx = rz = 0; if (mIsPanningOrZooming) //if panning or zooming, allow no twisting ry = 0; //ofLog() << "TX=" << tx << " TY=" << ty << " TZ=" << tz << " RX=" << rx << " RY=" << ry << " RZ=" << rz; const float kPanScale = -42; const float kZoomScale = -.063f; const float kTwistScale = -3.0f; bool usingPan = false; bool usingZoom = false; bool usingTwist = false; if (rz != 0 || tx != 0 || rx != 0 || tz != 0) { mSynth.PanView((rz + tx) * kPanScale, (rx - tz) * kPanScale); usingPan = true; mIsPanningOrZooming = true; } if (ty != 0) { mSynth.ZoomView(ty * kZoomScale, false); usingZoom = true; mIsPanningOrZooming = true; } if (ry != 0) { mSynth.MouseScrolled(0, ry * kTwistScale, true, false, false); usingTwist = true; mIsTwisting = true; } if (!mIsTwisting) { mSynth.SetRawSpaceMouseTwist(0, false); mSynth.SetRawSpaceMouseZoom(rawZoom, usingZoom); mSynth.SetRawSpaceMousePan(rawPan.x, rawPan.y, usingPan); } if (!mIsPanningOrZooming) { mSynth.SetRawSpaceMouseTwist(rawTwist, usingTwist); mSynth.SetRawSpaceMouseZoom(0, false); mSynth.SetRawSpaceMousePan(0, 0, false); } } void SpaceMouseMessageWindow::Impl::SbZeroEvent() { mSynth.SetRawSpaceMouseTwist(0, false); mSynth.SetRawSpaceMouseZoom(0, false); mSynth.SetRawSpaceMousePan(0, 0, false); mIsPanningOrZooming = false; mIsTwisting = false; } void SpaceMouseMessageWindow::Impl::SbButtonPressEvent(int buttonnumber) { std::cout << "Buttonnumber : " << buttonnumber << std::endl; } void SpaceMouseMessageWindow::Impl::SbButtonReleaseEvent(int buttonnumber) { std::cout << "Buttonnumber : " << buttonnumber << std::endl; } void SpaceMouseMessageWindow::Impl::HandleDeviceChangeEvent(SiSpwEvent* pEvent) { std::cout << "HandleDeviceChangeEvent : " << std::endl; } void SpaceMouseMessageWindow::Poll() { int bRet; MSG msg; //incoming message to be evaluated while (PeekMessage(&msg, (HWND)0, 0, 0, PM_NOREMOVE)) { if (bRet = GetMessage(&msg, NULL, 0, 0)) { if (bRet == -1) { //handle the error and possibly exit return; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } else { break; } } } LPCTSTR SpaceMouseMessageWindow::Impl::getClassNameFromAtom() const noexcept { return (LPCTSTR)(juce::pointer_sized_uint)atom; } #else SpaceMouseMessageWindow::SpaceMouseMessageWindow(ModularSynth&) {} #endif // BESPOKE_SPACEMOUSE_SUPPORT SpaceMouseMessageWindow::~SpaceMouseMessageWindow() = default; ```
/content/code_sandbox/Source/SpaceMouseControl.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
3,166
```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 **/ // // StepSequencer.h // modularSynth // // Created by Ryan Challinor on 12/12/12. // // #pragma once #include <iostream> #include "Transport.h" #include "Checkbox.h" #include "UIGrid.h" #include "Slider.h" #include "GridController.h" #include "ClickButton.h" #include "DropdownList.h" #include "IDrawableModule.h" #include "INoteSource.h" #include "RadioButton.h" #include "SynthGlobals.h" #include "Push2Control.h" #include "IPulseReceiver.h" #include "TextEntry.h" #include "IDrivableSequencer.h" #define NUM_STEPSEQ_ROWS 16 #define META_STEP_MAX 64 class StepSequencer; class StepSequencerRow : public ITimeListener { public: StepSequencerRow(StepSequencer* seq, UIGrid* grid, int row); ~StepSequencerRow(); void CreateUIControls(); void OnTimeEvent(double time) override; void PlayStep(double time, int step); void SetOffset(float offset); void UpdateTimeListener(); void Draw(float x, float y); int GetRowPitch() const { return mRowPitch; } private: UIGrid* mGrid{ nullptr }; int mRow{ 0 }; StepSequencer* mSeq{ nullptr }; float mOffset{ 0 }; struct PlayedStep { int step{ 0 }; double time{ -1 }; }; std::array<PlayedStep, 5> mPlayedSteps{}; int mPlayedStepsRoundRobin{ 0 }; TextEntry* mRowPitchEntry{ nullptr }; int mRowPitch{ 0 }; }; class NoteRepeat : public ITimeListener { public: NoteRepeat(StepSequencer* seq, int note); ~NoteRepeat(); void OnTimeEvent(double time) override; void SetInterval(NoteInterval interval); void SetOffset(float offset); private: int mRow{ 0 }; StepSequencer* mSeq{ nullptr }; NoteInterval mInterval{ NoteInterval::kInterval_None }; float mOffset{ 0 }; }; class StepSequencerNoteFlusher : public ITimeListener { public: StepSequencerNoteFlusher(StepSequencer* seq); ~StepSequencerNoteFlusher(); void SetInterval(NoteInterval interval); void OnTimeEvent(double time) override; private: StepSequencer* mSeq; }; class StepSequencer : public IDrawableModule, public INoteSource, public ITimeListener, public IFloatSliderListener, public IGridControllerListener, public IButtonListener, public IDropdownListener, public INoteReceiver, public IRadioButtonListener, public IIntSliderListener, public IPush2GridController, public IPulseReceiver, public ITextEntryListener, public IDrivableSequencer { public: StepSequencer(); ~StepSequencer(); static IDrawableModule* Create() { return new StepSequencer(); } static bool AcceptsAudio() { return false; } static bool AcceptsNotes() { return true; } static bool AcceptsPulses() { return true; } void CreateUIControls() override; void Init() override; void Poll() override; void PlayStepNote(double time, int note, float val); void SetEnabled(bool enabled) override { mEnabled = enabled; } bool IsEnabled() const override { return mEnabled; } int GetPadPressure(int row) { return mPadPressures[row]; } NoteInterval GetStepInterval() const { return mStepInterval; } int GetStepNum(double time); void Flush(double time) { if (mEnabled) mNoteOutput.Flush(time); } int GetStep(int step, int pitch); void SetStep(int step, int pitch, int velocity); int GetRowPitch(int row) const { return mRows[row]->GetRowPitch(); } //INoteReceiver void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override; void SendPressure(int pitch, int pressure) override; void SendCC(int control, int value, int voiceIdx = -1) override {} //IPulseReceiver void OnPulse(double time, float velocity, int flags) override; //ITimeListener void OnTimeEvent(double time) override; //IGridControllerListener void OnControllerPageSelected() override; void OnGridButton(int x, int y, float velocity, IGridController* grid) override; //IDrawableModule bool IsResizable() const override { return true; } void Resize(float w, float h) override; //IClickable void MouseReleased() override; bool MouseMoved(float x, float y) override; //IPush2GridController bool OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue) override; void UpdatePush2Leds(Push2Control* push2) override; bool IsMetaStepActive(double time, int col, int row); //IDrivableSequencer bool HasExternalPulseSource() const override { return mHasExternalPulseSource; } void ResetExternalPulseSource() override { mHasExternalPulseSource = false; } void CheckboxUpdated(Checkbox* checkbox, 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 RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override; void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override; void TextEntryComplete(TextEntry* entry) 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 3; } private: //IDrawableModule void DrawModule() override; void GetModuleDimensions(float& width, float& height) override; void OnClicked(float x, float y, bool right) override; void Exit() override; void KeyPressed(int key, bool isRepeat) override; void UpdateLights(bool force = false); void UpdateVelocityLights(); void UpdateMetaLights(); void DrawRowLabel(const char* label, int row, int x, int y); int GetNumSteps(NoteInterval interval, int numMeasures) const; Vec2i ControllerToGrid(const Vec2i& controller); int GetNumControllerChunks(); //how many vertical chunks of the sequence are there to fit multi-rowed on the controller? int GetMetaStep(double time); int GetMetaStepMaskIndex(int col, int row) { return MIN(col, META_STEP_MAX - 1) + row * META_STEP_MAX; } GridColor GetGridColor(int x, int y); void Step(double time, float velocity, int pulseFlags); bool HasGridController(); int GetGridControllerRows(); int GetGridControllerCols(); void RandomizeRow(int row); struct HeldButton { HeldButton(int col, int row) { mCol = col; mRow = row; } int mCol{ 0 }; int mRow{ 0 }; }; enum class NoteInputMode { PlayStepIndex, RepeatHeld }; UIGrid* mGrid{ nullptr }; float mStrength{ 1 }; FloatSlider* mStrengthSlider{ nullptr }; int mGridYOff{ 0 }; ClickButton* mClearButton{ nullptr }; int mColorOffset{ 3 }; DropdownList* mGridYOffDropdown{ nullptr }; std::array<StepSequencerRow*, NUM_STEPSEQ_ROWS> mRows{}; bool mAdjustOffsets{ false }; Checkbox* mAdjustOffsetsCheckbox{ nullptr }; std::array<float, NUM_STEPSEQ_ROWS> mOffsets{}; std::array<FloatSlider*, NUM_STEPSEQ_ROWS> mOffsetSlider{}; std::array<ClickButton*, NUM_STEPSEQ_ROWS> mRandomizeRowButton{}; std::map<int, int> mPadPressures{}; NoteInterval mRepeatRate{ NoteInterval::kInterval_None }; DropdownList* mRepeatRateDropdown{ nullptr }; std::array<NoteRepeat*, NUM_STEPSEQ_ROWS> mNoteRepeats{}; int mNumRows{ 8 }; int mNumMeasures{ 1 }; IntSlider* mNumMeasuresSlider{ nullptr }; NoteInterval mStepInterval{ NoteInterval::kInterval_16n }; DropdownList* mStepIntervalDropdown{ nullptr }; GridControlTarget* mGridControlTarget{ nullptr }; GridControlTarget* mVelocityGridController{ nullptr }; GridControlTarget* mMetaStepGridController{ nullptr }; int mCurrentColumn{ 0 }; IntSlider* mCurrentColumnSlider{ nullptr }; StepSequencerNoteFlusher mFlusher; ClickButton* mShiftLeftButton{ nullptr }; ClickButton* mShiftRightButton{ nullptr }; std::list<HeldButton> mHeldButtons{}; juce::uint32* mMetaStepMasks; bool mIsSetUp{ false }; NoteInputMode mNoteInputMode{ NoteInputMode::PlayStepIndex }; bool mHasExternalPulseSource{ false }; bool mPush2Connected{ false }; float mRandomizationAmount{ 1 }; FloatSlider* mRandomizationAmountSlider{ nullptr }; float mRandomizationDensity{ .25 }; FloatSlider* mRandomizationDensitySlider{ nullptr }; ClickButton* mRandomizeButton{ nullptr }; TransportListenerInfo* mTransportListenerInfo{ nullptr }; }; ```
/content/code_sandbox/Source/StepSequencer.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,301
```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 **/ // // Arpeggiator.cpp // modularSynth // // Created by Ryan Challinor on 12/2/12. // // #include "Arpeggiator.h" #include "OpenFrameworksPort.h" #include "Scale.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "UIControlMacros.h" Arpeggiator::Arpeggiator() { TheScale->AddListener(this); } void Arpeggiator::Init() { IDrawableModule::Init(); mTransportListenerInfo = TheTransport->AddListener(this, mInterval, OffsetInfo(0, true), true); } void Arpeggiator::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK(3, 20, 140); DROPDOWN(mIntervalSelector, "interval", (int*)(&mInterval), 50); INTSLIDER(mArpStepSlider, "step", &mArpStep, -3, 3); INTSLIDER(mOctaveRepeatsSlider, "octaves", &mOctaveRepeats, 1, 4); ENDUIBLOCK(mWidth, mHeight); 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); } Arpeggiator::~Arpeggiator() { TheTransport->RemoveListener(this); TheScale->RemoveListener(this); } void Arpeggiator::DrawModule() { if (Minimized() || IsVisible() == false) return; ofSetColor(255, 255, 255, gModuleDrawAlpha); mIntervalSelector->Draw(); mArpStepSlider->Draw(); mOctaveRepeatsSlider->Draw(); ofSetColor(200, 200, 200, gModuleDrawAlpha); std::string chord; for (int i = 0; i < mChord.size(); ++i) chord += GetArpNoteDisplay(mChord[i].pitch) + " "; DrawTextNormal(chord, 5, 16); ofSetColor(0, 255, 0, gModuleDrawAlpha); std::string pad; for (int i = 0; i < mChord.size(); ++i) { if (i != mArpIndex) { pad += GetArpNoteDisplay(mChord[i].pitch) + " "; } else { float w = gFont.GetStringWidth(pad, 13); DrawTextNormal(GetArpNoteDisplay(mChord[i].pitch), 6 + w, 16); break; } } } void Arpeggiator::OnScaleChanged() { mChordMutex.lock(); mChord.clear(); mChordMutex.unlock(); } std::string Arpeggiator::GetArpNoteDisplay(int pitch) { return NoteName(pitch, false, true); } void Arpeggiator::OnClicked(float x, float y, bool right) { IDrawableModule::OnClicked(x, y, right); } void Arpeggiator::MouseReleased() { IDrawableModule::MouseReleased(); } bool Arpeggiator::MouseMoved(float x, float y) { IDrawableModule::MouseMoved(x, y); return false; } void Arpeggiator::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) { mChordMutex.lock(); mChord.clear(); mChordMutex.unlock(); mNoteOutput.Flush(time); } } void Arpeggiator::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (!mEnabled || pitch < 0 || pitch >= 128) { PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); return; } if (velocity > 0 && !mInputNotes[pitch]) { mChordMutex.lock(); mChord.push_back(ArpNote(pitch, velocity, voiceIdx, modulation)); mChordMutex.unlock(); } if (velocity == 0 && mInputNotes[pitch]) { mChordMutex.lock(); for (auto iter = mChord.begin(); iter != mChord.end(); ++iter) { if (iter->pitch == pitch) { mChord.erase(iter); break; } } mChordMutex.unlock(); } mInputNotes[pitch] = velocity > 0; } void Arpeggiator::OnTimeEvent(double time) { if (!mEnabled) return; if (mChord.size() == 0) { if (mLastPitch != -1) PlayNoteOutput(time, mLastPitch, 0, -1); mLastPitch = -1; return; } if (mArpStep != 0) { mArpIndex += mArpStep; if (mChord.size() > 0) { while (mArpIndex >= (int)mChord.size()) { mArpIndex -= mChord.size(); mCurrentOctaveOffset = (mCurrentOctaveOffset + 1) % mOctaveRepeats; } while (mArpIndex < 0) { mArpIndex += mChord.size(); mCurrentOctaveOffset = (mCurrentOctaveOffset - 1 + mOctaveRepeats) % mOctaveRepeats; } } } else //pingpong { assert(mArpPingPongDirection == 1 || mArpPingPongDirection == -1); mArpIndex += mArpPingPongDirection; if (mChord.size() >= 2) { if (mArpIndex < 0) { mArpIndex = 1; mArpPingPongDirection = 1; } if (mArpIndex > mChord.size() - 1) { mArpIndex = (int)mChord.size() - 2; mArpPingPongDirection = -1; } } else { mArpIndex = ofClamp(mArpIndex, 0, mChord.size() - 1); } } int offPitch = -1; if (mLastPitch >= 0) { offPitch = mLastPitch; } if (mChord.size()) { ArpNote current = mChord[mArpIndex]; int outPitch = current.pitch; outPitch += mCurrentOctaveOffset * TheScale->GetPitchesPerOctave(); if (mLastPitch == outPitch) //same note, play noteoff first { PlayNoteOutput(time, mLastPitch, 0, -1); offPitch = -1; } float pressure = current.modulation.pressure ? current.modulation.pressure->GetValue(0) : 0; PlayNoteOutput(time, outPitch, ofClamp(current.vel + 127 * pressure, 0, 127), current.voiceIdx, current.modulation); mLastPitch = outPitch; } if (offPitch != -1) { PlayNoteOutput(time, offPitch, 0, -1); if (offPitch == mLastPitch) mLastPitch = -1; } } void Arpeggiator::UpdateInterval() { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) transportListenerInfo->mInterval = mInterval; } void Arpeggiator::ButtonClicked(ClickButton* button, double time) { } void Arpeggiator::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mIntervalSelector) UpdateInterval(); } void Arpeggiator::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mArpStepSlider) { if (oldVal > 0) mArpPingPongDirection = 1; else if (oldVal < 0) mArpPingPongDirection = -1; } } void Arpeggiator::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void Arpeggiator::SetUpFromSaveData() { SetUpPatchCables(mModuleSaveData.GetString("target")); } ```
/content/code_sandbox/Source/Arpeggiator.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,131
```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 **/ // // ArrangementController.h // Bespoke // // Created by Ryan Challinor on 8/26/14. // // #pragma once class ArrangementController { public: static int mPlayhead; static bool mPlay; static int mSampleLength; }; ```
/content/code_sandbox/Source/ArrangementController.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
158
```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 **/ // // PitchShifter.h // Bespoke // // Created by Ryan Challinor on 3/21/15. // // #pragma once #include "FFT.h" #include "RollingBuffer.h" #define MAX_FRAME_LENGTH 8192 class PitchShifter { public: PitchShifter(int fftBins); virtual ~PitchShifter(); void Process(float* buffer, int bufferSize); void SetRatio(float ratio) { mRatio = ratio; } void SetOversampling(int oversampling) { mOversampling = oversampling; } int GetLatency() const { return mLatency; } private: int mFFTBins; FFTData mFFTData; float* mLastPhase{ nullptr }; float* mSumPhase{ nullptr }; float* mWindower{ nullptr }; float* mAnalysisMag{ nullptr }; float* mAnalysisFreq{ nullptr }; float* mSynthesisMag{ nullptr }; float* mSynthesisFreq{ nullptr }; ::FFT mFFT; RollingBuffer mRollingInputBuffer; RollingBuffer mRollingOutputBuffer; float mRatio{ 1 }; int mOversampling{ 4 }; float mLatency{ 0 }; float gInFIFO[MAX_FRAME_LENGTH]{}; float gOutFIFO[MAX_FRAME_LENGTH]{}; float gFFTworksp[2 * MAX_FRAME_LENGTH]{}; float gLastPhase[MAX_FRAME_LENGTH / 2 + 1]{}; float gSumPhase[MAX_FRAME_LENGTH / 2 + 1]{}; float gOutputAccum[2 * MAX_FRAME_LENGTH]{}; float gAnaFreq[MAX_FRAME_LENGTH]{}; float gAnaMagn[MAX_FRAME_LENGTH]{}; float gSynFreq[MAX_FRAME_LENGTH]{}; float gSynMagn[MAX_FRAME_LENGTH]{}; long gRover{ false }; long gInit{ false }; }; ```
/content/code_sandbox/Source/PitchShifter.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
500
```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 **/ // // MidiClockIn.h // Bespoke // // Created by Ryan Challinor on 1/1/22. // // #pragma once #include <iostream> #include "MidiDevice.h" #include "IDrawableModule.h" #include "DropdownList.h" #include "Slider.h" class IAudioSource; //adapted from path_to_url class DelayLockedLoop { public: /** Reset the DLL with a time, period and rate */ inline void reset(double now, double period, double rate) { mE2 = period / rate; mT0 = now; mT1 = mT0 + mE2; } /** Update the DLL with the next timestamp */ inline void update(double time) { const double e = time - mT1; mT0 = mT1; mT1 += mB * e + mE2; mE2 += mC * e; } /** Set the dll's parameters. Bandwidth / Frequency */ inline void setParams(double bandwidth, double frequency) { SetLPF(bandwidth, frequency); } /** Return the difference in filtered time (mT1 - mT0) */ inline double timeDiff() { return (mT1 - mT0); } private: double mE2{ 0 }; double mT0{ 0 }; double mT1{ 0 }; double mB{ 0 }; double mC{ 0 }; inline void SetLPF(double bandwidth, double frequency) { double omega = 2.0 * juce::MathConstants<double>::pi * bandwidth / frequency; mB = juce::MathConstants<double>::sqrt2 * omega; mC = omega * omega; } }; class MidiClockIn : public IDrawableModule, public IDropdownListener, public MidiDeviceListener, public IFloatSliderListener, public IIntSliderListener { public: MidiClockIn(); virtual ~MidiClockIn(); static IDrawableModule* Create() { return new MidiClockIn(); } 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; } bool HasDebugDraw() const override { return true; } void OnMidiNote(MidiNote& note) override {} void OnMidiControl(MidiControl& control) override {} void OnMidi(const juce::MidiMessage& message) override; void DropdownUpdated(DropdownList* list, int oldVal, double time) override; void DropdownClicked(DropdownList* list) override; void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {} void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override {} virtual void LoadLayout(const ofxJSONElement& moduleInfo) override; virtual void SetUpFromSaveData() override; bool IsEnabled() const override { return mEnabled; } private: void InitDevice(); void BuildDeviceList(); float GetRoundedTempo(); //IDrawableModule void DrawModule() override; void DrawModuleUnclipped() override; void GetModuleDimensions(float& w, float& h) override { w = mWidth; h = mHeight; } float mWidth{ 200 }; float mHeight{ 20 }; enum class TempoRoundMode { kNone, kWhole, kHalf, kQuarter, kTenth }; static constexpr int kMaxHistory = 40; int mDeviceIndex{ -1 }; DropdownList* mDeviceList{ nullptr }; TempoRoundMode mTempoRoundMode{ TempoRoundMode::kWhole }; DropdownList* mTempoRoundModeList{ nullptr }; float mStartOffsetMs{ 0 }; FloatSlider* mStartOffsetMsSlider{ nullptr }; int mSmoothAmount{ kMaxHistory / 2 }; IntSlider* mSmoothAmountSlider{ nullptr }; bool mObeyClockStartStop{ true }; MidiDevice mDevice; std::array<float, kMaxHistory> mTempoHistory; int mTempoIdx{ -1 }; double mLastTimestamp{ -1 }; int mReceivedPulseCount{ 0 }; DelayLockedLoop mDelayLockedLoop; }; ```
/content/code_sandbox/Source/MidiClockIn.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,090
```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 **/ // // SampleFinder.cpp // modularSynth // // Created by Ryan Challinor on 1/20/13. // // #include "SampleFinder.h" #include "IAudioReceiver.h" #include "Sample.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "Profiler.h" SampleFinder::SampleFinder() { mWriteBuffer = new float[gBufferSize]; Clear(mWriteBuffer, gBufferSize); mSample = new Sample(); mSampleDrawer.SetSample(mSample); mSampleDrawer.SetPosition(5, 80); mSampleDrawer.SetDimensions(200, 40); } void SampleFinder::CreateUIControls() { IDrawableModule::CreateUIControls(); mVolumeSlider = new FloatSlider(this, "volume", 5, 20, 110, 15, &mVolume, 0, 2); mPlayCheckbox = new Checkbox(this, "play", 5, 60, &mPlay); mLoopCheckbox = new Checkbox(this, "loop", 60, 60, &mLoop); mEditCheckbox = new Checkbox(this, "edit", 100, 2, &mEditMode); mClipStartSlider = new IntSlider(this, "start", 5, 395, 900, 15, &mClipStart, 0, gSampleRate * 200); mClipEndSlider = new IntSlider(this, "end", 5, 410, 900, 15, &mClipEnd, 0, gSampleRate * 200); mNumBarsSlider = new IntSlider(this, "num bars", 215, 3, 220, 15, &mNumBars, 1, 16); mOffsetSlider = new FloatSlider(this, "offset", 215, 20, 110, 15, &mOffset, gSampleRate * -.5f, gSampleRate * .5f, 4); mWriteButton = new ClickButton(this, "write", 600, 50); mDoubleLengthButton = new ClickButton(this, "double", 600, 10); mHalveLengthButton = new ClickButton(this, "halve", 600, 28); mReverseCheckbox = new Checkbox(this, "reverse", 500, 10, &mReverse); } SampleFinder::~SampleFinder() { delete[] mWriteBuffer; delete mSample; } void SampleFinder::Process(double time) { PROFILER(SampleFinder); IAudioReceiver* target = GetTarget(); if (!mEnabled || target == nullptr || mSample == nullptr || mPlay == false) return; ComputeSliders(0); if (mWantWrite) { DoWrite(); mWantWrite = false; } int bufferSize = target->GetBuffer()->BufferSize(); float* out = target->GetBuffer()->GetChannel(0); assert(bufferSize == gBufferSize); float volSq = mVolume * mVolume; float speed = GetSpeed(); //TODO(Ryan) multichannel const float* data = mSample->Data()->GetChannel(0); int numSamples = mSample->LengthInSamples(); float sampleRateRatio = mSample->GetSampleRateRatio(); mPlayhead = TheTransport->GetMeasurePos(time) + (TheTransport->GetMeasure(time) % mNumBars); if (mReverse) mPlayhead = 1 - mPlayhead; mPlayhead /= mNumBars; mPlayhead *= mClipEnd - mClipStart; mPlayhead += mClipStart; mPlayhead += mOffset; for (int i = 0; i < bufferSize; ++i) { if (mPlayhead >= mClipEnd) mPlayhead -= (mClipEnd - mClipStart); if (mPlayhead < mClipStart) mPlayhead += (mClipEnd - mClipStart); int pos = int(mPlayhead); int posNext = int(mPlayhead) + 1; if (pos < numSamples) { float sample = pos < 0 ? 0 : data[pos]; float nextSample = posNext >= numSamples ? 0 : data[posNext]; float a = mPlayhead - pos; out[i] += ((1 - a) * sample + a * nextSample) * volSq; //interpolate } else { out[i] = 0; //fill the rest with zero } GetVizBuffer()->Write(out[i], 0); mPlayhead += speed * sampleRateRatio; } } void SampleFinder::DrawModule() { if (Minimized() || IsVisible() == false) return; mVolumeSlider->Draw(); mPlayCheckbox->Draw(); mLoopCheckbox->Draw(); mEditCheckbox->Draw(); if (mSample) { if (!mEditMode) { mSampleDrawer.SetDimensions(200, 40); mSampleDrawer.SetRange(mClipStart, mClipEnd); mSampleDrawer.Draw((int)mPlayhead); } else { mSampleDrawer.SetDimensions(900, 310); mSampleDrawer.SetRange(mZoomStart, mZoomEnd); mSampleDrawer.Draw((int)mPlayhead); mSampleDrawer.DrawLine(mClipStart, ofColor::red); mSampleDrawer.DrawLine(mClipEnd, ofColor::red); mClipStartSlider->Draw(); mClipEndSlider->Draw(); mNumBarsSlider->Draw(); mOffsetSlider->Draw(); mWriteButton->Draw(); mDoubleLengthButton->Draw(); mHalveLengthButton->Draw(); mReverseCheckbox->Draw(); DrawTextNormal(ofToString(mSample->GetPlayPosition()), 335, 50); DrawTextNormal("speed: " + ofToString(GetSpeed()), 4, 55); } } } bool SampleFinder::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) { ofVec2f bufferPos = ofVec2f(ofMap(x, 5, 5 + 900, 0, 1), ofMap(y, 80, 80 + 310, 0, 1)); if (IsInUnitBox(bufferPos)) { float zoomCenter = ofLerp(mZoomStart, mZoomEnd, bufferPos.x); float distFromStart = zoomCenter - mZoomStart; float distFromEnd = zoomCenter - mZoomEnd; distFromStart *= 1 - scrollY / 100; distFromEnd *= 1 - scrollY / 100; float slideX = (mZoomEnd - mZoomStart) * -scrollX / 300; mZoomStart = ofClamp(zoomCenter - distFromStart + slideX, 0, mSample->LengthInSamples()); mZoomEnd = ofClamp(zoomCenter - distFromEnd + slideX, 0, mSample->LengthInSamples()); UpdateZoomExtents(); return true; } return false; } void SampleFinder::FilesDropped(std::vector<std::string> files, int x, int y) { mSample->Reset(); mSample->Read(files[0].c_str()); mClipStart = 0; mClipEnd = mSample->LengthInSamples(); mZoomStart = 0; mZoomEnd = mClipEnd; UpdateZoomExtents(); } float SampleFinder::GetSpeed() { return float(mClipEnd - mClipStart) * gInvSampleRateMs / TheTransport->MsPerBar() / mNumBars * (mReverse ? -1 : 1); } void SampleFinder::DropdownClicked(DropdownList* list) { } void SampleFinder::DropdownUpdated(DropdownList* list, int oldVal, double time) { } void SampleFinder::UpdateSample() { } void SampleFinder::ButtonClicked(ClickButton* button, double time) { if (button == mWriteButton) { mWantWrite = true; } if (button == mDoubleLengthButton) { float newEnd = (mClipEnd - mClipStart) * 2 + mClipStart; if (newEnd < mSample->LengthInSamples()) { mClipEnd = newEnd; mNumBars *= 2; } } if (button == mHalveLengthButton) { if (mNumBars % 2 == 0) { float newEnd = (mClipEnd - mClipStart) / 2 + mClipStart; mClipEnd = newEnd; mNumBars /= 2; } } } void SampleFinder::DoWrite() { if (mSample) { mSample->ClipTo(mClipStart, mClipEnd); int shift = mOffset * (mClipEnd - mClipStart); if (shift < 0) shift += mClipEnd - mClipStart; mSample->ShiftWrap(shift); mSample->Write(ofGetTimestampString("loops/sample_%Y-%m-%d_%H-%M.wav").c_str()); mClipStart = 0; mClipEnd = mSample->LengthInSamples(); mOffset = 0; mZoomStart = 0; mZoomEnd = mClipEnd; UpdateZoomExtents(); } } void SampleFinder::UpdateZoomExtents() { mClipStartSlider->SetExtents(mZoomStart, mZoomEnd); mClipEndSlider->SetExtents(mZoomStart, mZoomEnd); } void SampleFinder::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mPlayCheckbox) { if (mSample) mSample->Reset(); } } void SampleFinder::GetModuleDimensions(float& width, float& height) { if (mEditMode) { width = 910; height = 430; } else { width = 210; height = 125; } } void SampleFinder::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { } void SampleFinder::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { if (slider == mClipStartSlider) { if (mSample && mClipStart > mSample->LengthInSamples()) mClipStart = mSample->LengthInSamples(); } if (slider == mClipEndSlider) { if (mSample && mClipEnd > mSample->LengthInSamples()) mClipEnd = mSample->LengthInSamples(); } } void SampleFinder::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (mSample) { mPlay = false; if (pitch == 16) { mSample->Reset(); } else if (pitch >= 0 && pitch < 16 && velocity > 0) { int slice = (pitch / 8) * 8 + 7 - (pitch % 8); int barLength = (mClipEnd - mClipStart) / mNumBars; int position = -mOffset * barLength + (barLength / 4) * slice + mClipStart; mSample->Play(time, 1, position); } } } void SampleFinder::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("target", moduleInfo); SetUpFromSaveData(); } void SampleFinder::SetUpFromSaveData() { SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); } ```
/content/code_sandbox/Source/SampleFinder.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
2,665
```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 **/ /* ============================================================================== NotePanAlternator.h Created: 25 Mar 2018 9:27:25pm Author: Ryan Challinor ============================================================================== */ #pragma once #include "NoteEffectBase.h" #include "IDrawableModule.h" #include "INoteSource.h" #include "Slider.h" class NotePanAlternator : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener { public: NotePanAlternator(); static IDrawableModule* Create() { return new NotePanAlternator(); } 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 = 40; } bool mFlip{ false }; float mPanOne{ -1 }; FloatSlider* mPanOneSlider{ nullptr }; float mPanTwo{ 1 }; FloatSlider* mPanTwoSlider{ nullptr }; }; ```
/content/code_sandbox/Source/NotePanAlternator.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
466
```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 **/ // // VSTPlugin.cpp // Bespoke // // Created by Ryan Challinor on 1/18/16. // // #include "VSTPlugin.h" #include "OpenFrameworksPort.h" #include "SynthGlobals.h" #include "IAudioReceiver.h" #include "ofxJSONElement.h" #include "ModularSynth.h" #include "Profiler.h" #include "Scale.h" #include "ModulationChain.h" #include "PatchCableSource.h" #include "UserPrefs.h" //#include "NSWindowOverlay.h" namespace { const int kGlobalModulationIdx = 16; const juce::String kInvalidPluginId = "--0-0"; //this is what's generated by juce's createIdentifierString() for an invalid PluginDescription juce::String GetFileNameWithoutExtension(const juce::String& fullPath) { auto lastSlash = fullPath.lastIndexOfChar('/') + 1; if (lastSlash == 0) lastSlash = fullPath.lastIndexOfChar('\\') + 1; auto lastDot = fullPath.lastIndexOfChar('.'); if (lastDot > lastSlash) return fullPath.substring(lastSlash, lastDot); return fullPath.substring(lastSlash); } } using namespace juce; namespace VSTLookup { struct PluginFormatSorter { explicit PluginFormatSorter(juce::String formatOrder) { mFormatOrder.addTokens(formatOrder, ";", ""); } int compareElements(const PluginDescription& first, const PluginDescription& second) const { int indexFirst = mFormatOrder.indexOf(first.pluginFormatName); int indexSecond = mFormatOrder.indexOf(second.pluginFormatName); if (indexFirst < 0) indexFirst = 999; if (indexSecond < 0) indexSecond = 999; int diff = indexFirst - indexSecond; if (diff == 0) diff = first.name.compareNatural(second.name, false); return diff; } juce::StringArray mFormatOrder; }; struct PluginNameSorter { int compareElements(const PluginDescription& first, const PluginDescription& second) const { return first.name.compareNatural(second.name, false); } }; void GetAvailableVSTs(std::vector<PluginDescription>& vsts) { vsts.clear(); static bool sFirstTime = true; if (sFirstTime) { auto file = juce::File(ofToDataPath("vst/found_vsts.xml")); if (file.existsAsFile()) { auto xml = juce::parseXML(file); TheSynth->GetKnownPluginList().recreateFromXml(*xml); } } auto types = TheSynth->GetKnownPluginList().getTypes(); std::string formatPreferenceOrder = UserPrefs.plugin_preference_order.Get(); bool allowDupes = formatPreferenceOrder.empty(); if (!allowDupes) { PluginFormatSorter formatSorter(formatPreferenceOrder); types.sort(formatSorter); } Array<PluginDescription> filtered; for (int i = 0; i < types.size(); ++i) { bool hasDupe = false; for (int j = 0; j < filtered.size(); ++j) { if (types[i].name == filtered[j].name) { hasDupe = true; break; } } if (!hasDupe || allowDupes) filtered.add(types[i]); } PluginNameSorter nameSorter; filtered.sort(nameSorter); for (int i = 0; i < filtered.size(); ++i) vsts.push_back(filtered[i]); //for (int i = 0; i < 2000; ++i) // vsts.insert(vsts.begin(), std::string("c:/a+") + ofToString(gRandom())); //SortByLastUsed(vsts); //add a bunch of duplicates to the list, to simulate a user with many VSTs /*auto vstCopy = vsts; for (int i = 0; i < 40; ++i) vsts.insert(vsts.end(), vstCopy.begin(), vstCopy.end());*/ sFirstTime = false; } void FillVSTList(DropdownList* list) { assert(list); std::vector<PluginDescription> vsts; GetAvailableVSTs(vsts); for (int i = 0; i < vsts.size(); ++i) list->AddLabel(vsts[i].createIdentifierString().toStdString(), i); } std::string GetVSTPath(std::string vstName) { if (juce::String(vstName).contains("/") || juce::String(vstName).contains("\\")) //already a path return vstName; vstName = GetFileNameWithoutExtension(vstName).toStdString(); auto types = TheSynth->GetKnownPluginList().getTypes(); for (int i = 0; i < types.size(); ++i) { #if BESPOKE_MAC if (types[i].pluginFormatName == juce::AudioUnitPluginFormat::getFormatName()) continue; //"fileOrIdentifier" is not a valid path, can't check #endif juce::File vst(types[i].fileOrIdentifier); if (vst.getFileNameWithoutExtension().toStdString() == vstName) return types[i].fileOrIdentifier.toStdString(); } return ""; } juce::String cutOffIdHash(juce::String inputString) { juce::StringArray parts; parts.addTokens(inputString, "-", ""); if (parts.size() >= 2) { parts.remove(parts.size() - 2); juce::String result = parts.joinIntoString("-"); return result; } return inputString; } bool GetPluginDesc(juce::PluginDescription& desc, juce::String pluginId) { auto types = TheSynth->GetKnownPluginList().getTypes(); auto cutId = cutOffIdHash(pluginId); for (int i = 0; i < types.size(); ++i) { if (types[i].createIdentifierString() == pluginId) { desc = types[i]; return true; } } for (int i = 0; i < types.size(); ++i) { if (cutOffIdHash(types[i].createIdentifierString()) == cutId) { desc = types[i]; return true; } } return false; } void GetRecentPlugins(std::vector<PluginDescription>& recentPlugins, int num) { recentPlugins.clear(); juce::PluginDescription pluginDesc{}; std::map<double, std::string> lastUsedTimes; int i = 0; if (juce::File(ofToDataPath("vst/recent_plugins.json")).existsAsFile()) { ofxJSONElement root; root.open(ofToDataPath("vst/recent_plugins.json")); ofxJSONElement jsonList = root["vsts"]; for (auto it = jsonList.begin(); it != jsonList.end(); ++it) { try { std::string id = it.key().asString(); double time = jsonList[id].asDouble(); lastUsedTimes.insert(std::make_pair(time, id)); } catch (Json::LogicError& e) { TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } } } std::map<double, std::string>::reverse_iterator rit; rit = lastUsedTimes.rbegin(); while (rit != lastUsedTimes.rend() && ++i <= num) { if (GetPluginDesc(pluginDesc, juce::String(rit->second))) { recentPlugins.push_back(pluginDesc); } ++rit; } } void SortByLastUsed(std::vector<juce::PluginDescription>& vsts) { std::map<std::string, double> lastUsedTimes; if (juce::File(ofToDataPath("vst/recent_plugins.json")).existsAsFile()) { ofxJSONElement root; root.open(ofToDataPath("vst/recent_plugins.json")); ofxJSONElement jsonList = root["vsts"]; for (auto it = jsonList.begin(); it != jsonList.end(); ++it) { try { std::string key = it.key().asString(); lastUsedTimes[key] = jsonList[key].asDouble(); } catch (Json::LogicError& e) { TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error); } } } std::sort(vsts.begin(), vsts.end(), [lastUsedTimes](juce::PluginDescription a, juce::PluginDescription b) { auto itA = lastUsedTimes.find(a.createIdentifierString().toStdString()); auto itB = lastUsedTimes.find(b.createIdentifierString().toStdString()); double timeA = 0; double timeB = 0; if (itA != lastUsedTimes.end()) timeA = (*itA).second; if (itB != lastUsedTimes.end()) timeB = (*itB).second; if (timeA == timeB) return a.name < b.name; return timeA > timeB; }); } } VSTPlugin::VSTPlugin() : IAudioProcessor(gBufferSize) { juce::File(ofToDataPath("vst")).createDirectory(); juce::File(ofToDataPath("vst/presets")).createDirectory(); mChannelModulations.resize(kGlobalModulationIdx + 1); mPluginName = "no plugin loaded"; } void VSTPlugin::CreateUIControls() { IDrawableModule::CreateUIControls(); mVolSlider = new FloatSlider(this, "vol", 3, 3, 80, 15, &mVol, 0, 4); mOpenEditorButton = new ClickButton(this, "open", mVolSlider, kAnchor_Right_Padded); mPresetFileSelector = new DropdownList(this, "preset", 3, 21, &mPresetFileIndex, 110); mSavePresetFileButton = new ClickButton(this, "save as", -1, -1); mShowParameterDropdown = new DropdownList(this, "show parameter", 3, 38, &mShowParameterIndex, 160); mPanicButton = new ClickButton(this, "panic", 166, 38); mPresetFileSelector->DrawLabel(true); mSavePresetFileButton->PositionTo(mPresetFileSelector, kAnchor_Right); mMidiOutCable = new AdditionalNoteCable(); mMidiOutCable->SetPatchCableSource(new PatchCableSource(this, kConnectionType_Note)); mMidiOutCable->GetPatchCableSource()->SetOverrideCableDir(ofVec2f(1, 0), PatchCableSource::Side::kRight); AddPatchCableSource(mMidiOutCable->GetPatchCableSource()); mMidiOutCable->GetPatchCableSource()->SetManualPosition(206 - 10, 10); if (mPlugin) { CreateParameterSliders(); } //const auto* editor = mPlugin->createEditor(); } VSTPlugin::~VSTPlugin() { } void VSTPlugin::Exit() { IDrawableModule::Exit(); if (mWindow) { mWindow.reset(); } if (mPlugin) { mPlugin.reset(); } } std::string VSTPlugin::GetTitleLabel() const { return GetPluginFormatName() + ": " + GetPluginName(); } std::string VSTPlugin::GetPluginName() const { return mPluginName; } std::string VSTPlugin::GetPluginFormatName() const { if (mPlugin) return mPluginFormatName; return "plugin"; } std::string VSTPlugin::GetPluginId() const { if (mPlugin) return mPluginId; return "no plugin loaded"; } void VSTPlugin::GetVSTFileDesc(std::string vstName, juce::PluginDescription& desc) { std::string path = VSTLookup::GetVSTPath(vstName); auto types = TheSynth->GetKnownPluginList().getTypes(); bool found = false; for (int i = 0; i < types.size(); ++i) { if (path == types[i].fileOrIdentifier) { found = true; desc = types[i]; break; } } if (!found) //couldn't find the VST at this path. maybe its installation got moved, or the bespoke state was saved on a different computer. try to find a VST of the same name. { juce::String desiredVstName = juce::String(path).replaceCharacter('\\', '/').fromLastOccurrenceOf("/", false, false).upToFirstOccurrenceOf(".", false, false); for (int i = 0; i < types.size(); ++i) { juce::String thisVstName = juce::String(types[i].fileOrIdentifier).replaceCharacter('\\', '/').fromLastOccurrenceOf("/", false, false).upToFirstOccurrenceOf(".", false, false); if (thisVstName == desiredVstName) { desc = types[i]; break; } } } } void VSTPlugin::SetVST(juce::PluginDescription pluginDesc) { ofLog() << "loading Plugin: " << pluginDesc.name << "; Format: " << pluginDesc.pluginFormatName << "; ID: " << pluginDesc.uniqueId; juce::String pluginId = pluginDesc.createIdentifierString(); std::string strPluginId = pluginId.toStdString(); if (strPluginId != kInvalidPluginId) mModuleSaveData.SetString("pluginId", strPluginId); else mModuleSaveData.SetString("pluginId", "none"); //mark VST as used if (strPluginId != kInvalidPluginId) { ofxJSONElement root; root.open(ofToDataPath("vst/recent_plugins.json")); auto time = juce::Time::getCurrentTime(); root["vsts"][strPluginId] = (double)time.currentTimeMillis(); root.save(ofToDataPath("vst/recent_plugins.json"), true); } if (mPlugin != nullptr && dynamic_cast<juce::AudioPluginInstance*>(mPlugin.get())->getPluginDescription().matchesIdentifierString(pluginId)) return; //this VST is already loaded! we're all set if (mPlugin != nullptr && mWindow != nullptr) { VSTWindow* window = mWindow.release(); delete window; //delete mWindowOverlay; //mWindowOverlay = nullptr; } LoadVST(pluginDesc); } void VSTPlugin::LoadVST(juce::PluginDescription desc) { mPluginReady = false; /*auto completionCallback = [this, &callbackDone] (std::unique_ptr<juce::AudioPluginInstance> instance, const String& error) { if (instance == nullptr) { ofLog() << error; } else { mVSTMutex.lock(); //instance->enableAllBuses(); instance->prepareToPlay(gSampleRate, gBufferSize); instance->setPlayHead(&mPlayhead); mNumInputChannels = CLAMP(instance->getTotalNumInputChannels(), 1, 4); mNumOutputChannels = CLAMP(instance->getTotalNumOutputChannels(), 1, 4); ofLog() << "vst inputs: " << mNumInputChannels << " vst outputs: " << mNumOutputChannels; mPlugin = std::move(instance); mVSTMutex.unlock(); } if (mPlugin != nullptr) CreateParameterSliders(); callbackDone = true; }; TheSynth->GetAudioPluginFormatManager().getFormat(i)->createPluginInstanceAsync(desc, gSampleRate, gBufferSize, completionCallback);*/ mVSTMutex.lock(); juce::String errorMessage; mPlugin = TheSynth->GetAudioPluginFormatManager().createPluginInstance(desc, gSampleRate, gBufferSize, errorMessage); if (mPlugin != nullptr) { mPlugin->enableAllBuses(); mPlugin->addListener(this); /* * For now, since Bespoke is at best stereo in stereo out, * Disable all non-main input and output buses */ mNumInputChannels = mPlugin->getTotalNumInputChannels(); mNumOutputChannels = mPlugin->getTotalNumOutputChannels(); ofLog() << "vst channel - inputs: " << mNumInputChannels << " x outputs: " << mNumOutputChannels; auto layouts = mPlugin->getBusesLayout(); mNumInBuses = layouts.inputBuses.size(); mNumOutBuses = layouts.outputBuses.size(); mPlugin->enableAllBuses(); ofLog() << "vst layout - inputs: " << layouts.inputBuses.size() << " x outputs: " << layouts.outputBuses.size(); mPlugin->prepareToPlay(gSampleRate, gBufferSize); mPlugin->setPlayHead(&mPlayhead); mPluginName = mPlugin->getName().toStdString(); mPluginFormatName = ofToString(desc.pluginFormatName.toLowerCase()); mPluginId = GetPluginName() + "_" + ofToString(desc.uniqueId); CreateParameterSliders(); RefreshPresetFiles(); mPluginReady = true; } else { TheSynth->LogEvent("error loading VST: " + errorMessage.toStdString(), kLogEventType_Error); if (mModuleSaveData.HasProperty("pluginId") && mModuleSaveData.GetString("pluginId").length() > 0) mPluginName = mModuleSaveData.GetString("pluginId") + " (not loaded)"; } mVSTMutex.unlock(); } void VSTPlugin::CreateParameterSliders() { assert(mPlugin); for (auto& slider : mParameterSliders) { if (slider.mSlider) { slider.mSlider->SetShowing(false); RemoveUIControl(slider.mSlider); slider.mSlider->Delete(); } } mParameterSliders.clear(); mShowParameterDropdown->Clear(); const auto& parameters = mPlugin->getParameters(); int numParameters = parameters.size(); mParameterSliders.resize(numParameters); for (int i = 0; i < numParameters; ++i) { mParameterSliders[i].mOwner = this; mParameterSliders[i].mValue = parameters[i]->getValue(); mParameterSliders[i].mParameter = parameters[i]; mParameterSliders[i].mDisplayName = parameters[i]->getName(64).toStdString(); HostedAudioProcessorParameter* parameterWithId = dynamic_cast<HostedAudioProcessorParameter*>(parameters[i]); if (parameterWithId) mParameterSliders[i].mID = "paramid_" + parameterWithId->getParameterID().toStdString(); else mParameterSliders[i].mID = "param_" + ofToString(parameters[i]->getParameterIndex()); mParameterSliders[i].mShowing = false; if (numParameters <= kMaxParametersInDropdown) //only show parameters in list if there are a small number. if there are many, make the user adjust them in the VST before they can be controlled { mShowParameterDropdown->AddLabel(mParameterSliders[i].mDisplayName.c_str(), i); mParameterSliders[i].mInSelectorList = true; } else { mParameterSliders[i].mInSelectorList = false; } } } void VSTPlugin::Poll() { if (mRescanParameterNames) { mRescanParameterNames = false; const auto& parameters = mPlugin->getParameters(); int numParameters = MIN(mParameterSliders.size(), parameters.size()); for (int i = 0; i < numParameters; ++i) { mParameterSliders[i].mDisplayName = parameters[i]->getName(64).toStdString(); if (mParameterSliders[i].mSlider != nullptr) mParameterSliders[i].mSlider->SetOverrideDisplayName(mParameterSliders[i].mDisplayName); } if (numParameters <= kMaxParametersInDropdown) // update the dropdown in this case { mShowParameterDropdown->Clear(); for (int i = 0; i < numParameters; ++i) { mShowParameterDropdown->AddLabel(mParameterSliders[i].mDisplayName.c_str(), i); mParameterSliders[i].mInSelectorList = true; } } } if (mDisplayMode == kDisplayMode_Sliders) { for (int i = 0; i < mParameterSliders.size(); ++i) { float value = mParameterSliders[i].mParameter->getValue(); if (mParameterSliders[i].mValue != value) mParameterSliders[i].mValue = value; } if (mChangeGestureParameterIndex != -1) { if (mChangeGestureParameterIndex < (int)mParameterSliders.size() && !mParameterSliders[mChangeGestureParameterIndex].mInSelectorList && mTemporarilyDisplayedParamIndex != mChangeGestureParameterIndex) { if (mTemporarilyDisplayedParamIndex != -1) mShowParameterDropdown->RemoveLabel(mTemporarilyDisplayedParamIndex); mTemporarilyDisplayedParamIndex = mChangeGestureParameterIndex; mShowParameterDropdown->AddLabel(mParameterSliders[mChangeGestureParameterIndex].mDisplayName, mChangeGestureParameterIndex); } mChangeGestureParameterIndex = -1; } } if (mWantOpenVstWindow) { mWantOpenVstWindow = false; if (mPlugin != nullptr) { if (mWindow == nullptr) mWindow = std::unique_ptr<VSTWindow>(VSTWindow::CreateVSTWindow(this, VSTWindow::Normal)); mWindow->ShowWindow(); //if (mWindow->GetNSViewComponent()) // mWindowOverlay = new NSWindowOverlay(mWindow->GetNSViewComponent()->getView()); } } if (mPresetFileUpdateQueued) { mPresetFileUpdateQueued = false; if (mPresetFileIndex >= 0 && mPresetFileIndex < (int)mPresetFilePaths.size()) { File resourceFile = File(mPresetFilePaths[mPresetFileIndex]); if (!resourceFile.existsAsFile()) { DBG("File doesn't exist ..."); return; } std::unique_ptr<FileInputStream> input(resourceFile.createInputStream()); if (!input->openedOk()) { DBG("Failed to open file"); return; } int rev = input->readInt(); int64 vstStateSize = input->readInt64(); char* vstState = new char[vstStateSize]; input->read(vstState, vstStateSize); mPlugin->setStateInformation(vstState, vstStateSize); int64 vstProgramStateSize = input->readInt64(); if (vstProgramStateSize > 0) { char* vstProgramState = new char[vstProgramStateSize]; input->read(vstProgramState, vstProgramStateSize); mPlugin->setCurrentProgramStateInformation(vstProgramState, vstProgramStateSize); } if (rev >= 2 && mModuleSaveData.GetBool("preset_file_sets_params")) { int numParamsShowing = input->readInt(); for (auto& param : mParameterSliders) param.mShowing = false; for (int i = 0; i < numParamsShowing; ++i) { int index = input->readInt(); if (index < mParameterSliders.size()) { mParameterSliders[index].mShowing = true; if (mParameterSliders[index].mSlider == nullptr) mParameterSliders[index].MakeSlider(); } } } } } } void VSTPlugin::audioProcessorChanged(juce::AudioProcessor* processor, const ChangeDetails& details) { if (details.parameterInfoChanged) { mRescanParameterNames = true; } } void VSTPlugin::audioProcessorParameterChangeGestureBegin(juce::AudioProcessor* processor, int parameterIndex) { //set this parameter so we can check it in Poll() mChangeGestureParameterIndex = parameterIndex; } void VSTPlugin::Process(double time) { if (!mPluginReady) { //bypass GetBuffer()->SetNumActiveChannels(2); SyncBuffers(); for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { if (GetTarget()) Add(GetTarget()->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize()); GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize(), ch); } GetBuffer()->Clear(); } #if BESPOKE_LINUX //HACK: weird race condition, which this seems to fix for now if (mPlugin == nullptr) return; #endif PROFILER(VSTPlugin); int inputChannels = MAX(2, mNumInputChannels); int outputChannels = MAX(2, mNumOutputChannels); GetBuffer()->SetNumActiveChannels(inputChannels); SyncBuffers(); /* * Multi-out VSTs which can't disable those outputs will expect *something* in the * buffer even though we don't read it. */ int bufferChannels = MAX(MAX(inputChannels * mNumInBuses, outputChannels * mNumOutBuses), 2); // how much to allocate in the juce::AudioBuffer const int kSafetyMaxChannels = 16; //hitting a crazy issue (memory stomp?) where numchannels is getting blown out sometimes int bufferSize = GetBuffer()->BufferSize(); assert(bufferSize == gBufferSize); juce::AudioBuffer<float> buffer(bufferChannels, bufferSize); for (int i = 0; i < inputChannels && i < kSafetyMaxChannels; ++i) buffer.copyFrom(i, 0, GetBuffer()->GetChannel(MIN(i, GetBuffer()->NumActiveChannels() - 1)), GetBuffer()->BufferSize()); IAudioReceiver* target = GetTarget(); if (mEnabled && mPlugin != nullptr) { mVSTMutex.lock(); ComputeSliders(0); { const juce::ScopedLock lock(mMidiInputLock); for (int i = 0; i < mChannelModulations.size(); ++i) { ChannelModulations& mod = mChannelModulations[i]; int channel = i + 1; if (i == kGlobalModulationIdx) channel = 1; if (mUseVoiceAsChannel == false) channel = mChannel; float bend = mod.mModulation.pitchBend ? mod.mModulation.pitchBend->GetValue(0) : ModulationParameters::kDefaultPitchBend; if (bend != mod.mLastPitchBend) { mod.mLastPitchBend = bend; mMidiBuffer.addEvent(juce::MidiMessage::pitchWheel(channel, (int)ofMap(bend, -mPitchBendRange, mPitchBendRange, 0, 16383, K(clamp))), 0); } float modWheel = mod.mModulation.modWheel ? mod.mModulation.modWheel->GetValue(0) : ModulationParameters::kDefaultModWheel; if (modWheel != mod.mLastModWheel) { mod.mLastModWheel = modWheel; mMidiBuffer.addEvent(juce::MidiMessage::controllerEvent(channel, mModwheelCC, ofClamp(modWheel * 127, 0, 127)), 0); } float pressure = mod.mModulation.pressure ? mod.mModulation.pressure->GetValue(0) : ModulationParameters::kDefaultPressure; if (pressure != mod.mLastPressure) { mod.mLastPressure = pressure; mMidiBuffer.addEvent(juce::MidiMessage::channelPressureChange(channel, ofClamp(pressure * 127, 0, 127)), 0); } } /*if (!mMidiBuffer.isEmpty()) { ofLog() << mMidiBuffer.getFirstEventTime() << " " << mMidiBuffer.getLastEventTime(); }*/ mMidiBuffer.addEvents(mFutureMidiBuffer, 0, mFutureMidiBuffer.getLastEventTime() + 1, 0); mFutureMidiBuffer.clear(); mFutureMidiBuffer.addEvents(mMidiBuffer, gBufferSize, mMidiBuffer.getLastEventTime() - gBufferSize + 1, -gBufferSize); mMidiBuffer.clear(gBufferSize, mMidiBuffer.getLastEventTime() + 1); if (mWantsPanic) { mWantsPanic = false; mMidiBuffer.clear(); for (int channel = 1; channel <= 16; ++channel) mMidiBuffer.addEvent(juce::MidiMessage::allNotesOff(channel), 0); for (int channel = 1; channel <= 16; ++channel) mMidiBuffer.addEvent(juce::MidiMessage::allSoundOff(channel), 1); } mPlugin->processBlock(buffer, mMidiBuffer); if (!mMidiBuffer.isEmpty()) { auto midiIt = mMidiBuffer.begin(); while (midiIt != mMidiBuffer.end()) { auto msg = (*midiIt).getMessage(); auto tMidi = time + (*midiIt).samplePosition * gInvSampleRateMs; if (msg.isNoteOn()) { mMidiOutCable->PlayNoteOutput(tMidi, msg.getNoteNumber(), msg.getVelocity()); } else if (msg.isNoteOff()) { mMidiOutCable->PlayNoteOutput(tMidi, msg.getNoteNumber(), 0); } else if (msg.isController()) { mMidiOutCable->SendCCOutput(msg.getControllerNumber(), msg.getControllerValue()); } midiIt++; } } mMidiBuffer.clear(); } mVSTMutex.unlock(); GetBuffer()->Clear(); /* * Until we support multi output we end up with this requirement that * the output is at most stereo. This stops mis-behaving plugins which * output the full buffer set from copying that onto the output. * (Ahem: Surge 1.9) */ int nChannelsToCopy = MIN(2, buffer.getNumChannels()); for (int ch = 0; ch < nChannelsToCopy && ch < kSafetyMaxChannels; ++ch) { int outputChannel = MIN(ch, GetBuffer()->NumActiveChannels() - 1); for (int sampleIndex = 0; sampleIndex < buffer.getNumSamples(); ++sampleIndex) { GetBuffer()->GetChannel(outputChannel)[sampleIndex] += buffer.getSample(ch, sampleIndex) * mVol; } if (target) Add(target->GetBuffer()->GetChannel(outputChannel), GetBuffer()->GetChannel(outputChannel), bufferSize); GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(outputChannel), bufferSize, outputChannel); } } else { //bypass for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch) { if (target) Add(target->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize()); GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize(), ch); } } GetBuffer()->Clear(); } void VSTPlugin::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) { if (!mPluginReady || mPlugin == nullptr) return; if (!mEnabled) return; if (pitch < 0 || pitch > 127) return; int channel = voiceIdx + 1; if (voiceIdx == -1) channel = 1; const juce::ScopedLock lock(mMidiInputLock); int sampleNumber = (time - gTime) * gSampleRateMs; //ofLog() << sampleNumber; if (velocity > 0) { mMidiBuffer.addEvent(juce::MidiMessage::noteOn(mUseVoiceAsChannel ? channel : mChannel, pitch, (uint8)velocity), sampleNumber); //ofLog() << "+ vst note on: " << (mUseVoiceAsChannel ? channel : mChannel) << " " << pitch << " " << (uint8)velocity; } else { mMidiBuffer.addEvent(juce::MidiMessage::noteOff(mUseVoiceAsChannel ? channel : mChannel, pitch), sampleNumber); //ofLog() << "- vst note off: " << (mUseVoiceAsChannel ? channel : mChannel) << " " << pitch; } int modIdx = voiceIdx; if (voiceIdx == -1) modIdx = kGlobalModulationIdx; mChannelModulations[modIdx].mModulation = modulation; } void VSTPlugin::SendCC(int control, int value, int voiceIdx /*=-1*/) { if (!mPluginReady || mPlugin == nullptr) return; if (control < 0 || control > 127) return; int channel = voiceIdx + 1; if (voiceIdx == -1) channel = 1; const juce::ScopedLock lock(mMidiInputLock); mMidiBuffer.addEvent(juce::MidiMessage::controllerEvent((mUseVoiceAsChannel ? channel : mChannel), control, (uint8)value), 0); } void VSTPlugin::SendMidi(const juce::MidiMessage& message) { if (!mPluginReady || mPlugin == nullptr) return; const juce::ScopedLock lock(mMidiInputLock); mMidiBuffer.addEvent(message, 0); } void VSTPlugin::SetEnabled(bool enabled) { mEnabled = enabled; } void VSTPlugin::PreDrawModule() { /*if (mDisplayMode == kDisplayMode_PluginOverlay && mWindowOverlay) { mWindowOverlay->GetDimensions(mOverlayWidth, mOverlayHeight); if (mWindow) { mOverlayWidth = 500; mOverlayHeight = 500; float contentMult = gDrawScale; float width = mOverlayWidth * contentMult; float height = mOverlayHeight * contentMult; mWindow->setSize(width, height); } mWindowOverlay->UpdatePosition(this); }*/ } void VSTPlugin::DrawModule() { if (Minimized() || IsVisible() == false) return; mVolSlider->Draw(); mPresetFileSelector->Draw(); mSavePresetFileButton->Draw(); mOpenEditorButton->Draw(); mPanicButton->Draw(); mShowParameterDropdown->Draw(); ofPushStyle(); ofSetColor(IDrawableModule::GetColor(kModuleCategory_Note)); DrawTextRightJustify("midi out:", 206 - 18, 14); ofPopStyle(); if (mDisplayMode == kDisplayMode_Sliders) { int sliderCount = 0; for (auto& slider : mParameterSliders) { if (slider.mSlider) { slider.mSlider->SetShowing(slider.mShowing); if (slider.mShowing) { const int kRows = 20; slider.mSlider->SetPosition(3 + (slider.mSlider->GetRect().width + 2) * (sliderCount / kRows), 60 + (17 * (sliderCount % kRows))); slider.mSlider->Draw(); ++sliderCount; } } } } } void VSTPlugin::GetModuleDimensions(float& width, float& height) { if (mDisplayMode == kDisplayMode_PluginOverlay) { /*if (mWindowOverlay) { width = mOverlayWidth; height = mOverlayHeight+20; } else {*/ width = 206; height = 40; //} } else { width = 206; height = 58; for (auto slider : mParameterSliders) { if (slider.mSlider && slider.mShowing) { width = MAX(width, slider.mSlider->GetRect(true).x + slider.mSlider->GetRect(true).width + 3); height = MAX(height, slider.mSlider->GetRect(true).y + slider.mSlider->GetRect(true).height + 3); } } } } void VSTPlugin::OnVSTWindowClosed() { mWindow.release(); } std::vector<IUIControl*> VSTPlugin::ControlsToIgnoreInSaveState() const { std::vector<IUIControl*> ignore; ignore.push_back(mPresetFileSelector); return ignore; } void VSTPlugin::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mPresetFileSelector) mPresetFileUpdateQueued = true; if (list == mShowParameterDropdown) { mParameterSliders[mShowParameterIndex].mShowing = true; if (mParameterSliders[mShowParameterIndex].mSlider == nullptr) mParameterSliders[mShowParameterIndex].MakeSlider(); mParameterSliders[mShowParameterIndex].mInSelectorList = true; mShowParameterIndex = -1; mTemporarilyDisplayedParamIndex = -1; } } void VSTPlugin::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { for (int i = 0; i < mParameterSliders.size(); ++i) { if (mParameterSliders[i].mSlider == slider) { mParameterSliders[i].mParameter->setValue(mParameterSliders[i].mValue); } } } void VSTPlugin::IntSliderUpdated(IntSlider* slider, int oldVal, double time) { } void VSTPlugin::CheckboxUpdated(Checkbox* checkbox, double time) { } void VSTPlugin::ButtonClicked(ClickButton* button, double time) { if (button == mOpenEditorButton) mWantOpenVstWindow = true; if (button == mPanicButton) { mWantsPanic = true; } if (button == mSavePresetFileButton && mPlugin != nullptr) { juce::File(ofToDataPath("vst/presets/" + GetPluginId())).createDirectory(); FileChooser chooser("Save preset as...", File(ofToDataPath("vst/presets/" + GetPluginId() + "/preset.vstp")), "*.vstp", true, false, TheSynth->GetFileChooserParent()); if (chooser.browseForFileToSave(true)) { std::string path = chooser.getResult().getFullPathName().toStdString(); File resourceFile(path); TemporaryFile tempFile(resourceFile); { FileOutputStream output(tempFile.getFile()); if (!output.openedOk()) { DBG("FileOutputStream didn't open correctly ..."); return; } juce::MemoryBlock vstState; mPlugin->getStateInformation(vstState); juce::MemoryBlock vstProgramState; mPlugin->getCurrentProgramStateInformation(vstProgramState); output.writeInt(GetModuleSaveStateRev()); output.writeInt64(vstState.getSize()); output.write(vstState.getData(), vstState.getSize()); output.writeInt64(vstProgramState.getSize()); if (vstProgramState.getSize() > 0) output.write(vstProgramState.getData(), vstProgramState.getSize()); std::vector<int> exposedParams; for (int i = 0; i < (int)mParameterSliders.size(); ++i) { if (mParameterSliders[i].mShowing) exposedParams.push_back(i); } output.writeInt((int)exposedParams.size()); for (int i : exposedParams) output.writeInt(i); output.flush(); // (called explicitly to force an fsync on posix) if (output.getStatus().failed()) { DBG("An error occurred in the FileOutputStream"); return; } } bool success = tempFile.overwriteTargetFileWithTemporary(); if (!success) { DBG("An error occurred writing the file"); return; } RefreshPresetFiles(); for (size_t i = 0; i < mPresetFilePaths.size(); ++i) { if (mPresetFilePaths[i] == path) { mPresetFileIndex = (int)i; break; } } } } } void VSTPlugin::DropdownClicked(DropdownList* list) { if (list == mPresetFileSelector) RefreshPresetFiles(); } void VSTPlugin::RefreshPresetFiles() { if (mPlugin == nullptr) return; juce::File(ofToDataPath("vst/presets/" + GetPluginId())).createDirectory(); mPresetFilePaths.clear(); mPresetFileSelector->Clear(); juce::Array<juce::File> fileList; for (const auto& entry : RangedDirectoryIterator{ juce::File{ ofToDataPath("vst/presets/" + GetPluginId()) }, false, "*.vstp" }) { fileList.add(entry.getFile()); } fileList.sort(); for (const auto& file : fileList) { mPresetFileSelector->AddLabel(file.getFileName().toStdString(), (int)mPresetFilePaths.size()); mPresetFilePaths.push_back(file.getFullPathName().toStdString()); } } void VSTPlugin::SaveLayout(ofxJSONElement& moduleInfo) { moduleInfo["parameterversion"] = 1; } void VSTPlugin::LoadLayout(const ofxJSONElement& moduleInfo) { mModuleSaveData.LoadString("pluginId", moduleInfo, "", VSTLookup::FillVSTList); mModuleSaveData.LoadString("target", moduleInfo); mModuleSaveData.LoadInt("channel", moduleInfo, 1, 0, 16); mModuleSaveData.LoadBool("usevoiceaschannel", moduleInfo, false); mModuleSaveData.LoadFloat("pitchbendrange", moduleInfo, 2, 1, 96, K(isTextField)); mModuleSaveData.LoadInt("modwheelcc(1or74)", moduleInfo, 1, 0, 127, K(isTextField)); mModuleSaveData.LoadBool("preset_file_sets_params", moduleInfo, true); if (!moduleInfo["vst"].isNull()) mOldVstPath = moduleInfo["vst"].asString(); else mOldVstPath = ""; if (!IsSpawningOnTheFly(moduleInfo)) { if (!moduleInfo["parameterversion"].isNull()) mParameterVersion = moduleInfo["parameterversion"].asInt(); else mParameterVersion = 0; } SetUpFromSaveData(); } void VSTPlugin::SetUpFromSaveData() { juce::PluginDescription pluginDesc; if (mModuleSaveData.HasProperty("pluginId") && mModuleSaveData.GetString("pluginId") != "") { auto pluginId = juce::String(mModuleSaveData.GetString("pluginId")); if (VSTLookup::GetPluginDesc(pluginDesc, pluginId)) { TheSynth->LogEvent("Plugin with " + pluginId.toStdString() + " id not found", kLogEventType_Error); } } else if (!mOldVstPath.empty()) { GetVSTFileDesc(mOldVstPath, pluginDesc); } SetVST(pluginDesc); SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target"))); mChannel = mModuleSaveData.GetInt("channel"); mUseVoiceAsChannel = mModuleSaveData.GetBool("usevoiceaschannel"); mPitchBendRange = mModuleSaveData.GetFloat("pitchbendrange"); mModwheelCC = mModuleSaveData.GetInt("modwheelcc(1or74)"); } void VSTPlugin::SaveState(FileStreamOut& out) { out << GetModuleSaveStateRev(); if (mPlugin) { out << true; juce::MemoryBlock vstState; mPlugin->getStateInformation(vstState); out << (int)vstState.getSize(); out.WriteGeneric(vstState.getData(), (int)vstState.getSize()); juce::MemoryBlock vstProgramState; mPlugin->getCurrentProgramStateInformation(vstProgramState); out << (int)vstProgramState.getSize(); if (vstProgramState.getSize() > 0) out.WriteGeneric(vstProgramState.getData(), (int)vstProgramState.getSize()); std::vector<int> exposedParams; for (int i = 0; i < (int)mParameterSliders.size(); ++i) { if (mParameterSliders[i].mShowing) exposedParams.push_back(i); } out << (int)exposedParams.size(); for (int i : exposedParams) out << i; } else { out << false; } IDrawableModule::SaveState(out); } void VSTPlugin::LoadState(FileStreamIn& in, int rev) { if (rev >= 3) { LoadVSTFromSaveData(in, rev); } else { //make all sliders, like we used to, so that the controls can load correctly for (auto& parameter : mParameterSliders) { if (parameter.mSlider == nullptr) parameter.MakeSlider(); } } IDrawableModule::LoadState(in, rev); if (ModularSynth::sLoadingFileSaveStateRev < 423) in >> rev; LoadStateValidate(rev <= GetModuleSaveStateRev()); if (rev < 3) LoadVSTFromSaveData(in, rev); } void VSTPlugin::LoadVSTFromSaveData(FileStreamIn& in, int rev) { bool hasPlugin; in >> hasPlugin; if (hasPlugin) { int vstStateSize; in >> vstStateSize; char* vstState = new char[vstStateSize]; in.ReadGeneric(vstState, vstStateSize); int vstProgramStateSize = 0; if (rev >= 1) in >> vstProgramStateSize; char* vstProgramState = new char[vstProgramStateSize]; if (rev >= 1 && vstProgramStateSize > 0) in.ReadGeneric(vstProgramState, vstProgramStateSize); if (mPlugin != nullptr) { ofLog() << "loading vst state for " << mPlugin->getName(); mPlugin->setStateInformation(vstState, vstStateSize); if (rev >= 1 && vstProgramStateSize > 0) mPlugin->setCurrentProgramStateInformation(vstProgramState, vstProgramStateSize); } else { TheSynth->LogEvent("Couldn't instantiate plugin to load state for " + mModuleSaveData.GetString("pluginId"), kLogEventType_Error); } if (rev >= 2) { int numParamsShowing; in >> numParamsShowing; for (auto& param : mParameterSliders) param.mShowing = false; for (int i = 0; i < numParamsShowing; ++i) { int index; in >> index; if (index < mParameterSliders.size()) { mParameterSliders[index].mShowing = true; if (mParameterSliders[index].mSlider == nullptr) mParameterSliders[index].MakeSlider(); } } } } } void VSTPlugin::ParameterSlider::MakeSlider() { const char* sliderID; if (mOwner->mParameterVersion == 0) sliderID = mDisplayName.c_str(); //old save files used unstable parameters names else sliderID = mID.c_str(); //now we use parameter IDs for more stability mSlider = new FloatSlider(mOwner, sliderID, -1, -1, 200, 15, &mValue, 0, 1); mSlider->SetOverrideDisplayName(mDisplayName); } void VSTPlugin::OnUIControlRequested(const char* name) { if (mParameterVersion == 0) //legacy path { for (auto& parameter : mParameterSliders) { if (parameter.mDisplayName == name && parameter.mSlider == nullptr) parameter.MakeSlider(); } } else { for (auto& parameter : mParameterSliders) { if (parameter.mID == name && parameter.mSlider == nullptr) parameter.MakeSlider(); } } } ```
/content/code_sandbox/Source/VSTPlugin.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
11,023
```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 **/ /* ============================================================================== PulseTrain.h Created: 10 Mar 2020 9:15:47pm Author: Ryan Challinor ============================================================================== */ #pragma once #include <iostream> #include "IDrawableModule.h" #include "Transport.h" #include "Checkbox.h" #include "DropdownList.h" #include "TextEntry.h" #include "Slider.h" #include "IPulseReceiver.h" #include "UIGrid.h" class PatchCableSource; class PulseTrain : public IDrawableModule, public ITimeListener, public IDropdownListener, public IIntSliderListener, public IFloatSliderListener, public IAudioPoller, public IPulseSource, public IPulseReceiver, public UIGridListener { public: PulseTrain(); virtual ~PulseTrain(); static IDrawableModule* Create() { return new PulseTrain(); } 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; 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 1; } 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{ 9999 }; NoteInterval mInterval{ NoteInterval::kInterval_8n }; DropdownList* mIntervalSelector{ nullptr }; bool mResetOnStart{ true }; Checkbox* mResetOnStartCheckbox{ nullptr }; static const int kIndividualStepCables = 16; PatchCableSource* mStepCables[kIndividualStepCables]{ nullptr }; UIGrid* mVelocityGrid{ nullptr }; }; ```
/content/code_sandbox/Source/PulseTrain.h
objective-c
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
846
```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 **/ // // Created by block on 8/6/2022. // #include "BoundsToPulse.h" #include "SynthGlobals.h" #include "ModularSynth.h" #include "PatchCableSource.h" BoundsToPulse::BoundsToPulse() : mSlider(nullptr) , mValue(0) { } void BoundsToPulse::Init() { IDrawableModule::Init(); TheTransport->AddAudioPoller(this); } BoundsToPulse::~BoundsToPulse() { TheTransport->RemoveAudioPoller(this); } void BoundsToPulse::CreateUIControls() { IDrawableModule::CreateUIControls(); mSlider = new FloatSlider(this, "input", 5, 4, 100, 15, &mValue, 0, 1); mMinCable = new PatchCableSource(this, kConnectionType_Pulse); mMaxCable = new PatchCableSource(this, kConnectionType_Pulse); AddPatchCableSource(mMinCable); AddPatchCableSource(mMaxCable); } void BoundsToPulse::OnTransportAdvanced(float amount) { for (int i = 0; i < gBufferSize; ++i) ComputeSliders(i); } void BoundsToPulse::DrawModule() { if (Minimized() || IsVisible() == false) return; mSlider->Draw(); mMinCable->SetManualPosition(10, 30); mMaxCable->SetManualPosition(100, 30); } void BoundsToPulse::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (!mEnabled) return; if (slider == mSlider) { // send the pulse through our main source *and* the relevant cable if (mValue == slider->GetMin() && mValue < oldVal) { DispatchPulse(GetPatchCableSource(), time, 1.f, 0); DispatchPulse(mMinCable, time, 1.f, 0); } else if (mValue == slider->GetMax() && oldVal < mValue) { DispatchPulse(GetPatchCableSource(), time, 1.f, 0); DispatchPulse(mMaxCable, time, 1.f, 0); } } } ```
/content/code_sandbox/Source/BoundsToPulse.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
608
```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 **/ // // LiveGranulator.cpp // modularSynth // // Created by Ryan Challinor on 10/2/13. // // #include "LiveGranulator.h" #include "SynthGlobals.h" #include "Profiler.h" #include "UIControlMacros.h" LiveGranulator::LiveGranulator() : mBufferLength(gSampleRate * 5) , mBuffer(mBufferLength) { mGranulator.SetLiveMode(true); mGranulator.mSpeed = 1; mGranulator.mGrainOverlap = 12; mGranulator.mGrainLengthMs = 300; } void LiveGranulator::Init() { IDrawableModule::Init(); TheTransport->AddListener(this, kInterval_None, OffsetInfo(0, true), false); } namespace { const float kBufferWidth = 80; const float kBufferHeight = 65; } void LiveGranulator::CreateUIControls() { IDrawableModule::CreateUIControls(); UIBLOCK(80); FLOATSLIDER(mGranOverlap, "overlap", &mGranulator.mGrainOverlap, .5f, MAX_GRAINS); FLOATSLIDER(mGranSpeed, "speed", &mGranulator.mSpeed, -3, 3); FLOATSLIDER(mGranLengthMs, "len ms", &mGranulator.mGrainLengthMs, 1, 1000); FLOATSLIDER(mDrySlider, "dry", &mDry, 0, 1); DROPDOWN(mAutoCaptureDropdown, "autocapture", (int*)(&mAutoCaptureInterval), 45); UIBLOCK_NEWCOLUMN(); FLOATSLIDER(mGranPosRandomize, "pos r", &mGranulator.mPosRandomizeMs, 0, 200); FLOATSLIDER(mGranSpeedRandomize, "spd r", &mGranulator.mSpeedRandomize, 0, .3f); FLOATSLIDER(mGranSpacingRandomize, "spa r", &mGranulator.mSpacingRandomize, 0, 1); CHECKBOX(mFreezeCheckbox, "frz", &mFreeze); UIBLOCK_SHIFTX(35); CHECKBOX(mGranOctaveCheckbox, "g oct", &mGranulator.mOctaves); UIBLOCK_NEWLINE(); FLOATSLIDER(mWidthSlider, "width", &mGranulator.mWidth, 0, 1); ENDUIBLOCK(mWidth, mHeight); mBufferX = mWidth + 3; mWidth += kBufferWidth + 3 * 2; UIBLOCK(mBufferX, mHeight - 17, kBufferWidth); FLOATSLIDER(mPosSlider, "pos", &mPos, -gSampleRate, gSampleRate); ENDUIBLOCK0(); mAutoCaptureDropdown->AddLabel("none", kInterval_None); mAutoCaptureDropdown->AddLabel("4n", kInterval_4n); mAutoCaptureDropdown->AddLabel("8n", kInterval_8n); mAutoCaptureDropdown->AddLabel("16n", kInterval_16n); mGranPosRandomize->SetMode(FloatSlider::kSquare); mGranSpeedRandomize->SetMode(FloatSlider::kSquare); mGranLengthMs->SetMode(FloatSlider::kSquare); } LiveGranulator::~LiveGranulator() { TheTransport->RemoveListener(this); } void LiveGranulator::ProcessAudio(double time, ChannelBuffer* buffer) { PROFILER(LiveGranulator); float bufferSize = buffer->BufferSize(); mBuffer.SetNumChannels(buffer->NumActiveChannels()); for (int i = 0; i < bufferSize; ++i) { ComputeSliders(i); mGranulator.SetLiveMode(!mFreeze); if (!mFreeze) { for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) mBuffer.Write(buffer->GetChannel(ch)[i], ch); } else if (mFreezeExtraSamples < FREEZE_EXTRA_SAMPLES_COUNT) { ++mFreezeExtraSamples; for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) mBuffer.Write(buffer->GetChannel(ch)[i], ch); } if (mEnabled) { float sample[ChannelBuffer::kMaxNumChannels]; Clear(sample, ChannelBuffer::kMaxNumChannels); mGranulator.ProcessFrame(time, mBuffer.GetRawBuffer(), mBufferLength, mBuffer.GetRawBufferOffset(0) - mFreezeExtraSamples - 1 + mPos, sample); for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch) buffer->GetChannel(ch)[i] = mDry * buffer->GetChannel(ch)[i] + sample[ch]; } time += gInvSampleRateMs; } } void LiveGranulator::DrawModule() { if (!mEnabled) return; mGranOverlap->Draw(); mGranSpeed->Draw(); mGranLengthMs->Draw(); mGranPosRandomize->Draw(); mGranSpeedRandomize->Draw(); mFreezeCheckbox->Draw(); mGranOctaveCheckbox->Draw(); mPosSlider->Draw(); mDrySlider->Draw(); mAutoCaptureDropdown->Draw(); mGranSpacingRandomize->Draw(); mWidthSlider->Draw(); if (mEnabled) { int drawLength = MIN(mBufferLength, gSampleRate * 2); if (mFreeze) drawLength = MIN(mBufferLength, drawLength + mFreezeExtraSamples); mBuffer.Draw(mBufferX, 3, kBufferWidth, kBufferHeight, drawLength); mGranulator.Draw(mBufferX, 3 + 20, kBufferWidth, kBufferHeight - 20 * 2, mBuffer.GetRawBufferOffset(0) - drawLength, drawLength, mBufferLength); } } float LiveGranulator::GetEffectAmount() { if (!mEnabled) return 0; return ofClamp(.5f + fabsf(mGranulator.mSpeed - 1), 0, 1); } void LiveGranulator::Freeze() { mFreeze = true; mFreezeExtraSamples = 0; } void LiveGranulator::OnTimeEvent(double time) { Freeze(); } void LiveGranulator::CheckboxUpdated(Checkbox* checkbox, double time) { if (checkbox == mEnabledCheckbox) mBuffer.ClearBuffer(); if (checkbox == mFreezeCheckbox) { mFreezeExtraSamples = 0; if (mFreeze) { mEnabled = true; Freeze(); } } } void LiveGranulator::DropdownUpdated(DropdownList* list, int oldVal, double time) { if (list == mAutoCaptureDropdown) { TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this); if (transportListenerInfo != nullptr) transportListenerInfo->mInterval = mAutoCaptureInterval; if (mAutoCaptureInterval == kInterval_None) { mFreeze = false; mFreezeExtraSamples = 0; } } } void LiveGranulator::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) { if (slider == mPosSlider) { if (!mFreeze) mPos = MIN(mPos, 0); } } ```
/content/code_sandbox/Source/LiveGranulator.cpp
c++
2016-08-14T14:36:36
2024-08-16T18:55:21
BespokeSynth
BespokeSynth/BespokeSynth
4,019
1,713