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
**/
//
// PitchChorus.cpp
// Bespoke
//
// Created by Ryan Challinor on 6/19/15.
//
//
#include "PitchChorus.h"
#include "Profiler.h"
#include "Scale.h"
#include "SynthGlobals.h"
PitchChorus::PitchChorus()
: IAudioProcessor(gBufferSize)
, mPassthrough(true)
, mPassthroughCheckbox(nullptr)
{
mOutputBuffer = new float[gBufferSize];
Clear(mOutputBuffer, gBufferSize);
}
void PitchChorus::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mPassthroughCheckbox = new Checkbox(this, "passthrough", 4, 4, &mPassthrough);
}
PitchChorus::~PitchChorus()
{
delete[] mOutputBuffer;
}
void PitchChorus::Process(double time)
{
PROFILER(PitchChorus);
if (!mEnabled)
return;
ComputeSliders(0);
SyncBuffers();
int bufferSize = GetBuffer()->BufferSize();
IAudioReceiver* target = GetTarget();
if (target)
{
Clear(mOutputBuffer, gBufferSize);
for (int i = 0; i < kNumShifters; ++i)
{
if (mShifters[i].mOn || mShifters[i].mRamp.Value(time) > 0)
{
BufferCopy(gWorkBuffer, GetBuffer()->GetChannel(0), bufferSize);
mShifters[i].mShifter.Process(gWorkBuffer, bufferSize);
double timeCopy = time;
for (int j = 0; j < bufferSize; ++j)
{
mOutputBuffer[j] += gWorkBuffer[j] * mShifters[i].mRamp.Value(timeCopy);
timeCopy += gInvSampleRateMs;
}
}
}
if (mPassthrough)
Add(mOutputBuffer, GetBuffer()->GetChannel(0), bufferSize);
Add(target->GetBuffer()->GetChannel(0), mOutputBuffer, bufferSize);
}
GetVizBuffer()->WriteChunk(mOutputBuffer, bufferSize, 0);
GetBuffer()->Reset();
}
void PitchChorus::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
for (int i = 0; i < kNumShifters; ++i)
{
if (velocity > 0 && mShifters[i].mOn == false)
{
float ratio = TheScale->PitchToFreq(pitch) / TheScale->PitchToFreq(60);
mShifters[i].mOn = true;
mShifters[i].mShifter.SetRatio(ratio);
mShifters[i].mPitch = pitch;
mShifters[i].mRamp.Start(time, 1, time + 100);
break;
}
if (velocity == 0 && mShifters[i].mOn == true && mShifters[i].mPitch == pitch)
{
mShifters[i].mOn = false;
mShifters[i].mRamp.Start(time, 0, time + 100);
break;
}
}
}
void PitchChorus::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mPassthroughCheckbox->Draw();
}
``` | /content/code_sandbox/Source/PitchChorus.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 804 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
PulseHocket.cpp
Created: 22 Feb 2020 10:40:15pm
Author: Ryan Challinor
==============================================================================
*/
#include "PulseHocket.h"
#include "SynthGlobals.h"
#include "UIControlMacros.h"
#include "PatchCableSource.h"
PulseHocket::PulseHocket()
{
for (int i = 0; i < kMaxDestinations; ++i)
mWeight[i] = (i == 0) ? 1 : 0;
Reseed();
}
PulseHocket::~PulseHocket()
{
}
void PulseHocket::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);
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 PulseHocket::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
for (int i = 0; i < kMaxDestinations; ++i)
{
mWeightSlider[i]->SetShowing(i < mNumDestinations);
mWeightSlider[i]->Draw();
}
mSeedEntry->SetShowing(mDeterministic);
mSeedEntry->Draw();
mPrevSeedButton->SetShowing(mDeterministic);
mPrevSeedButton->Draw();
mReseedButton->SetShowing(mDeterministic);
mReseedButton->Draw();
mNextSeedButton->SetShowing(mDeterministic);
mNextSeedButton->Draw();
}
void PulseHocket::AdjustHeight()
{
float deterministicPad = 28;
if (!mDeterministic)
deterministicPad = 3;
float height = mNumDestinations * 17 + deterministicPad;
mSeedEntry->Move(0, height - mHeight);
mPrevSeedButton->Move(0, height - mHeight);
mReseedButton->Move(0, height - mHeight);
mNextSeedButton->Move(0, height - mHeight);
mHeight = height;
}
void PulseHocket::OnPulse(double time, float velocity, int flags)
{
ComputeSliders(0);
if (flags & kPulseFlag_Reset)
mRandomIndex = 0;
float totalWeight = 0;
for (int i = 0; i < mNumDestinations; ++i)
totalWeight += mWeight[i];
float random;
if (mDeterministic)
{
random = ((abs(DeterministicRandom(mSeed, mRandomIndex)) % 10000) / 10000.0f) * totalWeight;
++mRandomIndex;
}
else
{
random = ofRandom(totalWeight);
}
int selectedDestination;
for (selectedDestination = 0; selectedDestination < mNumDestinations; ++selectedDestination)
{
if (random <= mWeight[selectedDestination] || selectedDestination == mNumDestinations - 1)
break;
random -= mWeight[selectedDestination];
}
DispatchPulse(mDestinationCables[selectedDestination], time, velocity, flags);
}
void PulseHocket::Reseed()
{
mSeed = gRandom() % 10000;
}
void PulseHocket::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 PulseHocket::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadInt("num_outputs", moduleInfo, 5, 2, kMaxDestinations, K(isTextField));
mModuleSaveData.LoadBool("deterministic", moduleInfo, false);
SetUpFromSaveData();
}
void PulseHocket::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
mNumDestinations = mModuleSaveData.GetInt("num_outputs");
int oldNumItems = (int)mDestinationCables.size();
if (mNumDestinations > oldNumItems)
{
for (int i = oldNumItems; i < mNumDestinations; ++i)
{
mDestinationCables.push_back(new PatchCableSource(this, kConnectionType_Pulse));
mDestinationCables[i]->SetOverrideCableDir(ofVec2f(1, 0), PatchCableSource::Side::kRight);
AddPatchCableSource(mDestinationCables[i]);
ofRectangle rect = mWeightSlider[i]->GetRect(true);
mDestinationCables[i]->SetManualPosition(rect.getMaxX() + 10, rect.y + rect.height / 2);
}
}
else if (mNumDestinations < oldNumItems)
{
for (int i = oldNumItems - 1; i >= mNumDestinations; --i)
{
RemovePatchCableSource(mDestinationCables[i]);
}
mDestinationCables.resize(mNumDestinations);
}
mDeterministic = mModuleSaveData.GetBool("deterministic");
AdjustHeight();
}
``` | /content/code_sandbox/Source/PulseHocket.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,453 |
```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
**/
//
// TitleBar.cpp
// Bespoke
//
// Created by Ryan Challinor on 11/30/14.
//
//
#include "TitleBar.h"
#include "ModularSynth.h"
#include "SynthGlobals.h"
#include "Profiler.h"
#include "ModuleFactory.h"
#include "ModuleSaveDataPanel.h"
#include "HelpDisplay.h"
#include "Prefab.h"
#include "UserPrefsEditor.h"
#include "UIControlMacros.h"
#include "VSTPlugin.h"
#include "VSTScanner.h"
#include "MidiController.h"
#include "juce_audio_devices/juce_audio_devices.h"
TitleBar* TheTitleBar = nullptr;
//static
bool TitleBar::sShowInitialHelpOverlay = true;
namespace
{
const std::string kManagePluginsLabel = "manage plugins...";
const std::string kPluginsDropdownLabel = "plugins:";
}
SpawnList::SpawnList(IDropdownListener* owner, int x, int y, std::string label, ModuleCategory moduleCategory, bool showDecorators)
: mLabel(label)
, mOwner(owner)
, mPos(x, y)
, mModuleCategory(moduleCategory)
, mShowDecorators(showDecorators)
{
}
void SpawnList::SetList(std::vector<ModuleFactory::Spawnable> spawnables)
{
if (mSpawnList == nullptr)
mSpawnList = new DropdownList(mOwner, mLabel.c_str(), mPos.x, mPos.y, &mSpawnIndex);
mSpawnList->SetNoHover(true);
mSpawnList->Clear();
mSpawnList->SetUnknownItemString(mLabel);
mSpawnables = spawnables;
for (int i = 0; i < mSpawnables.size(); ++i)
{
std::string name = mSpawnables[i].mLabel;
if (mShowDecorators && !mSpawnables[i].mDecorator.empty())
name += " " + mSpawnables[i].mDecorator;
if (TheSynth->GetModuleFactory()->IsExperimental(name))
name += " (exp.)";
mSpawnList->AddLabel(name, i);
}
}
namespace
{
ofVec2f kModuleGrabOffset(-40, 10);
}
void SpawnList::OnSelection(DropdownList* list)
{
if (list == mSpawnList)
{
IDrawableModule* module = Spawn(mSpawnIndex);
if (module != nullptr)
TheSynth->SetMoveModule(module, kModuleGrabOffset.x, kModuleGrabOffset.y, true);
mSpawnIndex = -1;
}
}
IDrawableModule* SpawnList::Spawn(int index)
{
if (mLabel == kPluginsDropdownLabel && index == 0)
{
TheTitleBar->ManagePlugins();
return nullptr;
}
IDrawableModule* module = TheSynth->SpawnModuleOnTheFly(mSpawnables[index], TheSynth->GetMouseX(TheSynth->GetRootContainer()) + kModuleGrabOffset.x, TheSynth->GetMouseY(TheSynth->GetRootContainer()) + kModuleGrabOffset.y);
return module;
}
void SpawnList::Draw()
{
float x, y;
mSpawnList->GetPosition(x, y, true);
//DrawTextNormal(mLabel,x,y-2);
mSpawnList->Draw();
}
void SpawnList::SetPosition(int x, int y)
{
mSpawnList->SetPosition(x, y);
}
TitleBar::TitleBar()
: mSpawnLists(this)
{
assert(TheTitleBar == nullptr);
TheTitleBar = this;
mHelpDisplay = dynamic_cast<HelpDisplay*>(HelpDisplay::Create());
mHelpDisplay->SetTypeName("helpdisplay", kModuleCategory_Other);
mNewPatchConfirmPopup.SetTypeName("newpatchconfirm", kModuleCategory_Other);
mNewPatchConfirmPopup.SetName("newpatchconfirm");
SetShouldDrawOutline(false);
}
void TitleBar::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK(140, 1);
BUTTON_STYLE(mPlayPauseButton, "play/pause", ButtonDisplayStyle::kPause);
UIBLOCK_SHIFTRIGHT();
UIBLOCK_SHIFTX(10);
BUTTON(mLoadStateButton, "load");
UIBLOCK_SHIFTRIGHT();
BUTTON(mSaveStateButton, "save");
UIBLOCK_SHIFTRIGHT();
BUTTON(mSaveStateAsButton, "save as");
UIBLOCK_SHIFTRIGHT();
UIBLOCK_SHIFTX(10);
BUTTON(mWriteAudioButton, "write audio");
UIBLOCK_NEWLINE();
BUTTON(mResetLayoutButton, "new patch");
UIBLOCK_SHIFTRIGHT();
CHECKBOX(mEventLookaheadCheckbox, "lookahead (exp.)", &Transport::sDoEventLookahead);
UIBLOCK_SHIFTRIGHT();
CHECKBOX(mShouldAutosaveCheckbox, "autosave", &ModularSynth::sShouldAutosave);
ENDUIBLOCK0();
mDisplayHelpButton = new ClickButton(this, " ? ", 380, 1);
mDisplayUserPrefsEditorButton = new ClickButton(this, "settings", 330, 1);
mLoadLayoutDropdown = new DropdownList(this, "load layout", 140, 20, &mLoadLayoutIndex);
mSaveLayoutButton = new ClickButton(this, "save layout", 280, 19);
mLoadLayoutDropdown->SetShowing(false);
mSaveLayoutButton->SetShowing(false);
mHelpDisplay->CreateUIControls();
ListLayouts();
mNewPatchConfirmPopup.CreateUIControls();
}
TitleBar::~TitleBar()
{
assert(TheTitleBar == this);
TheTitleBar = nullptr;
}
void TitleBar::ManagePlugins()
{
if (mPluginListWindow == nullptr)
mPluginListWindow.reset(new PluginListWindow(TheSynth->GetAudioPluginFormatManager(), this));
mPluginListWindow->toFront(true);
}
void TitleBar::OnWindowClosed()
{
mPluginListWindow.reset(nullptr);
TheSynth->GetKnownPluginList().createXml()->writeTo(juce::File(ofToDataPath("vst/found_vsts.xml")));
}
SpawnListManager::SpawnListManager(IDropdownListener* owner)
: mInstrumentModules(owner, 500, 16, "instruments:", kModuleCategory_Instrument, true)
, mNoteModules(owner, 0, 0, "note effects:", kModuleCategory_Note, true)
, mSynthModules(owner, 0, 0, "synths:", kModuleCategory_Synth, true)
, mAudioModules(owner, 0, 0, "audio effects:", kModuleCategory_Audio, true)
, mModulatorModules(owner, 0, 0, "modulators:", kModuleCategory_Modulator, true)
, mPulseModules(owner, 0, 0, "pulse:", kModuleCategory_Pulse, true)
, mPlugins(owner, 0, 0, kPluginsDropdownLabel, kModuleCategory_Synth, true)
, mOtherModules(owner, 0, 0, "other:", kModuleCategory_Other, true)
, mPrefabs(owner, 0, 0, "prefabs:", kModuleCategory_Other, false)
{
}
void SpawnListManager::SetModuleFactory(ModuleFactory* factory)
{
mInstrumentModules.SetList(factory->GetSpawnableModules(kModuleCategory_Instrument));
mNoteModules.SetList(factory->GetSpawnableModules(kModuleCategory_Note));
mSynthModules.SetList(factory->GetSpawnableModules(kModuleCategory_Synth));
mAudioModules.SetList(factory->GetSpawnableModules(kModuleCategory_Audio));
mModulatorModules.SetList(factory->GetSpawnableModules(kModuleCategory_Modulator));
mPulseModules.SetList(factory->GetSpawnableModules(kModuleCategory_Pulse));
mOtherModules.SetList(factory->GetSpawnableModules(kModuleCategory_Other));
SetUpPluginsDropdown();
SetUpPrefabsDropdown();
mDropdowns.push_back(&mInstrumentModules);
mDropdowns.push_back(&mNoteModules);
mDropdowns.push_back(&mSynthModules);
mDropdowns.push_back(&mAudioModules);
mDropdowns.push_back(&mModulatorModules);
mDropdowns.push_back(&mPulseModules);
mDropdowns.push_back(&mPlugins);
mDropdowns.push_back(&mOtherModules);
mDropdowns.push_back(&mPrefabs);
}
void SpawnListManager::SetUpPrefabsDropdown()
{
std::vector<ModuleFactory::Spawnable> prefabs;
ModuleFactory::GetPrefabs(prefabs);
mPrefabs.SetList(prefabs);
}
void SpawnListManager::SetUpPluginsDropdown()
{
std::vector<ModuleFactory::Spawnable> list;
ModuleFactory::Spawnable scanDummy;
scanDummy.mLabel = kManagePluginsLabel;
list.push_back(scanDummy);
std::vector<juce::PluginDescription> recentPlugins;
VSTLookup::GetRecentPlugins(recentPlugins, 8);
for (auto& pluginDesc : recentPlugins)
{
ModuleFactory::Spawnable spawnable{};
spawnable.mLabel = pluginDesc.name.toStdString();
spawnable.mDecorator = "[" + ModuleFactory::Spawnable::GetPluginLabel(pluginDesc) + "]";
spawnable.mPluginDesc = pluginDesc;
spawnable.mSpawnMethod = ModuleFactory::SpawnMethod::Plugin;
list.push_back(spawnable);
}
std::vector<juce::PluginDescription> vsts;
VSTLookup::GetAvailableVSTs(vsts);
for (auto& pluginDesc : vsts)
{
ModuleFactory::Spawnable spawnable{};
spawnable.mLabel = pluginDesc.name.toStdString();
spawnable.mDecorator = "[" + ModuleFactory::Spawnable::GetPluginLabel(pluginDesc) + "]";
spawnable.mPluginDesc = pluginDesc;
spawnable.mSpawnMethod = ModuleFactory::SpawnMethod::Plugin;
list.push_back(spawnable);
}
mPlugins.SetList(list);
mPlugins.GetList()->ClearSeparators();
mPlugins.GetList()->AddSeparator(1);
if (!recentPlugins.empty())
mPlugins.GetList()->AddSeparator((int)recentPlugins.size() + 1);
}
void TitleBar::ListLayouts()
{
mLoadLayoutDropdown->Clear();
int layoutIdx = 0;
for (const auto& entry : juce::RangedDirectoryIterator{ juce::File{ ofToDataPath("layouts") }, false, "*.json" })
{
const auto& file = entry.getFile();
mLoadLayoutDropdown->AddLabel(file.getFileNameWithoutExtension().toRawUTF8(), layoutIdx);
if (file.getRelativePathFrom(juce::File{ ofToDataPath("") }).toStdString() == TheSynth->GetLoadedLayout())
mLoadLayoutIndex = layoutIdx;
++layoutIdx;
}
mSaveLayoutButton->PositionTo(mLoadLayoutDropdown, kAnchor_Right);
}
void TitleBar::Poll()
{
mHelpDisplay->Poll();
}
void TitleBar::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
if (mLeftCornerHovered)
TheSynth->GetLocationZoomer()->EnterVanityPanningMode();
}
bool TitleBar::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
if (x < 130 && y < 36)
mLeftCornerHovered = true;
else
mLeftCornerHovered = false;
return false;
}
namespace
{
const float kDoubleHeightThreshold = 1200;
}
float TitleBar::GetPixelWidth() const
{
return ofGetWidth() / GetOwningContainer()->GetDrawScale();
}
void TitleBar::DrawModule()
{
if (HiddenByZoom())
return;
ofSetColor(255, 255, 255);
ofPushStyle();
if (gHoveredModule == this && mLeftCornerHovered)
ofSetColor(ofColor::lerp(ofColor::black, ofColor::white, ofMap(sin(gTime / 1000 * PI * 2), -1, 1, .7f, .9f)));
DrawTextBold("bespoke", 2, 28, 34);
#if BESPOKE_NIGHTLY && !BESPOKE_SUPPRESS_NIGHTLY_LABEL
DrawTextNormal("nightly", 90, 35, 8);
#endif
#if DEBUG
ofFill();
ofSetColor(0, 0, 0, 180);
ofRect(13, 12, 90, 17);
ofSetColor(255, 0, 0);
DrawTextBold("debug build", 17, 25, 17);
#endif
ofPopStyle();
std::string info;
if (TheSynth->GetMoveModule())
info += " (moving module \"" + std::string(TheSynth->GetMoveModule()->Name()) + "\")";
if (IKeyboardFocusListener::GetActiveKeyboardFocus())
info += " (entering text)";
float pixelWidth = GetPixelWidth();
DrawTextRightJustify(info, pixelWidth - 140, 32);
mSaveLayoutButton->Draw();
mSaveStateButton->Draw();
mSaveStateAsButton->Draw();
mLoadStateButton->Draw();
mWriteAudioButton->Draw();
mLoadLayoutDropdown->Draw();
mResetLayoutButton->Draw();
if (TheSynth->IsAudioPaused())
mPlayPauseButton->SetDisplayStyle(ButtonDisplayStyle::kPlay);
else
mPlayPauseButton->SetDisplayStyle(ButtonDisplayStyle::kPause);
mPlayPauseButton->Draw();
float startX = 400;
float startY = 2;
if (pixelWidth < kDoubleHeightThreshold)
{
startX = 10;
startY += 16 * 2 + 4;
}
float x = startX;
float y = startY;
for (auto* spawnList : mSpawnLists.GetDropdowns())
{
spawnList->SetPosition(x, y);
float w, h;
spawnList->GetList()->GetDimensions(w, h);
x += w + 5;
if (x >= pixelWidth - 260)
{
x = startX;
y += 18;
}
}
//temporarily fake the module type to get the colors we want for each dropdown
auto type = GetModuleCategory();
for (auto* spawnList : mSpawnLists.GetDropdowns())
{
mModuleCategory = spawnList->GetCategory();
spawnList->Draw();
}
mModuleCategory = type;
float usage = TheSynth->GetAudioDeviceManager().getCpuUsage();
std::string stats;
stats += "fps:" + ofToString(ofGetFrameRate(), 0);
stats += " audio cpu:" + ofToString(usage * 100, 1);
if (usage > 1)
ofSetColor(255, 150, 150);
else
ofSetColor(255, 255, 255);
DrawTextRightJustify(stats, ofGetWidth() / GetOwningContainer()->GetDrawScale() - 5, 33);
mDisplayHelpButton->SetPosition(ofGetWidth() / GetOwningContainer()->GetDrawScale() - 20, 4);
mDisplayHelpButton->Draw();
mDisplayUserPrefsEditorButton->SetPosition(mDisplayHelpButton->GetPosition(true).x - 55, 4);
mDisplayUserPrefsEditorButton->Draw();
mEventLookaheadCheckbox->Draw();
mShouldAutosaveCheckbox->Draw();
}
void TitleBar::DrawModuleUnclipped()
{
if (mPluginListWindow != nullptr)
{
ofPushStyle();
ofSetColor(255, 255, 255);
float titleBarWidth, titleBarHeight;
TheTitleBar->GetDimensions(titleBarWidth, titleBarHeight);
float x = 100;
float y = 50 + titleBarHeight;
gFontBold.DrawString("please close plugin manager to continue", 48, x, y);
ofPopStyle();
return;
}
float displayMessageCooldown = 1 - ofClamp((gTime - mDisplayMessageTime) / 1000, 0, 1);
if (displayMessageCooldown > 0)
{
ofPushStyle();
ofSetColor(255, 255, 255, displayMessageCooldown * 255);
float titleBarWidth, titleBarHeight;
TheTitleBar->GetDimensions(titleBarWidth, titleBarHeight);
float x = 100;
float y = 40 + titleBarHeight;
gFontBold.DrawString(mDisplayMessage, 48, x, y);
ofPopStyle();
}
if (HiddenByZoom())
return;
if (sShowInitialHelpOverlay)
{
ofPushStyle();
ofSetColor(255, 255, 255);
std::string text = "click ? to view help and toggle tooltips";
float size = 26;
float titleBarWidth, titleBarHeight;
TheTitleBar->GetDimensions(titleBarWidth, titleBarHeight);
ofRectangle helpButtonRect = mDisplayHelpButton->GetRect(true);
float x = helpButtonRect.getCenter().x;
float y = helpButtonRect.getCenter().y + 15 + titleBarHeight;
gFontBold.DrawString(text, size, x - gFontBold.GetStringWidth(text, size) - 15 * GetOwningContainer()->GetDrawScale(), y);
ofSetLineWidth(2);
float scale = GetOwningContainer()->GetDrawScale();
ofLine(x - 10, y - 6 * scale, x, y - 6 * scale);
ofLine(x, y - 6 * scale, x, y - 18 * scale);
ofLine(x - 3 * scale, y - 15 * scale, x, y - 18 * scale);
ofLine(x + 3 * scale, y - 15 * scale, x, y - 18 * scale);
ofPopStyle();
}
//midicontroller
{
const float kDisplayMs = 500;
std::string displayString;
IUIControl* drawControl = nullptr;
if (gTime < MidiController::sLastBoundControlTime + kDisplayMs)
{
drawControl = MidiController::sLastBoundUIControl;
if (drawControl != nullptr)
displayString = drawControl->Path() + " bound!";
}
else if (gTime < MidiController::sLastConnectedActivityTime + kDisplayMs)
{
drawControl = MidiController::sLastActivityUIControl;
if (drawControl != nullptr)
displayString = drawControl->Path(false, true) + ": " + drawControl->GetDisplayValue(drawControl->GetValue());
}
if (!displayString.empty() && drawControl != nullptr)
{
ofPushStyle();
ofFill();
ofVec2f pos(50, ofGetHeight() / GetOwningContainer()->GetDrawScale() - 100);
const float kWidth = 600;
const float kHeight = 70;
ofSetColor(80, 80, 80, 150);
ofRect(pos.x, pos.y, kWidth, kHeight);
ofSetColor(120, 120, 120, 150);
ofRect(pos.x, pos.y, kWidth * drawControl->GetMidiValue(), kHeight);
ofSetColor(255, 255, 255);
DrawTextBold(displayString, pos.x + 20, pos.y + 50, 38);
ofPopStyle();
}
}
}
void TitleBar::DisplayTemporaryMessage(std::string message)
{
mDisplayMessage = message;
mDisplayMessageTime = gTime;
}
bool TitleBar::HiddenByZoom() const
{
return false; //ofGetWidth() / GetOwningContainer()->GetDrawScale() < 620;
}
void TitleBar::GetModuleDimensions(float& width, float& height)
{
if (HiddenByZoom())
{
width = 0;
height = 0;
return;
}
width = ofGetWidth() / GetOwningContainer()->GetDrawScale() + 5;
if (GetPixelWidth() < kDoubleHeightThreshold)
height = 36 * 2;
else
height = 36;
}
void TitleBar::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void TitleBar::DropdownClicked(DropdownList* list)
{
if (list == mSpawnLists.mPlugins.GetList())
mSpawnLists.SetUpPluginsDropdown();
if (list == mSpawnLists.mPrefabs.GetList())
mSpawnLists.SetUpPrefabsDropdown();
}
void TitleBar::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mLoadLayoutDropdown)
{
std::string layout = mLoadLayoutDropdown->GetLabel(mLoadLayoutIndex);
TheSynth->LoadLayoutFromFile(ofToDataPath("layouts/" + layout + ".json"));
return;
}
for (auto* spawnList : mSpawnLists.GetDropdowns())
spawnList->OnSelection(list);
}
void TitleBar::ButtonClicked(ClickButton* button, double time)
{
if (button == mSaveLayoutButton)
{
if (GetKeyModifiers() == kModifier_Shift)
TheSynth->SaveLayoutAsPopup();
else
TheSynth->SaveLayout();
}
if (button == mSaveStateButton)
TheSynth->SaveCurrentState();
if (button == mSaveStateAsButton)
TheSynth->SaveStatePopup();
if (button == mLoadStateButton)
TheSynth->LoadStatePopup();
if (button == mWriteAudioButton)
TheSynth->SaveOutput();
if (button == mDisplayHelpButton)
{
float x, y, w, h, butW, butH;
mDisplayHelpButton->GetPosition(x, y);
mDisplayHelpButton->GetDimensions(butW, butH);
mHelpDisplay->GetDimensions(w, h);
mHelpDisplay->SetPosition(x - w + butW, y + butH);
mHelpDisplay->SetOwningContainer(GetOwningContainer());
mHelpDisplay->Show();
TheSynth->PushModalFocusItem(mHelpDisplay);
sShowInitialHelpOverlay = false;
}
if (button == mDisplayUserPrefsEditorButton)
TheSynth->GetUserPrefsEditor()->Show();
if (button == mResetLayoutButton)
{
auto buttonRect = mResetLayoutButton->GetRect();
mNewPatchConfirmPopup.SetOwningContainer(GetOwningContainer());
mNewPatchConfirmPopup.SetPosition(buttonRect.x, buttonRect.y + buttonRect.height + 2);
TheSynth->PushModalFocusItem(&mNewPatchConfirmPopup);
}
if (button == mPlayPauseButton)
TheSynth->SetAudioPaused(!TheSynth->IsAudioPaused());
}
void NewPatchConfirmPopup::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK(3, 20);
BUTTON(mConfirmButton, "confirm");
UIBLOCK_SHIFTRIGHT();
UIBLOCK_SHIFTX(5);
BUTTON(mCancelButton, "cancel");
ENDUIBLOCK(mWidth, mHeight);
}
void NewPatchConfirmPopup::DrawModule()
{
DrawTextNormal("clear this patch?", 3, 14);
mConfirmButton->Draw();
mCancelButton->Draw();
}
void NewPatchConfirmPopup::ButtonClicked(ClickButton* button, double time)
{
if (button == mConfirmButton)
TheSynth->ReloadInitialLayout();
if (button == mCancelButton)
TheSynth->PopModalFocusItem();
}
``` | /content/code_sandbox/Source/TitleBar.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 5,282 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// DCRemoverEffect.cpp
// Bespoke
//
// Created by Ryan Challinor on 12/2/14.
//
//
#include "DCRemoverEffect.h"
#include "Profiler.h"
DCRemoverEffect::DCRemoverEffect()
{
for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i)
{
mBiquad[i].SetFilterParams(10, sqrt(2) / 2);
mBiquad[i].SetFilterType(kFilterType_Highpass);
mBiquad[i].UpdateFilterCoeff();
}
}
DCRemoverEffect::~DCRemoverEffect()
{
}
void DCRemoverEffect::ProcessAudio(double time, ChannelBuffer* buffer)
{
PROFILER(DCRemoverEffect);
if (!mEnabled)
return;
float bufferSize = buffer->BufferSize();
for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch)
mBiquad[ch].Filter(buffer->GetChannel(ch), bufferSize);
}
void DCRemoverEffect::DrawModule()
{
}
float DCRemoverEffect::GetEffectAmount()
{
if (!mEnabled)
return 0;
return 1;
}
void DCRemoverEffect::GetModuleDimensions(float& width, float& height)
{
width = 30;
height = 0;
}
void DCRemoverEffect::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i)
mBiquad[i].Clear();
}
}
``` | /content/code_sandbox/Source/DCRemoverEffect.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 452 |
```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
**/
//
// NoiseEffect.h
// modularSynth
//
// Created by Ryan Challinor on 4/16/13.
//
//
#pragma once
#include <iostream>
#include "IAudioEffect.h"
#include "Slider.h"
#include "Checkbox.h"
class NoiseEffect : public IAudioEffect, public IIntSliderListener, public IFloatSliderListener
{
public:
NoiseEffect();
static IAudioEffect* Create() { return new NoiseEffect(); }
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 "noisify"; }
void CheckboxUpdated(Checkbox* checkbox, double time) override;
//IIntSliderListener
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 120;
height = 60;
}
float mAmount{ 0 };
int mWidth{ 10 };
int mSampleCounter{ 0 };
float mRandom{ 0 };
FloatSlider* mAmountSlider{ nullptr };
IntSlider* mWidthSlider{ nullptr };
};
``` | /content/code_sandbox/Source/NoiseEffect.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 439 |
```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
**/
//
// QwertyController.h
// Bespoke
//
// Created by Ryan Challinor on 4/15/24.
//
//
#pragma once
#include "MidiDevice.h"
#include "INonstandardController.h"
class QwertyController : public INonstandardController
{
public:
QwertyController(MidiDeviceListener* listener);
~QwertyController();
void OnKeyPressed(int key);
void OnKeyReleased(int key);
void SendValue(int page, int control, float value, bool forceNoteOn = false, int channel = -1) override {}
bool IsInputConnected() override { return true; }
bool Reconnect() override { return true; }
std::string GetControlTooltip(MidiMessageType type, int control) override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in) override;
private:
MidiDeviceListener* mListener{ nullptr };
std::array<bool, 128> mPressedKeys{};
};
``` | /content/code_sandbox/Source/QwertyController.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 311 |
```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
**/
/*
==============================================================================
NotePanner.h
Created: 24 Mar 2018 8:18:19pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "INoteSource.h"
#include "Slider.h"
class NotePanner : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener
{
public:
NotePanner();
static IDrawableModule* Create() { return new NotePanner(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 108;
height = 22;
}
float mPan{ 0 };
FloatSlider* mPanSlider{ nullptr };
};
``` | /content/code_sandbox/Source/NotePanner.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 433 |
```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
**/
/*
==============================================================================
NoteRangeFilter.cpp
Created: 29 Jan 2020 9:18:39pm
Author: Ryan Challinor
==============================================================================
*/
#include "NoteRangeFilter.h"
#include "OpenFrameworksPort.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
NoteRangeFilter::NoteRangeFilter()
{
}
void NoteRangeFilter::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
INTSLIDER(mMinPitchSlider, "min", &mMinPitch, 0, 127);
INTSLIDER(mMaxPitchSlider, "max", &mMaxPitch, 0, 127);
CHECKBOX(mWrapCheckbox, "wrap", &mWrap);
ENDUIBLOCK(mWidth, mHeight);
}
void NoteRangeFilter::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mMinPitchSlider->Draw();
mMaxPitchSlider->Draw();
mWrapCheckbox->Draw();
}
void NoteRangeFilter::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
mNoteOutput.Flush(time);
}
void NoteRangeFilter::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
if (slider == mMinPitchSlider || slider == mMaxPitchSlider)
mNoteOutput.Flush(time);
}
void NoteRangeFilter::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
ComputeSliders(0);
if (mWrap && mMaxPitch > mMinPitch)
{
int length = mMaxPitch - mMinPitch + 1;
while (pitch < mMinPitch)
pitch += length;
while (pitch > mMaxPitch)
pitch -= length;
}
if (!mEnabled || (pitch >= mMinPitch && pitch <= mMaxPitch))
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
}
void NoteRangeFilter::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void NoteRangeFilter::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/NoteRangeFilter.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 602 |
```c++
#include "Minimap.h"
#include "ModularSynth.h"
#include "OpenFrameworksPort.h"
namespace
{
const float kMaxLength = 150;
const float kMarginRight = 10;
const float kMarginTop = 45;
const float kBookmarkSize = 15;
const float kNumBookmarks = 9;
}
Minimap::Minimap()
{
}
Minimap::~Minimap()
{
}
void Minimap::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mGrid = new UIGrid("uigrid", 0, 0, kMaxLength, kBookmarkSize, kNumBookmarks, 1, this);
}
void Minimap::GetDimensions(float& width, float& height)
{
float windowWidth = ofGetWidth();
float windowHeight = ofGetHeight();
float ratio = windowWidth / windowHeight;
if (ofGetWidth() > ofGetHeight())
{
width = kMaxLength;
height = (kMaxLength / ratio) + kBookmarkSize;
}
else
{
height = kMaxLength;
width = (kMaxLength * ratio) + kBookmarkSize;
}
}
void Minimap::GetDimensionsMinimap(float& width, float& height)
{
GetDimensions(width, height);
if (width < height)
{
width -= kBookmarkSize;
}
else
{
height -= kBookmarkSize;
}
}
void Minimap::ComputeBoundingBox(ofRectangle& rect)
{
std::vector<IDrawableModule*> modules;
TheSynth->GetRootContainer()->GetAllModules(modules);
if (modules.empty())
{
rect = TheSynth->GetDrawRect();
return;
}
rect = modules[0]->GetRect();
for (int i = 1; i < modules.size(); ++i)
{
if (!modules[i]->IsShowing())
{
continue;
}
ofRectangle moduleRect = modules[i]->GetRect();
RectUnion(rect, moduleRect);
}
float minimapWidth, minimapHeight;
GetDimensionsMinimap(minimapWidth, minimapHeight);
float boundsAspectRatio = rect.width / rect.height;
float minimapAspectRatio = minimapWidth / minimapHeight;
//retain aspect ratio
if (boundsAspectRatio > minimapAspectRatio)
rect.height = rect.width / minimapAspectRatio;
else
rect.width = rect.height * minimapAspectRatio;
}
ofRectangle Minimap::CoordsToMinimap(ofRectangle& boundingBox, ofRectangle& source)
{
float width;
float height;
GetDimensionsMinimap(width, height);
float x1 = (source.getMinX() - boundingBox.x) / boundingBox.width * width;
float y1 = (source.getMinY() - boundingBox.y) / boundingBox.height * height;
float x2 = (source.getMaxX() - boundingBox.x) / boundingBox.width * width;
float y2 = (source.getMaxY() - boundingBox.y) / boundingBox.height * height;
return { x1, y1, x2 - x1, y2 - y1 };
}
ofVec2f Minimap::CoordsToViewport(ofRectangle& boundingBox, float x, float y)
{
float width;
float height;
GetDimensionsMinimap(width, height);
float x1 = x / width * boundingBox.width + boundingBox.x;
float y1 = y / height * boundingBox.height + boundingBox.y;
return { x1, y1 };
}
void Minimap::DrawModulesOnMinimap(ofRectangle& boundingBox)
{
std::vector<IDrawableModule*> modules;
TheSynth->GetRootContainer()->GetAllModules(modules);
ofPushStyle();
for (int i = 0; i < modules.size(); ++i)
{
if (!modules[i]->IsShowing())
{
continue;
}
ofRectangle moduleRect = modules[i]->GetRect();
ofColor moduleColor(IDrawableModule::GetColor(modules[i]->GetModuleCategory()));
ofSetColor(moduleColor);
ofFill();
ofRect(CoordsToMinimap(boundingBox, moduleRect));
}
ofPopStyle();
}
void Minimap::RectUnion(ofRectangle& target, ofRectangle& unionRect)
{
float x2 = target.getMaxX();
float y2 = target.getMaxY();
if (target.x > unionRect.x)
{
target.x = unionRect.x;
target.width = fabs(x2) - target.x;
}
if (target.y > unionRect.y)
{
target.y = unionRect.y;
target.height = fabs(y2) - target.y;
}
if (target.getMaxX() < unionRect.getMaxX())
{
x2 = unionRect.getMaxX();
}
if (target.getMaxY() < unionRect.getMaxY())
{
y2 = unionRect.getMaxY();
}
target.width = fabs(x2) - target.x;
target.height = fabs(y2) - target.y;
}
void Minimap::DrawModule()
{
float width;
float height;
ofRectangle boundingBox;
ofRectangle viewport = TheSynth->GetDrawRect();
ForcePosition();
ComputeBoundingBox(boundingBox);
GetDimensions(width, height);
DrawModulesOnMinimap(boundingBox);
for (int i = 0; i < mGrid->GetCols() * mGrid->GetRows(); ++i)
{
float val = 0.0f;
if (TheSynth->GetLocationZoomer()->HasLocation(i + '1'))
val = .5f;
mGrid->SetVal(i % mGrid->GetCols(), i / mGrid->GetCols(), val);
}
if (width < height)
{
mGrid->SetDimensions(kBookmarkSize, height);
mGrid->SetPosition(width - kBookmarkSize, 0);
mGrid->SetGrid(1, kNumBookmarks);
}
else
{
mGrid->SetDimensions(width, kBookmarkSize);
mGrid->SetPosition(0, height - kBookmarkSize);
mGrid->SetGrid(kNumBookmarks, 1);
}
ofPushMatrix();
float widthMM;
float heightMM;
GetDimensionsMinimap(widthMM, heightMM);
ofClipWindow(0, 0, widthMM, heightMM, true);
ofPushStyle();
ofSetColor(255, 255, 255, 80);
ofRect(CoordsToMinimap(boundingBox, viewport));
ofSetColor(255, 255, 255, 10);
ofFill();
ofRect(CoordsToMinimap(boundingBox, viewport));
ofPopStyle();
ofPopMatrix();
mGrid->Draw();
if (mHoveredBookmarkPos.mCol != -1)
{
ofPushStyle();
ofSetColor(255, 255, 255);
ofFill();
ofVec2f pos = mGrid->GetCellPosition(mHoveredBookmarkPos.mCol, mHoveredBookmarkPos.mRow) + mGrid->GetPosition(true);
float xsize = float(mGrid->GetWidth()) / mGrid->GetCols();
float ysize = float(mGrid->GetHeight()) / mGrid->GetRows();
if (GetKeyModifiers() == kModifier_Shift)
{
ofRect(pos.x + xsize / 2 - 1, pos.y + 2, 2, ysize - 4, 0);
ofRect(pos.x + 2, pos.y + ysize / 2 - 1, xsize - 4, 2, 0);
}
else
{
ofCircle(pos.x + xsize / 2, pos.y + ysize / 2, xsize / 2 - 2);
}
ofPopStyle();
}
}
void Minimap::OnClicked(float x, float y, bool right)
{
if (mGrid->TestClick(x, y, right, true))
{
float gridX, gridY;
mGrid->GetPosition(gridX, gridY, true);
GridCell cell = mGrid->GetGridCellAt(x - gridX, y - gridY);
int number = cell.mCol + cell.mRow + '1';
if (GetKeyModifiers() == kModifier_Shift)
TheSynth->GetLocationZoomer()->WriteCurrentLocation(number);
else
TheSynth->GetLocationZoomer()->MoveToLocation(number);
}
else
{
ofRectangle boundingBox;
ofRectangle viewport = TheSynth->GetDrawRect();
ComputeBoundingBox(boundingBox);
ofVec2f viewportCoords = CoordsToViewport(boundingBox, x, y);
TheSynth->SetDrawOffset(ofVec2f(-viewportCoords.x + viewport.width / 2, -viewportCoords.y + viewport.height / 2));
mClick = true;
}
}
void Minimap::MouseReleased()
{
mClick = false;
}
bool Minimap::MouseMoved(float x, float y)
{
if (mClick)
{
ofRectangle boundingBox;
ofRectangle viewport = TheSynth->GetDrawRect();
ComputeBoundingBox(boundingBox);
ofVec2f viewportCoords = CoordsToViewport(boundingBox, x, y);
TheSynth->SetDrawOffset(ofVec2f(-viewportCoords.x + viewport.width / 2, -viewportCoords.y + viewport.height / 2));
}
mGrid->NotifyMouseMoved(x, y);
float gridX, gridY;
mGrid->GetPosition(gridX, gridY, true);
if (mGrid->TestHover(x - gridX, y - gridY))
{
mHoveredBookmarkPos = mGrid->GetGridCellAt(x - gridX, y - gridY);
}
else
{
mHoveredBookmarkPos.mCol = -1;
mHoveredBookmarkPos.mRow = -1;
}
return false;
}
void Minimap::ForcePosition()
{
float width, height, scale;
scale = 1 / TheSynth->GetUIScale();
GetDimensions(width, height);
mX = (ofGetWidth() * scale) - (width + kMarginRight);
mY = kMarginTop;
}
``` | /content/code_sandbox/Source/Minimap.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,228 |
```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
**/
//
// FilterButterworth24db.h
// Bespoke
//
// Created by Ryan Challinor on 5/19/16.
//
//
#pragma once
class CFilterButterworth24db
{
public:
CFilterButterworth24db(void);
~CFilterButterworth24db(void);
void SetSampleRate(float fs);
void Set(float cutoff, float q);
void CopyCoeffFrom(CFilterButterworth24db& other);
float Run(float input);
void Clear();
private:
float t0{ 0 }, t1{ 0 }, t2{ 0 }, t3{ 0 };
float coef0{ 0 }, coef1{ 0 }, coef2{ 0 }, coef3{ 0 };
float history1{ 0 }, history2{ 0 }, history3{ 0 }, history4{ 0 };
float gain{ 0 };
float min_cutoff{ 0 }, max_cutoff{ 0 };
};
``` | /content/code_sandbox/Source/FilterButterworth24db.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 309 |
```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
**/
//
// ValueSetter.h
// Bespoke
//
// Created by Ryan Challinor on 1/1/16.
//
//
#pragma once
#include "IDrawableModule.h"
#include "IPulseReceiver.h"
#include "TextEntry.h"
#include "ClickButton.h"
#include "Slider.h"
class PatchCableSource;
class IUIControl;
class ValueSetter : public IDrawableModule, public IPulseReceiver, public ITextEntryListener, public IButtonListener, public IFloatSliderListener
{
public:
ValueSetter();
virtual ~ValueSetter();
static IDrawableModule* Create() { return new ValueSetter(); }
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 ButtonClicked(ClickButton* button, double time) override;
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
void TextEntryComplete(TextEntry* entry) override {}
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void SaveLayout(ofxJSONElement& moduleInfo) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void Go(double time);
PatchCableSource* mControlCable{ nullptr };
std::array<IUIControl*, IDrawableModule::kMaxOutputsPerPatchCableSource> mTargets{};
float mValue{ 0 };
TextEntry* mValueEntry{ nullptr };
FloatSlider* mValueSlider{ nullptr };
ClickButton* mButton{ nullptr };
double mLastClickTime{ 0 };
float mWidth{ 200 };
float mHeight{ 20 };
};
``` | /content/code_sandbox/Source/ValueSetter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 593 |
```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
**/
//
// Selector.h
// Bespoke
//
// Created by Ryan Challinor on 2/7/16.
//
//
#pragma once
#include "IDrawableModule.h"
#include "RadioButton.h"
#include "INoteReceiver.h"
class PatchCableSource;
class Selector : public IDrawableModule, public IRadioButtonListener, public INoteReceiver
{
public:
Selector();
~Selector() override;
static IDrawableModule* Create() { return new Selector(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() 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 {}
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void SyncList();
void SetIndex(int index, double time);
RadioButton* mSelector{ nullptr };
int mCurrentValue{ 0 };
std::vector<PatchCableSource*> mControlCables;
};
``` | /content/code_sandbox/Source/Selector.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 460 |
```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
**/
//
// AbletonLink.h
//
// Created by Ryan Challinor on 12/9/21.
//
//
#pragma once
#include <iostream>
#include <memory>
#include "IDrawableModule.h"
#include "Checkbox.h"
#include "IAudioPoller.h"
#include "Slider.h"
#include "ClickButton.h"
namespace ableton
{
class Link;
}
class AbletonLink : public IDrawableModule, public IAudioPoller, public IFloatSliderListener, public IButtonListener
{
public:
AbletonLink();
virtual ~AbletonLink();
static IDrawableModule* Create() { return new AbletonLink(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void Init() override;
void CreateUIControls() override;
void Poll() override;
void OnTransportAdvanced(float amount) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
float mWidth{ 200 };
float mHeight{ 20 };
float mOffsetMs{ 0 };
FloatSlider* mOffsetMsSlider{ nullptr };
ClickButton* mResetButton{ nullptr };
std::unique_ptr<ableton::Link> mLink;
double mTempo{ 120 };
std::size_t mNumPeers{ 0 };
double mLastReceivedBeat{ 0 };
double mSampleTime{ 0 };
};
``` | /content/code_sandbox/Source/AbletonLink.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 528 |
```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
**/
//
// TitleBar.h
// Bespoke
//
// Created by Ryan Challinor on 11/30/14.
//
//
#pragma once
#include <memory>
#include "IDrawableModule.h"
#include "DropdownList.h"
#include "ClickButton.h"
#include "Slider.h"
#include "VSTPlugin.h"
#include "WindowCloseListener.h"
#include "ModuleFactory.h"
class ModuleFactory;
class TitleBar;
class HelpDisplay;
struct SpawnListManager;
class PluginListWindow;
class SpawnList
{
public:
SpawnList(IDropdownListener* owner, int x, int y, std::string label, ModuleCategory moduleCategory, bool showDecorators);
void SetList(std::vector<ModuleFactory::Spawnable> spawnables);
void OnSelection(DropdownList* list);
void SetPosition(int x, int y);
void Draw();
DropdownList* GetList() { return mSpawnList; }
IDrawableModule* Spawn(int index);
std::string GetLabel() const { return mLabel; }
ModuleCategory GetCategory() const { return mModuleCategory; }
const std::vector<ModuleFactory::Spawnable>& GetElements() const { return mSpawnables; }
bool ShouldShowDecorators() const { return mShowDecorators; }
private:
std::string mLabel;
std::vector<ModuleFactory::Spawnable> mSpawnables;
int mSpawnIndex{ -1 };
DropdownList* mSpawnList{ nullptr };
IDropdownListener* mOwner{ nullptr };
ofVec2f mPos;
ModuleCategory mModuleCategory;
bool mShowDecorators{ false };
};
struct SpawnListManager
{
SpawnListManager(IDropdownListener* owner);
void SetModuleFactory(ModuleFactory* factory);
void SetUpPrefabsDropdown();
void SetUpPluginsDropdown();
const std::vector<SpawnList*>& GetDropdowns() const { return mDropdowns; }
SpawnList mInstrumentModules;
SpawnList mNoteModules;
SpawnList mSynthModules;
SpawnList mAudioModules;
SpawnList mModulatorModules;
SpawnList mPulseModules;
SpawnList mOtherModules;
SpawnList mPlugins;
SpawnList mPrefabs;
private:
std::vector<SpawnList*> mDropdowns;
juce::PluginDescription stump{};
};
class NewPatchConfirmPopup : public IDrawableModule, public IButtonListener
{
public:
NewPatchConfirmPopup() {}
void CreateUIControls() override;
void DrawModule() override;
bool HasTitleBar() const override { return false; }
void GetDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void ButtonClicked(ClickButton* button, double time) override;
private:
int mWidth{ 200 };
int mHeight{ 20 };
ClickButton* mConfirmButton{ nullptr };
ClickButton* mCancelButton{ nullptr };
};
class TitleBar : public IDrawableModule, public IDropdownListener, public IButtonListener, public IFloatSliderListener, public WindowCloseListener
{
public:
TitleBar();
~TitleBar();
void CreateUIControls() override;
bool HasTitleBar() const override { return false; }
bool AlwaysOnTop() override { return true; }
bool IsSingleton() const override { return true; }
void Poll() override;
HelpDisplay* GetHelpDisplay() { return mHelpDisplay; }
void SetModuleFactory(ModuleFactory* factory) { mSpawnLists.SetModuleFactory(factory); }
void ListLayouts();
void ManagePlugins();
const std::vector<SpawnList*>& GetSpawnLists() const { return mSpawnLists.GetDropdowns(); }
void DisplayTemporaryMessage(std::string message);
bool IsSaveable() override { return false; }
void OnWindowClosed() override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void DropdownClicked(DropdownList* list) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
static bool sShowInitialHelpOverlay;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void DrawModuleUnclipped() override;
void GetModuleDimensions(float& width, float& height) override;
void OnClicked(float x, float y, bool right) override;
bool MouseMoved(float x, float y) override;
bool HiddenByZoom() const;
float GetPixelWidth() const;
ClickButton* mPlayPauseButton{ nullptr };
ClickButton* mSaveLayoutButton{ nullptr };
ClickButton* mResetLayoutButton{ nullptr };
ClickButton* mSaveStateButton{ nullptr };
ClickButton* mSaveStateAsButton{ nullptr };
ClickButton* mLoadStateButton{ nullptr };
ClickButton* mWriteAudioButton{ nullptr };
DropdownList* mLoadLayoutDropdown{ nullptr };
ClickButton* mDisplayHelpButton{ nullptr };
ClickButton* mDisplayUserPrefsEditorButton{ nullptr };
Checkbox* mEventLookaheadCheckbox{ nullptr };
int mLoadLayoutIndex{ -1 };
Checkbox* mShouldAutosaveCheckbox{ nullptr };
HelpDisplay* mHelpDisplay{ nullptr };
SpawnListManager mSpawnLists;
bool mLeftCornerHovered{ false };
std::unique_ptr<PluginListWindow> mPluginListWindow;
NewPatchConfirmPopup mNewPatchConfirmPopup;
std::string mDisplayMessage;
double mDisplayMessageTime;
};
extern TitleBar* TheTitleBar;
``` | /content/code_sandbox/Source/TitleBar.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,335 |
```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
**/
//
// NoteDelayer.h
// Bespoke
//
// Created by Ryan Challinor on 5/3/16.
//
//
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "INoteSource.h"
#include "Slider.h"
#include "Transport.h"
class NoteDelayer : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public IAudioPoller
{
public:
NoteDelayer();
~NoteDelayer();
static IDrawableModule* Create() { return new NoteDelayer(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
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 NoteInfo
{
int mPitch{ 0 };
int mVelocity{ 0 };
double mTriggerTime{ 0 };
ModulationParameters mModulation;
};
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 108;
height = 22;
}
float mDelay{ .25 };
FloatSlider* mDelaySlider{ nullptr };
float mLastNoteOnTime{ 0 };
static const int kQueueSize = 500;
NoteInfo mInputNotes[kQueueSize]{};
int mConsumeIndex{ 0 };
int mAppendIndex{ 0 };
};
``` | /content/code_sandbox/Source/NoteDelayer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 566 |
```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
**/
//
// KompleteKontrol.cpp
// Bespoke
//
// Created by Ryan Challinor on 3/11/15.
//
//
#if BESPOKE_MAC
#include <CoreFoundation/CoreFoundation.h>
#endif
#include "KompleteKontrol.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "MidiController.h"
#include "FillSaveDropdown.h"
#include "PatchCableSource.h"
KompleteKontrol::KompleteKontrol()
: mInitialized(false)
, mKeyOffset(36)
, mNeedKeysUpdate(false)
, mController(nullptr)
{
mKontrol.Init();
mKontrol.QueueMessage("NIHWMainHandler", mKontrol.CreateMessage("NIGetServiceVersionMessage"));
TheScale->AddListener(this);
mKontrol.SetListener(this);
}
void KompleteKontrol::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mMidiControllerCable = new PatchCableSource(this, kConnectionType_Special);
mMidiControllerCable->AddTypeFilter("midicontroller");
mMidiControllerCable->SetManualPosition(95, 10);
AddPatchCableSource(mMidiControllerCable);
}
KompleteKontrol::~KompleteKontrol()
{
TheScale->RemoveListener(this);
}
void KompleteKontrol::Exit()
{
IDrawableModule::Exit();
mKontrol.Exit();
}
void KompleteKontrol::Poll()
{
mKontrol.Update();
if (!mInitialized && mKontrol.IsReady())
{
mNeedKeysUpdate = true;
mInitialized = true;
}
if (mNeedKeysUpdate)
UpdateKeys();
for (int i = 0; i < 9; ++i)
{
int control = i - 1 + 100;
if (i == 0)
control = 21;
UIControlConnection* connection = nullptr;
if (mController)
connection = mController->GetConnectionForControl(kMidiMessage_Control, control);
if (connection)
{
IUIControl* uicontrol = connection->GetUIControl();
if (uicontrol)
{
mTextBoxes[i].slider = true;
mTextBoxes[i].amount = uicontrol->GetMidiValue();
mTextBoxes[i].line1 = juce::String(uicontrol->Name()).toUpperCase().toStdString();
mTextBoxes[i].line2 = juce::String(uicontrol->GetDisplayValue(uicontrol->GetValue())).toUpperCase().toStdString();
if (mTextBoxes[i].line2.length() > 0 && mTextBoxes[i].line2[0] == '.')
mTextBoxes[i].line2 = " " + mTextBoxes[i].line2; //can't have a period as the first character, so add a space
}
else
{
mTextBoxes[i].slider = false;
mTextBoxes[i].line1 = "";
mTextBoxes[i].line2 = "";
}
}
else
{
mTextBoxes[i].slider = false;
mTextBoxes[i].line1 = "";
mTextBoxes[i].line2 = "";
}
}
if (mInitialized)
UpdateText();
}
void KompleteKontrol::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
DrawTextNormal("midicontroller:", 5, 13);
}
void KompleteKontrol::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
if (cableSource == mMidiControllerCable)
{
mController = dynamic_cast<MidiController*>(mMidiControllerCable->GetTarget());
}
}
void KompleteKontrol::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
mNoteOutput.PlayNote(time, pitch, velocity, voiceIdx, modulation);
mNeedKeysUpdate = true;
}
void KompleteKontrol::OnScaleChanged()
{
mNeedKeysUpdate = true;
}
void KompleteKontrol::UpdateKeys()
{
if (!mKontrol.IsReady())
return;
ofColor keys[61];
for (int i = 0; i < kNumKeys; ++i)
{
int pitch = i + mKeyOffset;
bool inScale = TheScale->MakeDiatonic(pitch) == pitch;
bool isRoot = pitch % TheScale->GetPitchesPerOctave() == TheScale->ScaleRoot();
bool isFifth = (pitch - 7) % TheScale->GetPitchesPerOctave() == TheScale->ScaleRoot();
bool isHeld = false;
bool isInPentatonic = pitch >= 0 && TheScale->IsInPentatonic(pitch);
std::list<int> heldNotes = mNoteOutput.GetHeldNotesList();
for (int iter : heldNotes)
{
if (iter == pitch)
isHeld = true;
}
if (isRoot)
keys[i] = ofColor(0, 255, 0);
else if (TheScale->GetPitchesPerOctave() != 12)
keys[i] = ofColor(40, 15, 0);
else if (isFifth && inScale)
keys[i] = ofColor(255, 0, 70);
else if (isInPentatonic)
keys[i] = ofColor(255, 70, 0);
else if (inScale)
keys[i] = ofColor(40, 15, 0);
else
keys[i] = ofColor::black;
if (isHeld)
{
if (keys[i].r == 0 && keys[i].g == 0 && keys[i].b == 0)
keys[i] = ofColor::blue; //out-of-key pressed notes turn blue
else
keys[i] = ofColor::red;
}
}
mKontrol.SetKeyLights(keys);
}
void KompleteKontrol::UpdateText()
{
if (mKontrol.IsReady() == false)
return;
uint16_t sliders[NUM_SLIDER_SEGMENTS];
std::string text;
for (int i = 0; i < 9; ++i)
{
int numPeriods1 = 0;
int numPeriods2 = 0;
for (int j = 0; j < 8; ++j)
{
uint16_t cell = 0;
if (mTextBoxes[i].slider)
{
if (j == 0)
cell |= 4;
if (mTextBoxes[i].amount > j / 8.0f)
cell |= 3;
if (j == 7 && mTextBoxes[i].amount > .999f)
cell |= 0xffff; //fill that ninth cell
}
if (j + 1 + numPeriods1 < mTextBoxes[i].line1.length() &&
mTextBoxes[i].line1[j + 1 + numPeriods1] == '.')
{
++numPeriods1;
cell |= 256;
}
if (j + 1 + numPeriods2 < mTextBoxes[i].line2.length() &&
mTextBoxes[i].line2[j + 1 + numPeriods2] == '.')
{
++numPeriods2;
cell |= 512;
}
sliders[i * 8 + j] = cell;
}
}
for (int i = 0; i < 9; ++i)
{
ofStringReplace(mTextBoxes[i].line1, ".", "");
for (int j = 0; j < 8; ++j)
{
if (j < mTextBoxes[i].line1.length())
text += mTextBoxes[i].line1[j];
else
text += " ";
}
}
for (int i = 0; i < 9; ++i)
{
ofStringReplace(mTextBoxes[i].line2, ".", "");
for (int j = 0; j < 8; ++j)
{
if (j < mTextBoxes[i].line2.length())
text += mTextBoxes[i].line2[j];
else
text += " ";
}
}
if (text != mCurrentText ||
memcmp(sliders, mCurrentSliders, NUM_SLIDER_SEGMENTS * sizeof(uint16_t)) != 0)
{
mKontrol.SetDisplay(sliders, text);
mCurrentText = text;
memcpy(mCurrentSliders, sliders, NUM_SLIDER_SEGMENTS * sizeof(uint16_t));
}
}
void KompleteKontrol::OnKontrolButton(int control, bool on)
{
if (mController)
{
if (control >= 24 && control <= 32) //the touch-sensitive encoder buttons
{
if (on)
{
int associatedControl = control + 76; //encoders are 100-108
UIControlConnection* connection = mController->GetConnectionForControl(kMidiMessage_Control, associatedControl);
if (connection)
{
IUIControl* uicontrol = connection->GetUIControl();
if (uicontrol)
uicontrol->StartBeacon();
}
}
}
else
{
if (control == 1) //fix collision with mod wheel
control = 98;
MidiControl c;
c.mDeviceName = 0;
c.mChannel = 1;
c.mControl = control;
c.mValue = on ? 127 : 0;
mController->OnMidiControl(c);
}
}
}
void KompleteKontrol::OnKontrolEncoder(int control, float change)
{
if (mController)
{
MidiControl c;
c.mDeviceName = 0;
c.mChannel = 1;
c.mControl = control + 100;
c.mValue = change > 0 ? 127 : 0;
mController->OnMidiControl(c);
}
}
void KompleteKontrol::OnKontrolOctave(int octave)
{
mKeyOffset = octave;
mNeedKeysUpdate = true;
}
void KompleteKontrol::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadString("controller", moduleInfo, "", FillDropdown<MidiController*>);
SetUpFromSaveData();
}
void KompleteKontrol::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
mMidiControllerCable->SetTarget(TheSynth->FindMidiController(mModuleSaveData.GetString("controller")));
}
``` | /content/code_sandbox/Source/KompleteKontrol.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,444 |
```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
**/
//
// CanvasControls.h
// Bespoke
//
// Created by Ryan Challinor on 12/30/14.
//
//
#pragma once
#include "IDrawableModule.h"
#include "TextEntry.h"
#include "ClickButton.h"
#include "Slider.h"
#include "DropdownList.h"
class Canvas;
class CanvasElement;
class CanvasControls : public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public IButtonListener, public ITextEntryListener, public IDropdownListener
{
public:
CanvasControls();
~CanvasControls();
static IDrawableModule* Create() { return new CanvasControls(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
bool HasTitleBar() const override { return false; }
bool CanMinimize() override { return false; }
void SetCanvas(Canvas* canvas);
void SetElement(CanvasElement* element);
void AllowDragModeSelection(bool allow);
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;
void TextEntryComplete(TextEntry* entry) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override {}
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool CanModuleTypeSaveState() const override { return false; }
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void PreDrawModule() override;
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
float mWidth{ 200 };
Canvas* mCanvas{ nullptr };
CanvasElement* mSelectedElement{ nullptr };
ClickButton* mRemoveElementButton{ nullptr };
TextEntry* mNumVisibleRowsEntry{ nullptr };
ClickButton* mClearButton{ nullptr };
float mDummyFloat{ 0 };
int mDummyInt{ 0 };
DropdownList* mDragModeSelector{ nullptr };
};
``` | /content/code_sandbox/Source/CanvasControls.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 606 |
```objective-c
#pragma once
#include <vector>
// THIS CLASS IS A TRANSLATION TO C++11 FROM THE REFERENCE
// JAVA IMPLEMENTATION OF THE IMPROVED PERLIN FUNCTION (see path_to_url~perlin/noise/)
// THE ORIGINAL JAVA IMPLEMENTATION IS COPYRIGHT 2002 KEN PERLIN
// I ADDED AN EXTRA METHOD THAT GENERATES A NEW PERMUTATION VECTOR (THIS IS NOT PRESENT IN THE ORIGINAL IMPLEMENTATION)
class PerlinNoise
{
// The permutation vector
std::vector<int> p;
public:
// Initialize with the reference values for the permutation vector
PerlinNoise();
// Generate a new permutation vector based on the value of seed
PerlinNoise(unsigned int seed);
// Get a noise value, for 2D images z can have any value
double noise(double x, double y, double z);
private:
double fade(double t);
double lerp(double t, double a, double b);
double grad(int hash, double x, double y, double z);
};
``` | /content/code_sandbox/Source/PerlinNoise.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 221 |
```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
**/
//
// LoopStorer.h
// Bespoke
//
// Created by Ryan Challinor on 1/22/15.
//
//
#pragma once
#include "EnvOscillator.h"
#include "IDrawableModule.h"
#include "Checkbox.h"
#include "Slider.h"
#include "DropdownList.h"
#include "Transport.h"
#include "ClickButton.h"
#include "OpenFrameworksPort.h"
class Sample;
class Looper;
class ChannelBuffer;
class LoopStorer : public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public IDropdownListener, public IButtonListener, public ITimeListener
{
public:
LoopStorer();
~LoopStorer();
static IDrawableModule* Create() { return new LoopStorer(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void Poll() override;
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
int GetRowY(int idx);
Looper* GetLooper() { return mLooper; }
int GetQueuedBufferIdx() { return mQueuedSwapBufferIdx; }
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void OnTimeEvent(double time) 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 DropdownClicked(DropdownList* list) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 0; }
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void SwapBuffer(int swapToIdx);
class SampleData
{
public:
SampleData();
~SampleData();
void Init(LoopStorer* storer, int index);
void Draw();
ChannelBuffer* mBuffer{ nullptr };
int mNumBars{ 1 };
Checkbox* mSelectCheckbox{ nullptr };
LoopStorer* mLoopStorer{ nullptr };
int mIndex{ 0 };
int mBufferLength{ -1 };
bool mIsCurrentBuffer{ false };
};
Looper* mLooper{ nullptr };
Checkbox* mRewriteToSelectionCheckbox{ nullptr };
bool mRewriteToSelection{ false };
DropdownList* mQuantizationDropdown{ nullptr };
NoteInterval mQuantization{ NoteInterval::kInterval_None };
int mQueuedSwapBufferIdx{ -1 };
ofMutex mSwapMutex;
bool mIsSwapping{ false };
ClickButton* mClearButton{ nullptr };
ofMutex mLoadMutex;
std::vector<SampleData*> mSamples;
int mCurrentBufferIdx{ 0 };
PatchCableSource* mLooperCable{ nullptr };
};
``` | /content/code_sandbox/Source/LoopStorer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 873 |
```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
**/
//
// CircleSequencer.h
// Bespoke
//
// Created by Ryan Challinor on 3/3/15.
//
//
#pragma once
#include <iostream>
#include "Transport.h"
#include "UIGrid.h"
#include "Slider.h"
#include "DropdownList.h"
#include "IDrawableModule.h"
#include "INoteSource.h"
#include "TextEntry.h"
class CircleSequencer;
#define CIRCLE_SEQUENCER_MAX_STEPS 10
class CircleSequencerRing
{
public:
CircleSequencerRing(CircleSequencer* owner, int index);
void Draw();
void OnClicked(float x, float y, bool right);
void MouseReleased();
void MouseMoved(float x, float y);
void CreateUIControls();
void OnTransportAdvanced(float amount);
void SaveState(FileStreamOut& out);
void LoadState(FileStreamIn& in);
private:
float GetRadius() { return 90 - mIndex * 15; }
int GetStepIndex(int x, int y, float& radiusOut);
int mLength{ 4 };
DropdownList* mLengthSelector{ nullptr };
int mPitch{ 0 };
TextEntry* mNoteSelector{ nullptr };
CircleSequencer* mOwner{ nullptr };
int mIndex{ 0 };
std::array<float, CIRCLE_SEQUENCER_MAX_STEPS> mSteps{};
float mOffset{ 0 };
FloatSlider* mOffsetSlider{ nullptr };
int mCurrentlyClickedStepIdx{ -1 };
int mHighlightStepIdx{ -1 };
float mLastMouseRadius{ -1 };
};
class CircleSequencer : public IDrawableModule, public INoteSource, public IAudioPoller, public IFloatSliderListener, public IDropdownListener, public ITextEntryListener
{
public:
CircleSequencer();
~CircleSequencer();
static IDrawableModule* Create() { return new CircleSequencer(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetEnabled(bool on) override { mEnabled = on; }
//IAudioPoller
void OnTransportAdvanced(float amount) override;
//IClickable
void MouseReleased() override;
bool MouseMoved(float x, float y) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void TextEntryComplete(TextEntry* entry) override {}
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 1; }
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 = 400;
height = 200;
}
void OnClicked(float x, float y, bool right) override;
std::vector<CircleSequencerRing*> mCircleSequencerRings;
};
``` | /content/code_sandbox/Source/CircleSequencer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 860 |
```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
**/
//
// SampleFinder.h
// modularSynth
//
// Created by Ryan Challinor on 6/18/13.
//
//
#pragma once
#include <iostream>
#include "IAudioSource.h"
#include "INoteReceiver.h"
#include "IDrawableModule.h"
#include "Checkbox.h"
#include "Slider.h"
#include "DropdownList.h"
#include "ClickButton.h"
#include "SampleDrawer.h"
class Sample;
class SampleFinder : public IAudioSource, public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public IDropdownListener, public IButtonListener, public INoteReceiver
{
public:
SampleFinder();
~SampleFinder();
static IDrawableModule* Create() { return new SampleFinder(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendCC(int control, int value, int voiceIdx = -1) override {}
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//IDrawableModule
void FilesDropped(std::vector<std::string> files, int x, int 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 FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void DropdownClicked(DropdownList* list) override;
void DropdownUpdated(DropdownList* list, 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:
void UpdateSample();
void DoWrite();
void UpdateZoomExtents();
float GetSpeed();
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
Sample* mSample{ nullptr };
float mVolume{ .6 };
FloatSlider* mVolumeSlider{ nullptr };
float* mWriteBuffer{ nullptr };
bool mPlay{ false };
Checkbox* mPlayCheckbox{ nullptr };
bool mLoop{ true };
Checkbox* mLoopCheckbox{ nullptr };
int mMeasureEarly{ 0 };
bool mEditMode{ true };
Checkbox* mEditCheckbox{ nullptr };
int mClipStart{ 0 };
IntSlider* mClipStartSlider{ nullptr };
int mClipEnd{ 1 };
IntSlider* mClipEndSlider{ nullptr };
float mZoomStart{ 0 };
float mZoomEnd{ 1 };
float mOffset{ 0 };
FloatSlider* mOffsetSlider{ nullptr };
int mNumBars{ 1 };
IntSlider* mNumBarsSlider{ nullptr };
ClickButton* mWriteButton{ nullptr };
double mPlayhead{ 0 };
bool mWantWrite{ false };
ClickButton* mDoubleLengthButton{ nullptr };
ClickButton* mHalveLengthButton{ nullptr };
SampleDrawer mSampleDrawer;
bool mReverse{ false };
Checkbox* mReverseCheckbox{ nullptr };
};
``` | /content/code_sandbox/Source/SampleFinder.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 899 |
```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
**/
/*
==============================================================================
NoteLatch.h
Created: 11 Apr 2020 3:28:14pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
class NoteLatch : public NoteEffectBase, public IDrawableModule
{
public:
NoteLatch();
static IDrawableModule* Create() { return new NoteLatch(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
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;
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 = 90;
height = 0;
}
bool mNoteState[128]{};
};
``` | /content/code_sandbox/Source/NoteLatch.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 390 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
Waveshaper.cpp
Created: 1 Dec 2019 10:01:56pm
Author: Ryan Challinor
==============================================================================
*/
#include "Waveshaper.h"
#include "ModularSynth.h"
#include "Profiler.h"
namespace
{
const int kGraphWidth = 100;
const int kGraphHeight = 100;
const int kGraphX = 115;
const int kGraphY = 18;
}
Waveshaper::Waveshaper()
: IAudioProcessor(gBufferSize)
{
}
void Waveshaper::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mTextEntry = new TextEntry(this, "y=", 2, 2, MAX_TEXTENTRY_LENGTH - 1, &mEntryString);
mTextEntry->SetFlexibleWidth(true);
mTextEntry->DrawLabel(true);
mRescaleSlider = new FloatSlider(this, "rescale", mTextEntry, kAnchor_Below, 110, 15, &mRescale, .1f, 10);
mASlider = new FloatSlider(this, "a", mRescaleSlider, kAnchor_Below, 110, 15, &mA, -10, 10, 4);
mBSlider = new FloatSlider(this, "b", mASlider, kAnchor_Below, 110, 15, &mB, -10, 10, 4);
mCSlider = new FloatSlider(this, "c", mBSlider, kAnchor_Below, 110, 15, &mC, -10, 10, 4);
mDSlider = new FloatSlider(this, "d", mCSlider, kAnchor_Below, 110, 15, &mD, -10, 10, 4);
mESlider = new FloatSlider(this, "e", mDSlider, kAnchor_Below, 110, 15, &mE, -10, 10, 4);
mSymbolTable.add_variable("x", mExpressionInput);
mSymbolTable.add_variable("x1", mHistPre1);
mSymbolTable.add_variable("x2", mHistPre2);
mSymbolTable.add_variable("y1", mHistPost1);
mSymbolTable.add_variable("y2", mHistPost2);
mSymbolTable.add_variable("t", mT);
mSymbolTable.add_variable("a", mA);
mSymbolTable.add_variable("b", mB);
mSymbolTable.add_variable("c", mC);
mSymbolTable.add_variable("d", mD);
mSymbolTable.add_variable("e", mE);
mSymbolTable.add_constants();
mExpression.register_symbol_table(mSymbolTable);
mSymbolTableDraw.add_variable("x", mExpressionInputDraw);
mSymbolTableDraw.add_variable("x1", mExpressionInputDraw);
mSymbolTableDraw.add_variable("x2", mExpressionInputDraw);
mSymbolTableDraw.add_variable("y1", mExpressionInputDraw);
mSymbolTableDraw.add_variable("y2", mExpressionInputDraw);
mSymbolTableDraw.add_variable("t", mT);
mSymbolTableDraw.add_variable("a", mA);
mSymbolTableDraw.add_variable("b", mB);
mSymbolTableDraw.add_variable("c", mC);
mSymbolTableDraw.add_variable("d", mD);
mSymbolTableDraw.add_variable("e", mE);
mSymbolTableDraw.add_constants();
mExpressionDraw.register_symbol_table(mSymbolTableDraw);
TextEntryComplete(mTextEntry);
}
Waveshaper::~Waveshaper()
{
}
void Waveshaper::Process(double time)
{
PROFILER(Waveshaper);
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;
}
float max = 0;
float min = 0;
int bufferSize = GetBuffer()->BufferSize();
ChannelBuffer* out = target->GetBuffer();
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
{
float* buffer = GetBuffer()->GetChannel(ch);
if (mExpressionValid)
{
for (int i = 0; i < bufferSize; ++i)
{
ComputeSliders(i);
mExpressionInput = buffer[i] * mRescale;
mHistPre1 = mBiquadState[ch].mHistPre1;
mHistPre2 = mBiquadState[ch].mHistPre2;
mHistPost1 = mBiquadState[ch].mHistPost1;
mHistPost2 = mBiquadState[ch].mHistPost2;
if (mExpressionInput > max)
max = mExpressionInput;
if (mExpressionInput < min)
min = mExpressionInput;
mT = (gTime + i * gInvSampleRateMs) * .001;
buffer[i] = mExpression.value() / mRescale;
mBiquadState[ch].mHistPre2 = mBiquadState[ch].mHistPre1;
mBiquadState[ch].mHistPre1 = mExpressionInput;
mBiquadState[ch].mHistPost2 = mBiquadState[ch].mHistPost1;
mBiquadState[ch].mHistPost1 = ofClamp(buffer[i], -1, 1); //keep feedback from spiraling out of control
}
}
Add(out->GetChannel(ch), buffer, bufferSize);
GetVizBuffer()->WriteChunk(buffer, bufferSize, ch);
}
mSmoothMax = max > mSmoothMax ? max : ofLerp(mSmoothMax, max, .01f);
mSmoothMin = min < mSmoothMin ? min : ofLerp(mSmoothMin, min, .01f);
GetBuffer()->Reset();
}
void Waveshaper::TextEntryComplete(TextEntry* entry)
{
exprtk::parser<float> parser;
mExpressionValid = parser.compile(mEntryString, mExpression);
if (mExpressionValid)
parser.compile(mEntryString, mExpressionDraw);
}
void Waveshaper::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
ofPushStyle();
ofSetColor(80, 80, 80, 80 * gModuleDrawAlpha);
ofFill();
ofRect(kGraphX, kGraphY, kGraphWidth, kGraphHeight);
if (!mExpressionValid)
{
ofSetColor(255, 0, 0, 60);
ofFill();
ofRect(mTextEntry->GetRect(true));
}
else
{
ofPushMatrix();
ofClipWindow(kGraphX, kGraphY, kGraphWidth, kGraphHeight, true);
ofSetColor(0, 255, 0, gModuleDrawAlpha);
ofNoFill();
ofBeginShape();
for (int i = 0; i < 100; ++i)
{
mExpressionInputDraw = ofMap(i, 0, kGraphWidth, -1, 1);
ofVertex(i + kGraphX, ofMap(mExpressionDraw.value(), -1, 1, kGraphHeight, 0) + kGraphY);
}
ofEndShape();
ofSetColor(245, 58, 135);
mExpressionInputDraw = mSmoothMin;
ofCircle(kGraphX + ofMap(mSmoothMin, -1, 1, 0, kGraphWidth), ofMap(mExpressionDraw.value(), -1, 1, kGraphHeight, 0) + kGraphY, 3);
mExpressionInputDraw = mSmoothMax;
ofCircle(kGraphX + ofMap(mSmoothMax, -1, 1, 0, kGraphWidth), ofMap(mExpressionDraw.value(), -1, 1, kGraphHeight, 0) + kGraphY, 3);
ofPopMatrix();
}
ofPopStyle();
mTextEntry->Draw();
mRescaleSlider->Draw();
mASlider->Draw();
mBSlider->Draw();
mCSlider->Draw();
mDSlider->Draw();
mESlider->Draw();
}
void Waveshaper::GetModuleDimensions(float& w, float& h)
{
w = MAX(kGraphX + kGraphWidth + 2, 4 + mTextEntry->GetRect().width);
h = kGraphY + kGraphHeight;
}
void Waveshaper::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void Waveshaper::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
``` | /content/code_sandbox/Source/Waveshaper.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,115 |
```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
**/
//
// NoteLooper.h
// modularSynth
//
// Created by Ryan Challinor on 3/31/13.
//
//
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "Transport.h"
#include "Checkbox.h"
#include "Slider.h"
#include "IDrawableModule.h"
#include "DropdownList.h"
#include "MidiDevice.h"
#include "Scale.h"
#include "Canvas.h"
#include "CanvasElement.h"
#include "ClickButton.h"
class NoteLooper : public IDrawableModule, public NoteEffectBase, public IAudioPoller, public IFloatSliderListener, public IIntSliderListener, public IDropdownListener, public IButtonListener
{
public:
NoteLooper();
~NoteLooper();
static IDrawableModule* Create() { return new NoteLooper(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
bool IsResizable() const override { return true; }
void Resize(float w, float h) override;
bool DrawToPush2Screen() override;
int GetNumMeasures() const { return mNumMeasures; }
void SetNumMeasures(int numMeasures);
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
//IAudioPoller
void OnTransportAdvanced(float amount) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
//IIntSliderListener
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
//IDropdownListener
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
//IButtonListener
void ButtonClicked(ClickButton* button, 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:
double GetCurPos(double time) const;
NoteCanvasElement* AddNote(double measurePos, int pitch, int velocity, double length, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters());
int GetNewVoice(int voiceIdx);
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
struct SavedPattern
{
ClickButton* mStoreButton{ nullptr };
ClickButton* mLoadButton{ nullptr };
std::vector<CanvasElement*> mNotes;
};
float mWidth{ 370 };
float mHeight{ 140 };
int mMinRow{ 127 };
int mMaxRow{ 0 };
bool mWrite{ false };
Checkbox* mWriteCheckbox{ nullptr };
bool mDeleteOrMute{ false };
Checkbox* mDeleteOrMuteCheckbox{ nullptr };
IntSlider* mNumMeasuresSlider{ nullptr };
int mNumMeasures{ 1 };
std::vector<CanvasElement*> mNoteChecker{ 128 };
std::array<NoteCanvasElement*, 128> mInputNotes{};
std::array<NoteCanvasElement*, 128> mCurrentNotes{};
Canvas* mCanvas{ nullptr };
ClickButton* mClearButton{ nullptr };
int mVoiceRoundRobin{ kNumVoices - 1 };
bool mAllowLookahead{ false };
std::array<ModulationParameters, kNumVoices + 1> mVoiceModulations{};
std::array<int, kNumVoices> mVoiceMap{};
std::array<SavedPattern, 4> mSavedPatterns;
};
``` | /content/code_sandbox/Source/NoteLooper.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,020 |
```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.cpp
Created: 12 Dec 2020 11:00:20pm
Author: Ryan Challinor
==============================================================================
*/
#include "PlaySequencer.h"
#include "OpenFrameworksPort.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
PlaySequencer::PlaySequencer()
{
mNoteOffScheduler.mOwner = this;
}
void PlaySequencer::Init()
{
IDrawableModule::Init();
mTransportListenerInfo = TheTransport->AddListener(this, mInterval, OffsetInfo(0, true), false);
TheTransport->AddListener(&mNoteOffScheduler, mInterval, OffsetInfo(TheTransport->GetMeasureFraction(mInterval) * .5f, false), false);
}
void PlaySequencer::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mGridControlTarget = new GridControlTarget(this, "grid", mWidth - 50, 4);
float width, height;
UIBLOCK0();
DROPDOWN(mIntervalSelector, "interval", (int*)(&mInterval), 50);
UIBLOCK_SHIFTRIGHT();
DROPDOWN(mNumMeasuresSelector, "measures", &mNumMeasures, 50);
UIBLOCK_NEWLINE();
CHECKBOX(mWriteCheckbox, "write", &mWrite);
CHECKBOX(mNoteRepeatCheckbox, "note repeat", &mNoteRepeat);
UIBLOCK_SHIFTRIGHT();
UIBLOCK_SHIFTUP();
CHECKBOX(mLinkColumnsCheckbox, "link columns", &mLinkColumns);
ENDUIBLOCK(width, height);
UIBLOCK(3, height + 3, 45);
for (size_t i = 0; i < mSavedPatterns.size(); ++i)
{
BUTTON(mSavedPatterns[i].mStoreButton, ("store" + ofToString(i)).c_str());
BUTTON(mSavedPatterns[i].mLoadButton, ("load" + ofToString(i)).c_str());
UIBLOCK_NEWCOLUMN();
}
ENDUIBLOCK(width, height);
ofLog() << "width: " << width << " height: " << height;
mGrid = new UIGrid("uigrid", 3, height + 3, mWidth - 16, 150, TheTransport->CountInStandardMeasure(mInterval), (int)mLanes.size(), this);
mGrid->SetFlip(true);
mGrid->SetGridMode(UIGrid::kMultisliderBipolar);
mGrid->SetRequireShiftForMultislider(true);
mGrid->SetRestrictDragToRow(true);
ofRectangle gridRect = mGrid->GetRect(true);
for (int i = 0; i < (int)mLanes.size(); ++i)
{
ofVec2f cellPos = mGrid->GetCellPosition(mGrid->GetCols() - 1, i) + mGrid->GetPosition(true);
mLanes[i].mMuteOrEraseCheckbox = new Checkbox(this, ("mute/delete" + ofToString(i)).c_str(), gridRect.getMaxX() + 3, cellPos.y + 1, &mLanes[i].mMuteOrErase);
mLanes[i].mMuteOrEraseCheckbox->SetDisplayText(false);
mLanes[i].mMuteOrEraseCheckbox->SetBoxSize(10);
}
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);
mNumMeasuresSelector->AddLabel("1", 1);
mNumMeasuresSelector->AddLabel("2", 2);
mNumMeasuresSelector->AddLabel("4", 4);
mNumMeasuresSelector->AddLabel("8", 8);
mNumMeasuresSelector->AddLabel("16", 16);
}
PlaySequencer::~PlaySequencer()
{
TheTransport->RemoveListener(this);
TheTransport->RemoveListener(&mNoteOffScheduler);
}
void PlaySequencer::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mGridControlTarget->Draw();
mIntervalSelector->Draw();
mWriteCheckbox->Draw();
mNoteRepeatCheckbox->Draw();
mLinkColumnsCheckbox->Draw();
mNumMeasuresSelector->Draw();
for (size_t i = 0; i < mLanes.size(); ++i)
mLanes[i].mMuteOrEraseCheckbox->Draw();
for (size_t i = 0; i < mSavedPatterns.size(); ++i)
{
mSavedPatterns[i].mStoreButton->Draw();
mSavedPatterns[i].mLoadButton->Draw();
if (mSavedPatterns[i].mHasSequence)
{
ofPushStyle();
ofFill();
ofSetColor(0, 255, 0, 80);
ofRectangle rect = mSavedPatterns[i].mLoadButton->GetRect(K(local));
ofRect(rect);
ofPopStyle();
}
}
mGrid->Draw();
ofPushStyle();
ofSetColor(255, 0, 0, 50);
ofFill();
for (int i = 0; i < (int)mLanes.size(); ++i)
{
if (mLanes[i].mMuteOrErase)
{
ofRectangle gridRect = mGrid->GetRect(true);
ofVec2f cellPos = mGrid->GetCellPosition(0, i) + mGrid->GetPosition(true);
ofRect(cellPos.x, cellPos.y + 1, gridRect.width, gridRect.height / mGrid->GetRows());
}
}
ofPopStyle();
}
void PlaySequencer::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
if (right)
return;
mGrid->TestClick(x, y, right);
}
void PlaySequencer::MouseReleased()
{
IDrawableModule::MouseReleased();
mGrid->MouseReleased();
}
bool PlaySequencer::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
mGrid->NotifyMouseMoved(x, y);
return false;
}
void PlaySequencer::CheckboxUpdated(Checkbox* checkbox, double time)
{
for (size_t i = 0; i < mLanes.size(); ++i)
{
if (checkbox == mLanes[i].mMuteOrEraseCheckbox)
{
if (mLinkColumns)
{
for (size_t j = 0; j < mLanes.size(); ++j)
{
if (j % 4 == i % 4)
mLanes[j].mMuteOrErase = mLanes[i].mMuteOrErase;
}
}
}
}
}
void PlaySequencer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (!mEnabled)
return;
if (pitch < mLanes.size())
{
if (velocity > 0)
{
mLanes[pitch].mInputVelocity = velocity;
}
else
{
if (mNoteRepeat)
mLanes[pitch].mInputVelocity = 0;
}
}
}
void PlaySequencer::OnTimeEvent(double time)
{
if (!mEnabled)
return;
int step = GetStep(time);
mGrid->SetHighlightCol(time, step);
for (int i = 0; i < (int)mLanes.size(); ++i)
{
float gridVal = mGrid->GetVal(step, i);
int playVelocity = (int)(gridVal * 127);
if (mLanes[i].mMuteOrErase)
{
playVelocity = 0;
if (mWrite)
mGrid->SetVal(step, i, 0);
}
if (mLanes[i].mInputVelocity > 0)
{
float velMult;
switch (GetVelocityLevel())
{
case 1: velMult = mVelocityLight; break;
case 2: velMult = mVelocityMed; break;
default:
case 3: velMult = mVelocityFull; break;
}
playVelocity = mLanes[i].mInputVelocity * velMult;
if (mWrite)
mGrid->SetVal(step, i, playVelocity / 127.0f);
if (!mNoteRepeat)
mLanes[i].mInputVelocity = 0;
}
if (playVelocity > 0 && mLanes[i].mIsPlaying == false)
{
PlayNoteOutput(time, i, playVelocity);
mLanes[i].mIsPlaying = true;
}
if (mSustain)
{
if (mLanes[i].mIsPlaying && playVelocity == 0)
{
PlayNoteOutput(time, i, 0);
mLanes[i].mIsPlaying = false;
}
}
}
UpdateLights();
}
void PlaySequencer::NoteOffScheduler::OnTimeEvent(double time)
{
if (mOwner->mSustain)
return;
for (int i = 0; i < (int)mOwner->mLanes.size(); ++i)
{
if (mOwner->mLanes[i].mIsPlaying)
{
mOwner->PlayNoteOutput(time, i, 0);
mOwner->mLanes[i].mIsPlaying = false;
}
}
mOwner->UpdateLights(true);
}
int PlaySequencer::GetStep(double time)
{
int step = TheTransport->GetSyncedStep(time, this, mTransportListenerInfo, mGrid->GetCols());
return step;
}
void PlaySequencer::UpdateInterval()
{
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
{
transportListenerInfo->mInterval = mInterval;
transportListenerInfo->mOffsetInfo = OffsetInfo(0, false);
}
TransportListenerInfo* noteOffListenerInfo = TheTransport->GetListenerInfo(&mNoteOffScheduler);
if (noteOffListenerInfo != nullptr)
{
noteOffListenerInfo->mInterval = mInterval;
noteOffListenerInfo->mOffsetInfo = OffsetInfo(TheTransport->GetMeasureFraction(mInterval) * .5f, false);
}
UpdateNumMeasures(mNumMeasures);
}
void PlaySequencer::UpdateNumMeasures(int oldNumMeasures)
{
int oldSteps = mGrid->GetCols();
int stepsPerMeasure = TheTransport->GetStepsPerMeasure(this);
mGrid->SetGrid(stepsPerMeasure * mNumMeasures, (int)mLanes.size());
if (mNumMeasures > oldNumMeasures)
{
for (int i = 1; i < mNumMeasures / oldNumMeasures; ++i)
{
for (int j = 0; j < oldSteps; ++j)
{
for (int row = 0; row < mGrid->GetRows(); ++row)
{
mGrid->SetVal(j + i * oldSteps, row, mGrid->GetVal(j, row));
}
}
}
}
}
void PlaySequencer::UpdateLights(bool betweener)
{
if (mGridControlTarget->GetGridController() == nullptr)
return;
IGridController* gridController = mGridControlTarget->GetGridController();
for (int i = 0; i < 4; ++i)
gridController->SetLight(i, 0, mWrite ? kGridColor2Bright : kGridColorOff);
for (int i = 0; i < 3; ++i)
gridController->SetLight(i, 1, mNoteRepeat && !betweener ? kGridColor2Bright : kGridColorOff);
gridController->SetLight(3, 1, mLinkColumns ? kGridColor2Bright : kGridColorOff);
gridController->SetLight(0, 2, mNumMeasures == 1 ? kGridColor3Bright : kGridColorOff);
gridController->SetLight(1, 2, mNumMeasures == 2 ? kGridColor3Bright : kGridColorOff);
gridController->SetLight(2, 2, mNumMeasures == 4 ? kGridColor3Bright : kGridColorOff);
gridController->SetLight(3, 2, mNumMeasures == 8 ? kGridColor3Bright : kGridColorOff);
gridController->SetLight(0, 3, GetVelocityLevel() == 1 || GetVelocityLevel() == 3 ? kGridColor2Bright : kGridColorOff);
gridController->SetLight(1, 3, GetVelocityLevel() == 2 || GetVelocityLevel() == 3 ? kGridColor2Bright : kGridColorOff);
gridController->SetLight(3, 3, mClearLane ? kGridColor1Bright : kGridColorOff);
int step = GetStep(gTime);
for (int i = 0; i < 16; ++i)
{
int x = (i / 4) % 4 + 4;
int y = i % 4;
gridController->SetLight(x, y, step % 16 == i ? kGridColor3Bright : kGridColorOff);
}
for (int i = 0; i < (int)mLanes.size(); ++i)
{
int x = i % 4 * 2;
int y = 7 - i / 4;
gridController->SetLight(x, y, mLanes[i].mIsPlaying ? kGridColor2Bright : kGridColorOff);
gridController->SetLight(x + 1, y, mLanes[i].mMuteOrErase ? kGridColorOff : kGridColor1Bright);
}
}
int PlaySequencer::GetVelocityLevel()
{
if (mUseLightVelocity && !mUseMedVelocity)
return 1;
if (mUseMedVelocity && !mUseLightVelocity)
return 2;
return 3;
}
void PlaySequencer::OnControllerPageSelected()
{
UpdateLights();
}
void PlaySequencer::OnGridButton(int x, int y, float velocity, IGridController* grid)
{
if (grid == mGridControlTarget->GetGridController())
{
bool press = velocity > 0;
if (x >= 0 && y >= 0)
{
if (press && y == 0 && x < 4)
mWrite = !mWrite;
if (press && y == 1 && x < 3)
mNoteRepeat = !mNoteRepeat;
if (press && y == 1 && x == 3)
mLinkColumns = !mLinkColumns;
if (press && y == 2)
{
int newNumMeasures = mNumMeasures;
if (x == 0)
newNumMeasures = 1;
if (x == 1)
newNumMeasures = 2;
if (x == 2)
newNumMeasures = 4;
if (x == 3)
newNumMeasures = 8;
if (newNumMeasures != mNumMeasures)
{
int oldNumMeasures = mNumMeasures;
mNumMeasures = newNumMeasures;
UpdateNumMeasures(oldNumMeasures);
}
}
if (x == 0 && y == 3)
mUseLightVelocity = press;
if (x == 1 && y == 3)
mUseMedVelocity = press;
if (x == 3 && y == 3)
mClearLane = press;
if (x == 2 && y == 3 && mClearLane)
mGrid->Clear();
if (x >= 4 && y == 0)
ButtonClicked(mSavedPatterns[x - 4].mStoreButton, NextBufferTime(false));
if (x >= 4 && y == 1)
ButtonClicked(mSavedPatterns[x - 4].mLoadButton, NextBufferTime(false));
if (y >= 4)
{
int pitch = x / 2 + (7 - y) * 4;
if (x % 2 == 0)
{
if (velocity > 0)
{
mLanes[pitch].mInputVelocity = velocity * 127;
}
else
{
if (mNoteRepeat)
mLanes[pitch].mInputVelocity = 0;
}
}
else if (x % 2 == 1)
{
mLanes[pitch].mMuteOrErase = press;
if (mLinkColumns)
{
for (size_t i = 0; i < mLanes.size(); ++i)
{
if (i % 4 == pitch % 4)
mLanes[i].mMuteOrErase = press;
}
}
if (press && mClearLane)
{
for (int i = 0; i < mGrid->GetCols(); ++i)
{
mGrid->SetVal(i, pitch, 0);
if (mLinkColumns)
{
for (int j = 0; j < (int)mLanes.size(); ++j)
{
if (j % 4 == pitch % 4)
mGrid->SetVal(i, j, 0);
}
}
}
}
}
}
UpdateLights();
}
}
}
void PlaySequencer::ButtonClicked(ClickButton* button, double time)
{
for (size_t i = 0; i < mSavedPatterns.size(); ++i)
{
if (button == mSavedPatterns[i].mStoreButton)
{
mSavedPatterns[i].mNumMeasures = mNumMeasures;
mSavedPatterns[i].mData = mGrid->GetData();
mSavedPatterns[i].mHasSequence = false;
for (auto& cell : mSavedPatterns[i].mData)
{
if (cell != 0)
{
mSavedPatterns[i].mHasSequence = true;
break;
}
}
}
if (button == mSavedPatterns[i].mLoadButton)
{
mNumMeasures = mSavedPatterns[i].mNumMeasures;
UpdateNumMeasures(mNumMeasures);
mGrid->SetData(mSavedPatterns[i].mData);
}
}
}
void PlaySequencer::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mIntervalSelector)
UpdateInterval();
if (list == mNumMeasuresSelector)
UpdateNumMeasures(oldVal);
}
void PlaySequencer::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
namespace
{
const float extraW = 25;
const float extraH = 100;
}
void PlaySequencer::GetModuleDimensions(float& width, float& height)
{
width = mGrid->GetWidth() + extraW;
height = mGrid->GetHeight() + extraH;
}
void PlaySequencer::Resize(float w, float h)
{
w = MAX(w - extraW, 219);
h = MAX(h - extraH, 111);
SetGridSize(w, h);
ofRectangle gridRect = mGrid->GetRect(true);
for (int i = 0; i < (int)mLanes.size(); ++i)
{
ofVec2f cellPos = mGrid->GetCellPosition(mGrid->GetCols() - 1, i) + mGrid->GetPosition(true);
mLanes[i].mMuteOrEraseCheckbox->SetPosition(gridRect.getMaxX() + 3, cellPos.y + 1);
mLanes[i].mMuteOrEraseCheckbox->SetBoxSize(MAX(10, mGrid->GetHeight() / mLanes.size()));
}
}
void PlaySequencer::SetGridSize(float w, float h)
{
mGrid->SetDimensions(w, h);
}
void PlaySequencer::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadBool("sustain", moduleInfo, false);
mModuleSaveData.LoadFloat("velocity_full", moduleInfo, 1, 0, 1, K(isTextField));
mModuleSaveData.LoadFloat("velocity_med", moduleInfo, .5f, 0, 1, K(isTextField));
mModuleSaveData.LoadFloat("velocity_light", moduleInfo, .25f, 0, 1, K(isTextField));
SetUpFromSaveData();
}
void PlaySequencer::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
mSustain = mModuleSaveData.GetBool("sustain");
mVelocityFull = mModuleSaveData.GetFloat("velocity_full");
mVelocityMed = mModuleSaveData.GetFloat("velocity_med");
mVelocityLight = mModuleSaveData.GetFloat("velocity_light");
}
void PlaySequencer::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
mGrid->SaveState(out);
out << (int)mSavedPatterns.size();
for (size_t i = 0; i < mSavedPatterns.size(); ++i)
{
out << mSavedPatterns[i].mNumMeasures;
out << mSavedPatterns[i].mHasSequence;
out << (int)mSavedPatterns[i].mData.size();
for (auto& data : mSavedPatterns[i].mData)
out << data;
}
}
void PlaySequencer::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());
mGrid->LoadState(in);
int numPatterns;
in >> numPatterns;
LoadStateValidate(numPatterns == mSavedPatterns.size());
for (size_t i = 0; i < mSavedPatterns.size(); ++i)
{
in >> mSavedPatterns[i].mNumMeasures;
in >> mSavedPatterns[i].mHasSequence;
int size;
in >> size;
LoadStateValidate(size == (int)mSavedPatterns[i].mData.size());
for (int j = 0; j < size; ++j)
in >> mSavedPatterns[i].mData[j];
}
}
``` | /content/code_sandbox/Source/PlaySequencer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 5,242 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Snapshots.cpp
// modularSynth
//
// Created by Ryan Challinor on 7/29/13.
//
//
#include "Snapshots.h"
#include "ModularSynth.h"
#include "Slider.h"
#include "ofxJSONElement.h"
#include "PatchCableSource.h"
#include "juce_core/juce_core.h"
std::vector<IUIControl*> Snapshots::sSnapshotHighlightControls;
Snapshots::Snapshots()
{
}
Snapshots::~Snapshots()
{
TheTransport->RemoveAudioPoller(this);
}
void Snapshots::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mGrid = new UIGrid("uigrid", 5, 38, 120, 50, 8, 3, this);
mBlendTimeSlider = new FloatSlider(this, "blend", 5, 20, 70, 15, &mBlendTime, 0, 5000);
mCurrentSnapshotSelector = new DropdownList(this, "snapshot", 35, 3, &mCurrentSnapshot, 64);
mRandomizeButton = new ClickButton(this, "random", 78, 20);
mAddButton = new ClickButton(this, "add", 101, 3);
mClearButton = new ClickButton(this, "clear", mAddButton, kAnchor_Right);
mStoreCheckbox = new Checkbox(this, "store", mClearButton, kAnchor_Right, &mStoreMode);
mDeleteCheckbox = new Checkbox(this, "delete", mStoreCheckbox, kAnchor_Right, &mDeleteMode);
mAutoStoreOnSwitchCheckbox = new Checkbox(this, "auto-store on switch", mStoreCheckbox, kAnchor_Below, &mAutoStoreOnSwitch);
mSnapshotLabelEntry = new TextEntry(this, "snapshot label", -1, -1, 12, &mSnapshotLabel);
{
mModuleCable = new PatchCableSource(this, kConnectionType_Special);
ofColor color = IDrawableModule::GetColor(kModuleCategory_Other);
color.a *= .3f;
mModuleCable->SetColor(color);
mModuleCable->SetManualPosition(10, 10);
mModuleCable->SetDefaultPatchBehavior(kDefaultPatchBehavior_Add);
//mModuleCable->SetPatchCableDrawMode(kPatchCableDrawMode_HoverOnly);
AddPatchCableSource(mModuleCable);
}
{
mUIControlCable = new PatchCableSource(this, kConnectionType_UIControl);
ofColor color = IDrawableModule::GetColor(kModuleCategory_Modulator);
color.a *= .3f;
mUIControlCable->SetColor(color);
mUIControlCable->SetManualPosition(25, 10);
mUIControlCable->SetDefaultPatchBehavior(kDefaultPatchBehavior_Add);
//mUIControlCable->SetPatchCableDrawMode(kPatchCableDrawMode_HoverOnly);
AddPatchCableSource(mUIControlCable);
}
for (int i = 0; i < 32; ++i)
mCurrentSnapshotSelector->AddLabel(ofToString(i).c_str(), i);
}
void Snapshots::Init()
{
IDrawableModule::Init();
int defaultSnapshot = mModuleSaveData.GetInt("defaultsnapshot");
if (defaultSnapshot != -1)
SetSnapshot(defaultSnapshot, gTime);
TheTransport->AddAudioPoller(this);
}
void Snapshots::Poll()
{
if (mQueuedSnapshotIndex != -1)
{
SetSnapshot(mQueuedSnapshotIndex, NextBufferTime(false));
mQueuedSnapshotIndex = -1;
}
if (mDrawSetSnapshotCountdown > 0)
{
--mDrawSetSnapshotCountdown;
if (mDrawSetSnapshotCountdown == 0)
sSnapshotHighlightControls.clear();
}
if (!mBlending && !mBlendRamps.empty())
{
mBlendRamps.clear();
}
}
void Snapshots::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mGrid->Draw();
mBlendTimeSlider->Draw();
mCurrentSnapshotSelector->Draw();
mRandomizeButton->Draw();
mAddButton->Draw();
mSnapshotLabelEntry->SetPosition(3, mGrid->GetRect(K(local)).getMaxY() + 3);
mSnapshotLabelEntry->Draw();
mClearButton->Draw();
mStoreCheckbox->Draw();
mDeleteCheckbox->Draw();
mAutoStoreOnSwitchCheckbox->Draw();
int hover = mGrid->CurrentHover();
bool storeMode = (GetKeyModifiers() == kModifier_Shift) || mStoreMode;
bool deleteMode = (GetKeyModifiers() == kModifier_Alt) || mDeleteMode;
if (storeMode || deleteMode)
{
if (hover >= 0 && hover < mGrid->GetCols() * mGrid->GetRows())
{
ofVec2f pos = mGrid->GetCellPosition(hover % mGrid->GetCols(), hover / mGrid->GetCols()) + mGrid->GetPosition(true);
float xsize = float(mGrid->GetWidth()) / mGrid->GetCols();
float ysize = float(mGrid->GetHeight()) / mGrid->GetRows();
ofPushStyle();
ofSetColor(0, 0, 0);
if (storeMode)
{
ofFill();
ofRect(pos.x + xsize / 2 - 1, pos.y + 3, 2, ysize - 6, 0);
ofRect(pos.x + 3, pos.y + ysize / 2 - 1, xsize - 6, 2, 0);
}
else if (deleteMode && !mSnapshotCollection[hover].mSnapshots.empty())
{
ofLine(pos.x + 3, pos.y + 3, pos.x + xsize - 3, pos.y + ysize - 3);
ofLine(pos.x + xsize - 3, pos.y + 3, pos.x + 3, pos.y + ysize - 3);
}
ofPopStyle();
}
}
else
{
if (mCurrentSnapshot < mGrid->GetCols() * mGrid->GetRows())
{
ofVec2f pos = mGrid->GetCellPosition(mCurrentSnapshot % mGrid->GetCols(), mCurrentSnapshot / mGrid->GetCols()) + mGrid->GetPosition(true);
float xsize = float(mGrid->GetWidth()) / mGrid->GetCols();
float ysize = float(mGrid->GetHeight()) / mGrid->GetRows();
ofPushStyle();
ofSetColor(255, 255, 255);
ofSetLineWidth(2);
ofNoFill();
ofRect(pos.x, pos.y, xsize, ysize);
ofPopStyle();
}
}
}
void Snapshots::DrawModuleUnclipped()
{
int hover = mGrid->CurrentHover();
if (hover >= 0 && !mSnapshotCollection.empty())
{
assert(hover >= 0 && hover < mSnapshotCollection.size());
std::string tooltip = mSnapshotCollection[hover].mLabel;
ofVec2f pos = mGrid->GetCellPosition(hover % mGrid->GetCols(), hover / mGrid->GetCols()) + mGrid->GetPosition(true);
pos.x += (mGrid->GetWidth() / mGrid->GetCols()) + 3;
pos.y += (mGrid->GetHeight() / mGrid->GetRows()) / 2;
float width = GetStringWidth(tooltip);
ofFill();
ofSetColor(50, 50, 50);
ofRect(pos.x, pos.y, width + 10, 15);
ofNoFill();
ofSetColor(255, 255, 255);
ofRect(pos.x, pos.y, width + 10, 15);
ofSetColor(255, 255, 255);
DrawTextNormal(tooltip, pos.x + 5, pos.y + 12);
}
}
bool Snapshots::HasSnapshot(int index) const
{
return !mSnapshotCollection[index].mSnapshots.empty();
}
void Snapshots::UpdateGridValues()
{
mGrid->Clear();
assert(mSnapshotCollection.size() >= size_t(mGrid->GetRows()) * mGrid->GetCols());
for (int i = 0; i < mGrid->GetRows() * mGrid->GetCols(); ++i)
{
float val = 0;
if (mSnapshotCollection[i].mSnapshots.empty() == false)
val = .5f;
mGrid->SetVal(i % mGrid->GetCols(), i / mGrid->GetCols(), val);
}
}
bool Snapshots::IsTargetingModule(IDrawableModule* module) const
{
return VectorContains(module, mSnapshotModules);
}
void Snapshots::AddSnapshotTarget(IDrawableModule* target)
{
if (!IsTargetingModule(target))
{
mSnapshotModules.push_back(target);
mModuleCable->AddPatchCable(target);
}
}
void Snapshots::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
if (right)
return;
if (mGrid->TestClick(x, y, right, true))
{
float gridX, gridY;
mGrid->GetPosition(gridX, gridY, true);
GridCell cell = mGrid->GetGridCellAt(x - gridX, y - gridY);
int idx = cell.mCol + cell.mRow * mGrid->GetCols();
if (GetKeyModifiers() == kModifier_Shift || mStoreMode)
StoreSnapshot(idx, false);
else if (GetKeyModifiers() == kModifier_Alt || mDeleteMode)
DeleteSnapshot(idx);
else
SetSnapshot(idx, NextBufferTime(false));
UpdateGridValues();
}
}
bool Snapshots::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
mGrid->NotifyMouseMoved(x, y);
return false;
}
void Snapshots::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (velocity > 0 && pitch < (int)mSnapshotCollection.size())
{
if (mStoreMode)
StoreSnapshot(pitch, false);
else if (mDeleteMode)
DeleteSnapshot(pitch);
else
SetSnapshot(pitch, time);
UpdateGridValues();
}
}
void Snapshots::SetSnapshot(int idx, double time)
{
if (!mAllowSetOnAudioThread && IsAudioThread())
{
mQueuedSnapshotIndex = idx;
return;
}
if (idx < 0 || idx >= (int)mSnapshotCollection.size())
return;
if (mAutoStoreOnSwitch && idx != mCurrentSnapshot)
StoreSnapshot(mCurrentSnapshot, false);
mCurrentSnapshot = idx;
if (mBlendTime > 0)
{
mRampMutex.lock();
mBlending = true;
mBlendProgress = 0;
mBlendRamps.clear();
}
sSnapshotHighlightControls.clear();
const SnapshotCollection& coll = mSnapshotCollection[idx];
for (std::list<Snapshot>::const_iterator i = coll.mSnapshots.begin();
i != coll.mSnapshots.end(); ++i)
{
auto context = IClickable::sPathLoadContext;
IClickable::sPathLoadContext = GetParent() ? GetParent()->Path() + "~" : "";
IUIControl* control = TheSynth->FindUIControl(i->mControlPath);
IClickable::sPathLoadContext = context;
if (control)
{
if (mBlendTime == 0 ||
i->mHasLFO ||
!i->mGridContents.empty() ||
!i->mString.empty())
{
control->SetValueDirect(i->mValue, time);
FloatSlider* slider = dynamic_cast<FloatSlider*>(control);
if (slider)
{
if (i->mHasLFO)
slider->AcquireLFO()->Load(i->mLFOSettings);
else
slider->DisableLFO();
}
UIGrid* grid = dynamic_cast<UIGrid*>(control);
if (grid)
{
for (int col = 0; col < i->mGridCols; ++col)
{
for (int row = 0; row < i->mGridRows; ++row)
{
grid->SetVal(col, row, i->mGridContents[size_t(col) + size_t(row) * i->mGridCols]);
}
}
}
TextEntry* textEntry = dynamic_cast<TextEntry*>(control);
if (textEntry && textEntry->GetTextEntryType() == kTextEntry_Text)
textEntry->SetText(i->mString);
if (control->ShouldSerializeForSnapshot() && !i->mString.empty())
{
juce::MemoryBlock outputStream;
outputStream.fromBase64Encoding(i->mString);
FileStreamIn in(outputStream);
control->LoadState(in, true);
}
}
else
{
ControlRamp ramp;
ramp.mUIControl = control;
ramp.mRamp.Start(0, control->GetValue(), i->mValue, mBlendTime);
mBlendRamps.push_back(ramp);
}
sSnapshotHighlightControls.push_back(control);
}
}
if (mBlendTime > 0)
{
mRampMutex.unlock();
}
mDrawSetSnapshotCountdown = 30;
mSnapshotLabel = coll.mLabel;
}
void Snapshots::RandomizeTargets()
{
for (int i = 0; i < mSnapshotControls.size(); ++i)
RandomizeControl(mSnapshotControls[i]);
for (int i = 0; i < mSnapshotModules.size(); ++i)
{
for (auto* control : mSnapshotModules[i]->GetUIControls())
RandomizeControl(control);
}
}
void Snapshots::RandomizeControl(IUIControl* control)
{
if (strcmp(control->Name(), "enabled") == 0) //don't randomize enabled/disable checkbox, too annoying
return;
if (dynamic_cast<ClickButton*>(control) != nullptr)
return;
control->SetFromMidiCC(ofRandom(1), NextBufferTime(false), true);
}
void Snapshots::OnTransportAdvanced(float amount)
{
if (mBlending)
{
mRampMutex.lock();
mBlendProgress += amount * TheTransport->MsPerBar();
for (auto& ramp : mBlendRamps)
{
ramp.mUIControl->SetValueDirect(ramp.mRamp.Value(mBlendProgress), gTime);
}
if (mBlendProgress >= mBlendTime)
mBlending = false;
mRampMutex.unlock();
}
}
void Snapshots::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
if (TheSynth->IsLoadingState())
return;
auto numModules = mSnapshotModules.size();
auto numControls = mSnapshotControls.size();
mSnapshotModules.clear();
for (auto cable : mModuleCable->GetPatchCables())
mSnapshotModules.push_back(static_cast<IDrawableModule*>(cable->GetTarget()));
mSnapshotControls.clear();
for (auto cable : mUIControlCable->GetPatchCables())
mSnapshotControls.push_back(static_cast<IUIControl*>(cable->GetTarget()));
if (mSnapshotModules.size() < numModules || mSnapshotControls.size() < numControls) //we removed something, clean up any snapshots that refer to it
{
for (auto& square : mSnapshotCollection)
{
std::vector<Snapshot> toRemove;
for (const auto& snapshot : square.mSnapshots)
{
if (!IsConnectedToPath(snapshot.mControlPath))
toRemove.push_back(snapshot);
}
for (auto remove : toRemove)
square.mSnapshots.remove(remove);
}
}
}
bool Snapshots::IsConnectedToPath(std::string path) const
{
auto context = IClickable::sPathLoadContext;
IClickable::sPathLoadContext = GetParent() ? GetParent()->Path() + "~" : "";
IUIControl* control = TheSynth->FindUIControl(path);
IClickable::sPathLoadContext = context;
if (control == nullptr)
return false;
if (VectorContains(control, mSnapshotControls))
return true;
if (VectorContains(control->GetModuleParent(), mSnapshotModules))
return true;
return false;
}
void Snapshots::StoreSnapshot(int idx, bool setAsCurrent)
{
assert(idx >= 0 && idx < mSnapshotCollection.size());
SnapshotCollection& coll = mSnapshotCollection[idx];
coll.mSnapshots.clear();
for (int i = 0; i < mSnapshotControls.size(); ++i)
{
coll.mSnapshots.push_back(Snapshot(mSnapshotControls[i], this));
}
for (int i = 0; i < mSnapshotModules.size(); ++i)
{
for (auto* control : mSnapshotModules[i]->GetUIControls())
{
if (dynamic_cast<ClickButton*>(control) == nullptr)
coll.mSnapshots.push_back(Snapshot(control, this));
}
for (auto* grid : mSnapshotModules[i]->GetUIGrids())
coll.mSnapshots.push_back(Snapshot(grid, this));
}
mSnapshotLabel = coll.mLabel;
if (setAsCurrent)
mCurrentSnapshot = idx;
UpdateGridValues();
}
void Snapshots::DeleteSnapshot(int idx)
{
assert(idx >= 0 && idx < mSnapshotCollection.size());
SnapshotCollection& coll = mSnapshotCollection[idx];
coll.mSnapshots.clear();
coll.mLabel = ofToString(idx);
mCurrentSnapshotSelector->SetLabel(coll.mLabel, idx);
}
bool Snapshots::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 - 1) * 8;
if (x == 0 && y == 0)
{
mStoreMode = midiValue > 0;
}
else if (x == 1 && y == 0)
{
mDeleteMode = midiValue > 0;
}
else if (midiValue > 0 && index >= 0 && index < (int)mSnapshotCollection.size())
{
if (mStoreMode)
StoreSnapshot(index, false);
else if (mDeleteMode)
DeleteSnapshot(index);
else
SetSnapshot(index, gTime);
UpdateGridValues();
}
return true;
}
}
return false;
}
void Snapshots::UpdatePush2Leds(Push2Control* push2)
{
for (int x = 0; x < 8; ++x)
{
for (int y = 0; y < 8; ++y)
{
int pushColor;
int index = x + (y - 1) * 8;
if (x == 0 && y == 0)
{
if (mStoreMode)
pushColor = 126;
else
pushColor = 86;
}
else if (x == 1 && y == 0)
{
if (mDeleteMode)
pushColor = 127;
else
pushColor = 114;
}
else if (index >= 0 && index < (int)mSnapshotCollection.size())
{
if (index == mCurrentSnapshot)
pushColor = 120;
else if (mSnapshotCollection[index].mSnapshots.empty() == false)
pushColor = 125;
else
pushColor = 20;
}
else
{
pushColor = 0;
}
push2->SetLed(kMidiMessage_Note, x + (7 - y) * 8 + 36, pushColor);
}
}
}
namespace
{
const float extraW = 10;
const float extraH = 58;
const float gridSquareDimension = 18;
const int maxGridSide = 20;
}
void Snapshots::ButtonClicked(ClickButton* button, double time)
{
if (button == mRandomizeButton)
RandomizeTargets();
if (button == mAddButton)
{
for (size_t i = 0; i < mSnapshotCollection.size(); ++i)
{
if (mSnapshotCollection[i].mSnapshots.empty())
{
StoreSnapshot(i, false);
mCurrentSnapshot = i;
UpdateGridValues();
break;
}
}
}
if (button == mClearButton)
{
for (size_t i = 0; i < mSnapshotCollection.size(); ++i)
{
if (!mSnapshotCollection[i].mSnapshots.empty())
DeleteSnapshot(i);
}
UpdateGridValues();
}
}
void Snapshots::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mCurrentSnapshotSelector)
{
int newIdx = mCurrentSnapshot;
mCurrentSnapshot = oldVal;
if (mStoreMode)
StoreSnapshot(newIdx, false);
else if (mDeleteMode)
DeleteSnapshot(newIdx);
else
SetSnapshot(newIdx, time);
UpdateGridValues();
}
}
void Snapshots::TextEntryComplete(TextEntry* entry)
{
if (entry == mSnapshotLabelEntry)
{
mSnapshotCollection[mCurrentSnapshot].mLabel = mSnapshotLabel;
mCurrentSnapshotSelector->SetLabel(mSnapshotLabel, mCurrentSnapshot);
}
}
void Snapshots::GetModuleDimensions(float& width, float& height)
{
width = mGrid->GetWidth() + extraW;
height = mGrid->GetHeight() + extraH;
}
void Snapshots::Resize(float w, float h)
{
SetGridSize(MAX(w - extraW, 120), MAX(h - extraH, gridSquareDimension));
}
void Snapshots::SetGridSize(float w, float h)
{
mGrid->SetDimensions(w, h);
int cols = MIN(w / gridSquareDimension, maxGridSide);
int rows = MIN(h / gridSquareDimension, maxGridSide);
mGrid->SetGrid(cols, rows);
int oldSize = (int)mSnapshotCollection.size();
if (oldSize < size_t(cols) * rows)
{
mSnapshotCollection.resize(size_t(cols) * rows);
for (int i = oldSize; i < (int)mSnapshotCollection.size(); ++i)
mSnapshotCollection[i].mLabel = ofToString(i);
}
UpdateGridValues();
}
void Snapshots::SaveLayout(ofxJSONElement& moduleInfo)
{
moduleInfo["gridwidth"] = mGrid->GetWidth();
moduleInfo["gridheight"] = mGrid->GetHeight();
}
void Snapshots::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadInt("defaultsnapshot", moduleInfo, -1, -1, 100, true);
mModuleSaveData.LoadFloat("gridwidth", moduleInfo, 120, 120, 1000);
mModuleSaveData.LoadFloat("gridheight", moduleInfo, 50, 15, 1000);
mModuleSaveData.LoadBool("allow_set_on_audio_thread", moduleInfo, true);
mModuleSaveData.LoadBool("auto_store_on_switch", moduleInfo, false);
SetUpFromSaveData();
}
void Snapshots::SetUpFromSaveData()
{
SetGridSize(mModuleSaveData.GetFloat("gridwidth"), mModuleSaveData.GetFloat("gridheight"));
mAllowSetOnAudioThread = mModuleSaveData.GetBool("allow_set_on_audio_thread");
}
void Snapshots::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out << (int)mSnapshotCollection.size();
for (auto& coll : mSnapshotCollection)
{
out << (int)coll.mSnapshots.size();
for (auto& snapshot : coll.mSnapshots)
{
out << snapshot.mControlPath;
out << snapshot.mValue;
out << snapshot.mHasLFO;
snapshot.mLFOSettings.SaveState(out);
out << snapshot.mGridCols;
out << snapshot.mGridRows;
assert(snapshot.mGridContents.size() == size_t(snapshot.mGridCols) * snapshot.mGridRows);
for (size_t i = 0; i < snapshot.mGridContents.size(); ++i)
out << snapshot.mGridContents[i];
out << snapshot.mString;
}
out << coll.mLabel;
}
out << (int)mSnapshotModules.size();
for (auto module : mSnapshotModules)
{
if (module != nullptr && !module->IsDeleted())
out << module->Path();
else
out << std::string("");
}
out << (int)mSnapshotControls.size();
for (auto control : mSnapshotControls)
{
if (control != nullptr && !control->GetModuleParent()->IsDeleted())
out << control->Path();
else
out << std::string("");
}
out << mCurrentSnapshot;
}
void Snapshots::LoadState(FileStreamIn& in, int rev)
{
mLoadRev = rev;
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
int collSize;
in >> collSize;
mSnapshotCollection.resize(collSize);
for (int i = 0; i < collSize; ++i)
{
int snapshotSize;
in >> snapshotSize;
mSnapshotCollection[i].mSnapshots.resize(snapshotSize);
for (auto& snapshotData : mSnapshotCollection[i].mSnapshots)
{
in >> snapshotData.mControlPath;
in >> snapshotData.mValue;
in >> snapshotData.mHasLFO;
snapshotData.mLFOSettings.LoadState(in);
in >> snapshotData.mGridCols;
in >> snapshotData.mGridRows;
if (rev < 3)
{
// Check if the loaded values are within an acceptable range.
// This is done because mGridCols and mGridRows could previously be saved with random values since they were not properly initialized.
if (snapshotData.mGridCols < 0 || snapshotData.mGridCols > 1000)
snapshotData.mGridCols = 0;
if (snapshotData.mGridRows < 0 || snapshotData.mGridRows > 1000)
snapshotData.mGridRows = 0;
}
snapshotData.mGridContents.resize(size_t(snapshotData.mGridCols) * snapshotData.mGridRows);
for (int k = 0; k < snapshotData.mGridCols * snapshotData.mGridRows; ++k)
in >> snapshotData.mGridContents[k];
in >> snapshotData.mString;
}
in >> mSnapshotCollection[i].mLabel;
if (rev < 2 && mSnapshotCollection[i].mLabel.empty())
mSnapshotCollection[i].mLabel = ofToString(i);
mCurrentSnapshotSelector->SetLabel(mSnapshotCollection[i].mLabel, i);
}
UpdateGridValues();
std::string path;
int size;
in >> size;
for (int i = 0; i < size; ++i)
{
in >> path;
if (path != "")
{
IDrawableModule* module = TheSynth->FindModule(path);
if (module)
{
mSnapshotModules.push_back(module);
mModuleCable->AddPatchCable(module);
}
}
}
in >> size;
for (int i = 0; i < size; ++i)
{
in >> path;
if (path != "")
{
IUIControl* control = TheSynth->FindUIControl(path);
if (control)
{
mSnapshotControls.push_back(control);
mUIControlCable->AddPatchCable(control);
}
}
}
if (rev >= 2)
in >> mCurrentSnapshot;
}
void Snapshots::UpdateOldControlName(std::string& oldName)
{
IDrawableModule::UpdateOldControlName(oldName);
if (oldName == "blend ms")
oldName = "blend";
if (oldName == "preset")
oldName = "snapshot";
}
bool Snapshots::LoadOldControl(FileStreamIn& in, std::string& oldName)
{
if (mLoadRev < 2)
{
if (oldName == "preset")
{
//load from int slider
int intSliderRev;
in >> intSliderRev;
in >> mCurrentSnapshot;
int dummy;
if (intSliderRev >= 1)
{
in >> dummy;
in >> dummy;
}
return true;
}
}
return false;
}
std::vector<IUIControl*> Snapshots::ControlsToNotSetDuringLoadState() const
{
std::vector<IUIControl*> ignore;
ignore.push_back(mCurrentSnapshotSelector);
return ignore;
}
Snapshots::Snapshot::Snapshot(IUIControl* control, Snapshots* snapshots)
{
auto context = IClickable::sPathSaveContext;
IClickable::sPathSaveContext = snapshots->GetParent() ? snapshots->GetParent()->Path() + "~" : "";
mControlPath = control->Path();
IClickable::sPathSaveContext = context;
mValue = control->GetValue();
FloatSlider* slider = dynamic_cast<FloatSlider*>(control);
if (slider)
{
FloatSliderLFOControl* lfo = slider->GetLFO();
if (lfo && lfo->Active())
{
mHasLFO = true;
mLFOSettings = lfo->GetSettings();
}
else
{
mHasLFO = false;
}
}
else
{
mHasLFO = false;
}
UIGrid* grid = dynamic_cast<UIGrid*>(control);
if (grid)
{
mGridCols = grid->GetCols();
mGridRows = grid->GetRows();
mGridContents.resize(size_t(grid->GetCols()) * grid->GetRows());
for (int col = 0; col < grid->GetCols(); ++col)
{
for (int row = 0; row < grid->GetRows(); ++row)
{
mGridContents[size_t(col) + size_t(row) * grid->GetCols()] = grid->GetVal(col, row);
}
}
}
TextEntry* textEntry = dynamic_cast<TextEntry*>(control);
if (textEntry && textEntry->GetTextEntryType() == kTextEntry_Text)
mString = textEntry->GetText();
if (control->ShouldSerializeForSnapshot())
{
juce::MemoryBlock tempBlock;
{
FileStreamOut out(tempBlock);
control->SaveState(out);
}
mString = tempBlock.toBase64Encoding().toStdString();
}
}
``` | /content/code_sandbox/Source/Snapshots.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 6,981 |
```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
**/
//
// NoteToFreq.h
// Bespoke
//
// Created by Ryan Challinor on 12/17/15.
//
//
#pragma once
#include "IDrawableModule.h"
#include "INoteReceiver.h"
#include "IModulator.h"
class PatchCableSource;
class NoteToFreq : public IDrawableModule, public INoteReceiver, public IModulator
{
public:
NoteToFreq();
virtual ~NoteToFreq();
static IDrawableModule* Create() { return new NoteToFreq(); }
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 {}
//IModulator
float Value(int samplesIn = 0) override;
bool Active() const override { return mEnabled; }
bool CanAdjustRange() const override { return false; }
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) 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;
}
float mPitch{ 0 };
ModulationChain* mPitchBend{ nullptr };
};
``` | /content/code_sandbox/Source/NoteToFreq.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 515 |
```objective-c
#pragma once
#undef LoadString //undo some junk from a windows define
#include <limits>
#include "SynthGlobals.h"
#include "IDrawableModule.h"
#include "TextEntry.h"
#include "RollingBuffer.h"
#include "NamedMutex.h"
#include "ofxJSONElement.h"
#include "ModuleFactory.h"
#include "LocationZoomer.h"
#include "EffectFactory.h"
#include "ModuleContainer.h"
#include "Minimap.h"
#include <thread>
#ifdef BESPOKE_LINUX
#include <climits>
#endif
namespace juce
{
class AudioDeviceManager;
class AudioFormatManager;
class Component;
class OpenGLContext;
class String;
class MouseInputSource;
class AudioPluginFormatManager;
class KnownPluginList;
}
class IAudioSource;
class IAudioReceiver;
class INoteReceiver;
class MidiDevice;
class Sample;
class PatchCable;
class MidiController;
class NVGcontext;
class QuickSpawnMenu;
class ADSRDisplay;
class UserPrefsEditor;
class Minimap;
class ScriptWarningPopup;
class NoteOutputQueue;
enum LogEventType
{
kLogEventType_Verbose,
kLogEventType_Warning,
kLogEventType_Error
};
class ConsoleListener : public IDrawableModule, public ITextEntryListener
{
public:
void GetModuleDimensions(float& width, float& height) override
{
width = 1;
height = 1;
}
void TextEntryActivated(TextEntry* entry) override;
void TextEntryComplete(TextEntry* entry) override;
bool IsEnabled() const override { return false; }
private:
void DrawModule() override {}
};
class ModularSynth
{
public:
ModularSynth();
virtual ~ModularSynth();
void Setup(juce::AudioDeviceManager* globalAudioDeviceManager, juce::AudioFormatManager* globalAudioFormatManager, juce::Component* mainComponent, juce::OpenGLContext* openGLContext);
void LoadResources(void* nanoVG, void* fontBoundsNanoVG);
void InitIOBuffers(int inputChannelCount, int outputChannelCount);
void Poll();
void Draw(void* vg);
void PostRender();
void Exit();
void Focus();
void KeyPressed(int key, bool isRepeat);
void KeyReleased(int key);
void MouseMoved(int x, int y);
void MouseDragged(int x, int y, int button, const juce::MouseInputSource& source);
void MousePressed(int x, int y, int button, const juce::MouseInputSource& source);
void MouseReleased(int x, int y, int button, const juce::MouseInputSource& source);
void MouseScrolled(float xScroll, float yScroll, bool isSmoothScroll, bool isInvertedScroll, bool canZoomCanvas);
void MouseMagnify(int x, int y, float scaleFactor, const juce::MouseInputSource& source);
void FilesDropped(std::vector<std::string> files, int x, int y);
void AddExtraPoller(IPollable* poller);
void RemoveExtraPoller(IPollable* poller);
void AudioOut(float* const* output, int bufferSize, int nChannels);
void AudioIn(const float* const* input, int bufferSize, int nChannels);
void OnConsoleInput(std::string command = "");
void ClearConsoleInput();
bool IsReady();
bool IsAudioPaused() const { return mAudioPaused; }
void SetAudioPaused(bool paused) { mAudioPaused = paused; }
void AddMidiDevice(MidiDevice* device);
void ArrangeAudioSourceDependencies();
IDrawableModule* SpawnModuleOnTheFly(ModuleFactory::Spawnable spawnable, float x, float y, bool addToContainer = true, std::string name = "");
void SetMoveModule(IDrawableModule* module, float offsetX, float offsetY, bool canStickToCursor);
int GetNumInputChannels() const { return (int)mInputBuffers.size(); }
int GetNumOutputChannels() const { return (int)mOutputBuffers.size(); }
float* GetInputBuffer(int channel);
float* GetOutputBuffer(int channel);
IDrawableModule* FindModule(std::string name, bool fail = false);
IAudioReceiver* FindAudioReceiver(std::string name, bool fail = false);
INoteReceiver* FindNoteReceiver(std::string name, bool fail = false);
IUIControl* FindUIControl(std::string path);
MidiController* FindMidiController(std::string name, bool fail = false);
void MoveToFront(IDrawableModule* module);
bool InMidiMapMode();
void GetAllModules(std::vector<IDrawableModule*>& out) { mModuleContainer.GetAllModules(out); }
void PushModalFocusItem(IDrawableModule* item);
void PopModalFocusItem();
IDrawableModule* GetTopModalFocusItem() const;
std::vector<IDrawableModule*> GetModalFocusItemStack() const { return mModalFocusItemStack; }
bool IsModalFocusItem(IDrawableModule* item) const;
void LogEvent(std::string event, LogEventType type);
void SetNextDrawTooltip(std::string tooltip) { mNextDrawTooltip = tooltip; }
bool LoadLayoutFromFile(std::string jsonFile, bool makeDefaultLayout = true);
bool LoadLayoutFromString(std::string jsonString);
void LoadLayout(ofxJSONElement json);
std::string GetLoadedLayout() const { return mLoadedLayoutPath; }
void ReloadInitialLayout() { mWantReloadInitialLayout = true; }
bool HasFatalError() { return mFatalError != ""; }
void AddLissajousDrawer(IDrawableModule* module) { mLissajousDrawers.push_back(module); }
bool IsLissajousDrawer(IDrawableModule* module) { return VectorContains(module, mLissajousDrawers); }
void GrabSample(ChannelBuffer* data, std::string name, bool window = false, int numBars = -1);
void GrabSample(std::string filePath);
Sample* GetHeldSample() const { return mHeldSample; }
void ClearHeldSample();
float GetRawMouseX() { return mMousePos.x; }
float GetRawMouseY() { return mMousePos.y; }
float GetMouseX(ModuleContainer* context, float rawX = FLT_MAX);
float GetMouseY(ModuleContainer* context, float rawY = FLT_MAX);
void SetMousePosition(ModuleContainer* context, float x, float y);
bool IsMouseButtonHeld(int button) const;
ofVec2f& GetDrawOffset() { return mModuleContainer.GetDrawOffsetRef(); }
void SetDrawOffset(ofVec2f offset) { mModuleContainer.SetDrawOffset(offset); }
const ofRectangle& GetDrawRect() const { return mDrawRect; }
void SetPixelRatio(double ratio) { mPixelRatio = ratio; }
double GetPixelRatio() const { return mPixelRatio; }
long GetFrameCount() { return mFrameCount; }
void SetUIScale(float scale) { mUILayerModuleContainer.SetDrawScale(scale); }
float GetUIScale() { return mUILayerModuleContainer.GetDrawScale(); }
ModuleContainer* GetRootContainer() { return &mModuleContainer; }
ModuleContainer* GetUIContainer() { return &mUILayerModuleContainer; }
bool ShouldShowGridSnap() const;
bool MouseMovedSignificantlySincePressed() const { return mMouseMovedSignificantlySincePressed; }
void ZoomView(float zoomAmount, bool fromMouse);
void SetZoomLevel(float zoomLevel);
void PanView(float x, float y);
void PanTo(float x, float y);
void SetRawSpaceMouseTwist(float twist, bool isUsing)
{
mSpaceMouseInfo.mTwist = twist;
mSpaceMouseInfo.mUsingTwist = isUsing;
}
void SetRawSpaceMouseZoom(float zoom, bool isUsing)
{
mSpaceMouseInfo.mZoom = zoom;
mSpaceMouseInfo.mUsingZoom = isUsing;
}
void SetRawSpaceMousePan(float x, float y, bool isUsing)
{
mSpaceMouseInfo.mPan.set(x, y);
mSpaceMouseInfo.mUsingPan = isUsing;
}
void SetResizeModule(IDrawableModule* module) { mResizeModule = module; }
void SetGroupSelectContext(ModuleContainer* context) { mGroupSelectContext = context; }
bool IsGroupSelecting() const { return mGroupSelectContext != nullptr; }
IDrawableModule* GetMoveModule() { return mMoveModule; }
ModuleFactory* GetModuleFactory() { return &mModuleFactory; }
juce::AudioDeviceManager& GetAudioDeviceManager() { return *mGlobalAudioDeviceManager; }
juce::AudioFormatManager& GetAudioFormatManager() { return *mGlobalAudioFormatManager; }
juce::AudioPluginFormatManager& GetAudioPluginFormatManager() { return *mAudioPluginFormatManager.get(); }
juce::KnownPluginList& GetKnownPluginList() { return *mKnownPluginList.get(); }
juce::Component* GetMainComponent() { return mMainComponent; }
juce::OpenGLContext* GetOpenGLContext() { return mOpenGLContext; }
IDrawableModule* GetLastClickedModule() const;
EffectFactory* GetEffectFactory() { return &mEffectFactory; }
const std::vector<IDrawableModule*>& GetGroupSelectedModules() const { return mGroupSelectedModules; }
bool ShouldAccentuateActiveModules() const;
bool ShouldDimModule(IDrawableModule* module);
LocationZoomer* GetLocationZoomer() { return &mZoomer; }
IDrawableModule* GetModuleAtCursor(int offsetX = 0, int offsetY = 0);
void RegisterPatchCable(PatchCable* cable);
void UnregisterPatchCable(PatchCable* cable);
template <class T>
std::vector<std::string> GetModuleNames() { return mModuleContainer.GetModuleNames<T>(); }
void LockRender(bool lock)
{
if (lock)
{
mRenderLock.lock();
}
else
{
mRenderLock.unlock();
}
}
void UpdateFrameRate(float fps) { mFrameRate = fps; }
float GetFrameRate() const { return mFrameRate; }
std::recursive_mutex& GetRenderLock() { return mRenderLock; }
NamedMutex* GetAudioMutex() { return &mAudioThreadMutex; }
static std::thread::id GetAudioThreadID() { return sAudioThreadId; }
NoteOutputQueue* GetNoteOutputQueue() { return mNoteOutputQueue; }
IDrawableModule* CreateModule(const ofxJSONElement& moduleInfo);
void SetUpModule(IDrawableModule* module, const ofxJSONElement& moduleInfo);
void OnModuleAdded(IDrawableModule* module);
void OnModuleDeleted(IDrawableModule* module);
void AddDynamicModule(IDrawableModule* module);
void ScheduleEnvelopeEditorSpawn(ADSRDisplay* adsrDisplay);
bool IsLoadingState() const { return mIsLoadingState; }
bool IsLoadingModule() const { return mIsLoadingModule; }
bool IsDuplicatingModule() const { return mIsDuplicatingModule; }
void SetIsLoadingState(bool loading) { mIsLoadingState = loading; }
static std::string GetUserPrefsPath();
static void CrashHandler(void*);
static void DumpStats(bool isCrash, void* crashContext);
void SaveLayout(std::string jsonFile = "", bool makeDefaultLayout = true);
ofxJSONElement GetLayout();
void SaveLayoutAsPopup();
void SaveOutput();
void SaveState(std::string file, bool autosave);
void LoadState(std::string file);
void SetStartupSaveStateFile(std::string bskPath);
void SaveCurrentState();
void SaveStatePopup();
void LoadStatePopup();
void ToggleQuickSpawn();
QuickSpawnMenu* GetQuickSpawn() { return mQuickSpawn; }
std::string GetLastSavePath() { return mCurrentSaveStatePath; }
UserPrefsEditor* GetUserPrefsEditor() { return mUserPrefsEditor; }
juce::Component* GetFileChooserParent() const;
const juce::String& GetTextFromClipboard() const;
void CopyTextToClipboard(const juce::String& text);
void SetFatalError(std::string error);
static bool sShouldAutosave;
static float sBackgroundLissajousR;
static float sBackgroundLissajousG;
static float sBackgroundLissajousB;
static float sBackgroundR;
static float sBackgroundG;
static float sBackgroundB;
static float sCableAlpha;
static int sLoadingFileSaveStateRev;
static int sLastLoadedFileSaveStateRev;
static constexpr int kSaveStateRev = 426;
private:
void ResetLayout();
void ReconnectMidiDevices();
void DrawConsole();
void CheckClick(IDrawableModule* clickedModule, float x, float y, bool rightButton);
void UpdateUserPrefsLayout();
void LoadStatePopupImp();
IDrawableModule* DuplicateModule(IDrawableModule* module);
void DeleteAllModules();
void TriggerClapboard();
void DoAutosave();
void FindCircularDependencies();
bool FindCircularDependencySearch(std::list<IAudioSource*> chain, IAudioSource* searchFrom);
void ClearCircularDependencyMarkers();
bool IsCurrentSaveStateATemplate() const;
void ReadClipboardTextFromSystem();
int mIOBufferSize{ 0 };
std::vector<IAudioSource*> mSources;
std::vector<IDrawableModule*> mLissajousDrawers;
std::vector<IDrawableModule*> mDeletedModules;
bool mHasCircularDependency{ false };
std::vector<IDrawableModule*> mModalFocusItemStack;
IDrawableModule* mMoveModule{ nullptr };
int mMoveModuleOffsetX{ 0 };
int mMoveModuleOffsetY{ 0 };
bool mMoveModuleCanStickToCursor{ false }; //if the most current mMoveModule can stick to the cursor if you release the mouse button before moving it
ofVec2f mLastMoveMouseScreenPos;
ofVec2f mLastMouseDragPos;
bool mIsMousePanning{ false };
std::array<bool, 5> mIsMouseButtonHeld{ false };
struct SpaceMouseInfo
{
float mTwist{ 0 };
float mZoom{ 0 };
ofVec2f mPan{ 0, 0 };
bool mUsingTwist{ false };
bool mUsingZoom{ false };
bool mUsingPan{ false };
};
SpaceMouseInfo mSpaceMouseInfo;
char mConsoleText[MAX_TEXTENTRY_LENGTH]{ 0 };
TextEntry* mConsoleEntry{ nullptr };
ConsoleListener* mConsoleListener{ nullptr };
std::vector<MidiDevice*> mMidiDevices;
LocationZoomer mZoomer;
QuickSpawnMenu* mQuickSpawn{ nullptr };
std::unique_ptr<Minimap> mMinimap{ nullptr };
UserPrefsEditor* mUserPrefsEditor{ nullptr };
RollingBuffer* mGlobalRecordBuffer{ nullptr };
long long mRecordingLength{ 0 };
struct LogEventItem
{
LogEventItem(double _time, std::string _text, LogEventType _type)
: time(_time)
, text(_text)
, type(_type)
{}
double time{ 0 };
std::string text;
LogEventType type{ LogEventType::kLogEventType_Verbose };
};
std::list<LogEventItem> mEvents;
std::list<std::string> mErrors;
NamedMutex mAudioThreadMutex;
static std::thread::id sAudioThreadId;
NoteOutputQueue* mNoteOutputQueue{ nullptr };
bool mAudioPaused{ false };
bool mIsLoadingState{ false };
bool mArrangeDependenciesWhenLoadCompletes{ false };
ModuleFactory mModuleFactory;
EffectFactory mEffectFactory;
int mClickStartX{ std::numeric_limits<int>::max() }; //to detect click and release in place
int mClickStartY{ std::numeric_limits<int>::max() };
bool mMouseMovedSignificantlySincePressed{ true };
bool mLastClickWasEmptySpace{ false };
bool mIsShiftPressed{ false };
double mLastShiftPressTime{ -9999 };
std::string mLoadedLayoutPath;
bool mWantReloadInitialLayout{ false };
std::string mCurrentSaveStatePath;
std::string mStartupSaveStateFile;
Sample* mHeldSample{ nullptr };
IDrawableModule* mLastClickedModule{ nullptr };
bool mInitialized{ false };
ofRectangle mDrawRect;
std::vector<IDrawableModule*> mGroupSelectedModules;
ModuleContainer* mGroupSelectContext{ nullptr };
bool mHasDuplicatedDuringDrag{ false };
bool mHasAutopatchedToTargetDuringDrag{ false };
IDrawableModule* mResizeModule{ nullptr };
bool mShowLoadStatePopup{ false };
std::vector<PatchCable*> mPatchCables;
ofMutex mKeyInputMutex;
std::vector<std::pair<int, bool> > mQueuedKeyInput;
ofVec2f mMousePos;
std::string mNextDrawTooltip;
bool mHideTooltipsUntilMouseMove{ false };
juce::AudioDeviceManager* mGlobalAudioDeviceManager{ nullptr };
juce::AudioFormatManager* mGlobalAudioFormatManager{ nullptr };
juce::Component* mMainComponent{ nullptr };
juce::OpenGLContext* mOpenGLContext{ nullptr };
std::recursive_mutex mRenderLock;
float mFrameRate{ 0 };
long mFrameCount{ 0 };
ModuleContainer mModuleContainer;
ModuleContainer mUILayerModuleContainer;
ADSRDisplay* mScheduledEnvelopeEditorSpawnDisplay{ nullptr };
bool mIsLoadingModule{ false };
bool mIsDuplicatingModule{ false };
std::list<IPollable*> mExtraPollers;
std::string mFatalError;
double mLastClapboardTime{ -9999 };
double mPixelRatio{ 1 };
std::vector<float*> mInputBuffers;
std::vector<float*> mOutputBuffers;
std::unique_ptr<juce::AudioPluginFormatManager> mAudioPluginFormatManager;
std::unique_ptr<juce::KnownPluginList> mKnownPluginList;
};
extern ModularSynth* TheSynth;
``` | /content/code_sandbox/Source/ModularSynth.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 4,053 |
```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
**/
//
// PressureToModwheel.h
// Bespoke
//
// Created by Ryan Challinor on 1/4/16.
//
//
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "ModulationChain.h"
class PressureToModwheel : public NoteEffectBase, public IDrawableModule
{
public:
PressureToModwheel();
virtual ~PressureToModwheel();
static IDrawableModule* Create() { return new PressureToModwheel(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) 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 = 120;
height = 0;
}
};
``` | /content/code_sandbox/Source/PressureToModwheel.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 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
**/
//
// TriggerDetector.cpp
// modularSynth
//
// Created by Ryan Challinor on 3/22/14.
//
//
#include "TriggerDetector.h"
#include "SynthGlobals.h"
TriggerDetector::TriggerDetector()
: mHistory(gSampleRate)
{
}
void TriggerDetector::Process(float sample)
{
if (mSharpness > 0)
{
float filter = 1 - mSharpness * .001f;
mAvg = filter * mAvg + (1 - filter) * sample;
sample -= mAvg; //highpass
}
if (sample - mHistory.GetSample(100, 0) > mThreshold && sample > .1f && mWaitingForFall == false)
{
mTriggered = true;
mWaitingForFall = true;
}
if (sample < mHistory.GetSample(100, 0))
mWaitingForFall = false;
mHistory.Write(sample, 0);
}
float TriggerDetector::GetValue()
{
return mHistory.GetSample(1, 0);
}
bool TriggerDetector::CheckTriggered()
{
bool triggered = mTriggered;
mTriggered = false;
return triggered;
}
void TriggerDetector::Draw(int x, int y)
{
ofPushStyle();
ofSetLineWidth(1);
ofSetColor(0, 255, 0);
for (int i = 1; i < mHistory.Size() - 1; ++i)
{
ofRect(x - i / 50, y, 1, -mHistory.GetSample(i, 0) * 300);
}
ofPopStyle();
}
``` | /content/code_sandbox/Source/TriggerDetector.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 449 |
```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
**/
/*
==============================================================================
ValueStream.cpp
Created: 25 Oct 2020 7:09:05pm
Author: Ryan Challinor
==============================================================================
*/
#include "ValueStream.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
#include "SynthGlobals.h"
#include "UIControlMacros.h"
ValueStream::ValueStream()
{
}
void ValueStream::Init()
{
IDrawableModule::Init();
TheTransport->AddAudioPoller(this);
}
ValueStream::~ValueStream()
{
TheTransport->RemoveAudioPoller(this);
}
void ValueStream::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
FLOATSLIDER(mSpeedSlider, "speed", &mSpeed, .4f, 5);
ENDUIBLOCK0();
mControlCable = new PatchCableSource(this, kConnectionType_UIControl);
AddPatchCableSource(mControlCable);
}
void ValueStream::Poll()
{
}
void ValueStream::OnTransportAdvanced(float amount)
{
if (mUIControl && mEnabled)
{
for (int i = 0; i < gBufferSize; ++i)
{
if (mFloatSlider)
mFloatSlider->Compute(i);
mValues[mValueDisplayPointer] = mUIControl->GetValue();
mValueDisplayPointer = (mValueDisplayPointer + 1) % mValues.size();
}
}
}
void ValueStream::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mSpeedSlider->Draw();
if (mFloatSlider)
{
ofBeginShape();
for (int i = 0; i < mWidth; ++i)
{
float x = mWidth - i;
int samplesAgo = int(i / (mSpeed / 200)) + 1;
if (samplesAgo < mValues.size())
{
float y = ofMap(mValues[(mValueDisplayPointer - samplesAgo + mValues.size()) % mValues.size()], mFloatSlider->GetMin(), mFloatSlider->GetMax(), mHeight - 10, 10);
ofVertex(x, y);
}
}
ofEndShape();
}
}
void ValueStream::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
if (mControlCable->GetPatchCables().empty() == false)
mUIControl = dynamic_cast<IUIControl*>(mControlCable->GetPatchCables()[0]->GetTarget());
else
mUIControl = nullptr;
mFloatSlider = dynamic_cast<FloatSlider*>(mUIControl);
}
void ValueStream::GetModuleDimensions(float& width, float& height)
{
width = mWidth;
height = mHeight;
}
void ValueStream::Resize(float w, float h)
{
mWidth = MAX(w, 200);
mHeight = MAX(h, 120);
}
void ValueStream::SaveLayout(ofxJSONElement& moduleInfo)
{
moduleInfo["width"] = mWidth;
moduleInfo["height"] = mHeight;
}
void ValueStream::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadInt("width", moduleInfo, 200, 120, 1000);
mModuleSaveData.LoadInt("height", moduleInfo, 120, 15, 1000);
SetUpFromSaveData();
}
void ValueStream::SetUpFromSaveData()
{
mWidth = mModuleSaveData.GetInt("width");
mHeight = mModuleSaveData.GetInt("height");
}
void ValueStream::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
}
void ValueStream::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
}
``` | /content/code_sandbox/Source/ValueStream.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 977 |
```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
**/
//
// Profiler.cpp
// modularSynth
//
// Created by Ryan Challinor on 2/28/14.
//
//
#include "Profiler.h"
#include "SynthGlobals.h"
#if BESPOKE_WINDOWS
#include <intrin.h>
#else
#include <chrono>
#endif
Profiler::Cost Profiler::sCosts[];
bool Profiler::sEnableProfiler = false;
namespace
{
static inline uint64_t rdtscp(uint32_t& aux)
{
//@TODO(Noxy): Why is windows treated differently here? Doesn't std::chrono::high_resolution_clock::now work on windows?
#if BESPOKE_WINDOWS
unsigned __int64 i;
unsigned int ui;
i = __rdtscp(&ui);
//printf_s("%I64d ticks\n", i);
//printf_s("TSC_AUX was %x\n", ui);
return i;
#else
std::chrono::high_resolution_clock::time_point time_point = std::chrono::high_resolution_clock::now();
return time_point.time_since_epoch().count();
#endif
}
}
Profiler::Profiler(const char* name, uint32_t hash)
{
if (sEnableProfiler)
{
for (int i = 0; i < PROFILER_MAX_TRACK; ++i)
{
if (sCosts[i].mHash == hash)
{
mIndex = i;
break;
}
if (sCosts[i].mName[0] == 0)
{
mIndex = i;
sCosts[i].mName = name;
sCosts[i].mHash = hash;
break;
}
}
uint32_t aux;
mTimerStart = rdtscp(aux);
//struct timespec t;
//clock_gettime(CLOCK_MONOTONIC, &t);
//mTimerStart = t.tv_sec * 1000000000 + t.tv_nsec;
}
}
Profiler::~Profiler()
{
if (sEnableProfiler)
{
uint32_t aux;
sCosts[mIndex].mFrameCost += rdtscp(aux) - mTimerStart;
//struct timespec t;
//clock_gettime(CLOCK_MONOTONIC, &t);
//unsigned long long timerEnd = t.tv_sec * 1000000000 + t.tv_nsec;
//sCosts[mIndex].mFrameCost += timerEnd - mTimerStart;
}
}
//static
void Profiler::PrintCounters()
{
//bool printedBreak = false;
for (int i = 0; i < PROFILER_MAX_TRACK; ++i)
{
if (sCosts[i].mName[0] == 0)
break;
/*if (sCosts[i].mFrameCost > 500)
{
if (!printedBreak)
{
ofLog() << "******* PrintCounters():";
printedBreak = true;
}
ofLog() << sCosts[i].mName << " " << sCosts[i].mFrameCost << " us";
}*/
sCosts[i].EndFrame();
}
}
//static
void Profiler::Draw()
{
if (!sEnableProfiler)
return;
ofPushMatrix();
ofTranslate(30, 70);
ofPushStyle();
ofFill();
ofSetColor(0, 0, 0, 140);
//ofRect(-5,-15,600,sCosts.size()*15+10);
long entireFrameUs = GetSafeFrameLengthNanoseconds();
for (int i = 0; i < PROFILER_MAX_TRACK; ++i)
{
if (sCosts[i].mName[0] == 0)
break;
const Cost& cost = sCosts[i];
long maxCost = cost.MaxCost();
ofSetColor(255, 255, 255);
gFont.DrawString(std::string(sCosts[i].mName) + ": " + ofToString(maxCost / 1000), 13, 0, 0);
if (maxCost > entireFrameUs)
ofSetColor(255, 0, 0);
else
ofSetColor(0, 255, 0);
ofRect(250, -10, (float)maxCost / entireFrameUs * (ofGetWidth() - 300) * .1f, 10);
ofTranslate(0, 15);
}
ofPopStyle();
ofPopMatrix();
}
//static
long Profiler::GetSafeFrameLengthNanoseconds()
{
//using about 70% of the length of buffer size doing processing seems to be safe
//for avoiding starvation issues
return long((gBufferSize / float(gSampleRate)) * 1000000000 * .7f);
}
//static
void Profiler::ToggleProfiler()
{
sEnableProfiler = !sEnableProfiler;
for (int i = 0; i < PROFILER_MAX_TRACK; ++i)
sCosts[i].mName[0] = 0;
}
void Profiler::Cost::EndFrame()
{
mHistory[mHistoryIdx] = mFrameCost;
mFrameCost = 0;
++mHistoryIdx;
if (mHistoryIdx >= PROFILER_HISTORY_LENGTH)
mHistoryIdx = 0;
}
unsigned long long Profiler::Cost::MaxCost() const
{
unsigned long long maxCost = 0;
for (int i = 0; i < PROFILER_HISTORY_LENGTH; ++i)
maxCost = MAX(maxCost, mHistory[i]);
return maxCost;
}
``` | /content/code_sandbox/Source/Profiler.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,301 |
```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
**/
//
// DropdownList.h
// modularSynth
//
// Created by Ryan Challinor on 12/18/12.
//
//
#pragma once
#include "IUIControl.h"
#include "IDrawableModule.h"
#include "ClickButton.h"
struct DropdownListElement
{
std::string mLabel;
int mValue{ 0 };
};
class DropdownList;
class IDropdownListener
{
public:
virtual ~IDropdownListener() {}
virtual void DropdownClicked(DropdownList* list) {}
virtual void DropdownUpdated(DropdownList* list, int oldVal, double time) = 0;
};
class DropdownListModal : public IDrawableModule, public IButtonListener
{
public:
DropdownListModal(DropdownList* owner) { mOwner = owner; }
void CreateUIControls() override;
void SetUpModal();
void DrawModule() override;
void SetDimensions(int w, int h)
{
mWidth = w;
mHeight = h;
}
bool HasTitleBar() const override { return false; }
void GetDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
bool ShouldClipContents() override { return false; }
DropdownList* GetOwner() const { return mOwner; }
bool MouseMoved(float x, float y) override;
std::string GetHoveredLabel();
float GetMouseX() { return mMouseX; }
float GetMouseY() { return mMouseY; }
void SetShowPagingControls(bool show);
void SetIsScrolling(bool scrolling) { mIsScrolling = scrolling; }
void ButtonClicked(ClickButton* button, double time) override;
private:
void OnClicked(float x, float y, bool right) override;
int mWidth{ 1 };
int mHeight{ 1 };
int mColumnWidth{ 1 };
float mMouseX{ -1 };
float mMouseY{ -1 };
DropdownList* mOwner;
ClickButton* mPagePrevButton{ nullptr };
ClickButton* mPageNextButton{ nullptr };
bool mIsScrolling{ false };
};
enum class DropdownDisplayStyle
{
kNormal,
kHamburger
};
class DropdownList : public IUIControl
{
public:
DropdownList(IDropdownListener* owner, const char* name, int x, int y, int* var, float width = -1);
DropdownList(IDropdownListener* owner, const char* name, IUIControl* anchor, AnchorDirection anchorDirection, int* var, float width = -1);
void AddLabel(std::string label, int value);
void RemoveLabel(int value);
void SetLabel(std::string label, int value);
std::string GetLabel(int val) const;
void SetDisplayStyle(DropdownDisplayStyle style) { mDisplayStyle = style; }
void Render() override;
bool MouseMoved(float x, float y) override;
void MouseReleased() override;
void DrawDropdown(int w, int h, bool isScrolling);
bool DropdownClickedAt(int x, int y);
void SetIndex(int i, double time, bool forceUpdate);
void Clear();
void SetVar(int* var) { mVar = var; }
EnumMap GetEnumMap();
void SetUnknownItemString(std::string str)
{
mUnknownItemString = str;
CalculateWidth();
}
void DrawLabel(bool draw) { mDrawLabel = draw; }
void SetWidth(int width);
void SetDrawTriangle(bool draw) { mDrawTriangle = draw; }
void GetPopupDimensions(float& width, float& height) { mModalList.GetDimensions(width, height); }
void SetMaxPerColumn(int max)
{
mMaxPerColumn = max;
CalculateWidth();
}
int GetItemIndexAt(int x, int y);
DropdownListElement GetElement(int index) { return mElements[index]; }
DropdownListModal* GetModalDropdown() { return &mModalList; }
float GetMaxItemWidth() const { return mMaxItemWidth; }
void ChangePage(int direction);
void AddSeparator(int index) { mSeparators.push_back(index); }
void ClearSeparators() { mSeparators.clear(); }
void CopyContentsTo(DropdownList* list) const;
//IUIControl
void SetFromMidiCC(float slider, double time, bool setViaModulator) override;
float GetValueForMidiCC(float slider) const override;
void SetValue(float value, double time, bool forceUpdate = false) override;
float GetValue() const override;
float GetMidiValue() const override;
int GetNumValues() override { return (int)mElements.size(); }
std::string GetDisplayValue(float val) const override;
bool InvertScrollDirection() override { return true; }
void Increment(float amount) override;
void Poll() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, bool shouldSetValue = true) override;
void GetDimensions(float& width, float& height) override;
static constexpr int kItemSpacing = 15;
static constexpr int kPageBarSpacing = 20;
protected:
~DropdownList(); //protected so that it can't be created on the stack
private:
void OnClicked(float x, float y, bool right) override;
void CalcSliderVal();
int FindItemIndex(float val) const;
void CalculateWidth();
ofVec2f GetModalListPosition() const;
int mWidth{ 35 };
int mHeight{ DropdownList::kItemSpacing };
int mMaxItemWidth{ 20 };
int mMaxPerColumn{ 40 };
int mDisplayColumns{ 1 };
int mTotalColumns{ 1 };
int mCurrentPagedColumn{ 0 };
std::vector<DropdownListElement> mElements{};
int* mVar;
DropdownListModal mModalList;
bool mDropdownIsOpen{ false };
IDropdownListener* mOwner{ nullptr };
std::string mUnknownItemString{ "-----" };
bool mDrawLabel{ false };
float mLabelSize{ 0 };
float mSliderVal{ 0 };
int mLastSetValue{ 0 };
bool mAutoCalculateWidth{ false };
bool mDrawTriangle{ true };
double mLastScrolledTime{ -9999 };
std::vector<int> mSeparators;
DropdownDisplayStyle mDisplayStyle{ DropdownDisplayStyle::kNormal };
};
``` | /content/code_sandbox/Source/DropdownList.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,513 |
```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
**/
/*
==============================================================================
GridModule.cpp
Created: 19 Jul 2020 10:36:16pm
Author: Ryan Challinor
==============================================================================
*/
#include "GridModule.h"
#include "OpenFrameworksPort.h"
#include "SynthGlobals.h"
#include "ofxJSONElement.h"
#include "ModularSynth.h"
#include "ScriptModule.h"
#include "PatchCableSource.h"
GridModule::GridModule()
{
for (size_t i = 0; i < mHighlightCells.size(); ++i)
mHighlightCells[i].time = -1;
mColors.push_back(ofColor::white);
mColors.push_back(ofColor::magenta);
mColors.push_back(ofColor::lime);
mColors.push_back(ofColor::red);
mColors.push_back(ofColor::yellow);
mColors.push_back(ofColor::blue);
for (size_t i = 0; i < mGridOverlay.size(); ++i)
mGridOverlay[i] = -1;
}
void GridModule::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mMomentaryCheckbox = new Checkbox(this, "momentary", 40, 3, &mMomentary);
mGrid = new UIGrid("uigrid", 40, 22, 90, 90, 8, 8, this);
mGrid->SetListener(this);
mGridControlTarget = new GridControlTarget(this, "grid", 4, 4);
GetPatchCableSource()->SetEnabled(false);
mGridOutputCable = new PatchCableSource(this, kConnectionType_Grid);
mGridOutputCable->SetManualPosition(10, 30);
mGridOutputCable->AddTypeFilter("gridcontroller");
AddPatchCableSource(mGridOutputCable);
}
GridModule::~GridModule()
{
}
void GridModule::Init()
{
IDrawableModule::Init();
UpdateLights();
}
void GridModule::OnControllerPageSelected()
{
if (mGridControlTarget->GetGridController())
mGridControlTarget->GetGridController()->ResetLights();
UpdateLights();
}
void GridModule::GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue)
{
OnGridButton(col, row, value, nullptr);
}
void GridModule::OnGridButton(int x, int y, float velocity, IGridController* grid)
{
if (y < GetRows() && x < GetCols())
{
for (auto listener : mScriptListeners)
listener->RunCode(gTime, "on_grid_button(" + ofToString(x) + ", " + ofToString(y) + ", " + ofToString(velocity) + ")");
if (mGridControllerOwner)
mGridControllerOwner->OnGridButton(x, y, velocity, this);
}
UpdateLights();
}
void GridModule::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
OnGridButton(pitch % GetCols(), ((pitch / GetCols()) % GetRows()), velocity / 127.0f, nullptr);
}
void GridModule::UpdateLights()
{
if (!mGridControlTarget)
return;
for (int x = 0; x < GetCols(); ++x)
{
for (int y = 0; y < GetRows(); ++y)
{
if (mGridControlTarget->GetGridController())
{
if (mDirectColorMode)
mGridControlTarget->GetGridController()->SetLightDirect(x, y, Get(x, y) * 127);
else
mGridControlTarget->GetGridController()->SetLight(x, y, Get(x, y) > 0 ? kGridColor1Bright : kGridColorOff);
}
}
}
}
void GridModule::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mMomentaryCheckbox->Draw();
ofSetColor(150, 150, 150, 255);
mGrid->Draw();
mGridControlTarget->Draw();
ofPushStyle();
ofSetColor(128, 128, 128, gModuleDrawAlpha * .8f);
for (int i = 0; i < mGrid->GetRows() && i < (int)mLabels.size(); ++i)
{
ofVec2f pos = mGrid->GetCellPosition(0, i) + mGrid->GetPosition(true);
float scale = MIN(mGrid->IClickable::GetDimensions().y / mGrid->GetRows() - 2, 10);
DrawTextNormal(mLabels[i], 2, pos.y - (scale / 8), scale);
}
ofPopStyle();
ofPushStyle();
ofFill();
for (int i = 0; i < (int)mGridOverlay.size(); ++i)
{
if (mGridOverlay[i] > 0)
{
Vec2i cell(i % kGridOverlayMaxDim, i / kGridOverlayMaxDim);
if (cell.x < GetCols() && cell.y < GetRows())
{
ofVec2f pos = mGrid->GetCellPosition(cell.x, cell.y) + mGrid->GetPosition(true);
float xsize = float(mGrid->GetWidth()) / mGrid->GetCols();
float ysize = float(mGrid->GetHeight()) / mGrid->GetRows();
ofSetColor(GetColor(mGridOverlay[i]));
ofRect(pos.x + 3, pos.y + 3, xsize - 6, ysize - 6);
}
}
}
ofPopStyle();
ofPushStyle();
ofSetLineWidth(3);
for (size_t i = 0; i < mHighlightCells.size(); ++i)
{
if (mHighlightCells[i].time != -1)
{
if (gTime - mHighlightCells[i].time < mHighlightCells[i].duration)
{
if (gTime - mHighlightCells[i].time > 0)
{
ofVec2f pos = mGrid->GetCellPosition(mHighlightCells[i].position.x, mHighlightCells[i].position.y) + mGrid->GetPosition(true);
float xsize = float(mGrid->GetWidth()) / mGrid->GetCols();
float ysize = float(mGrid->GetHeight()) / mGrid->GetRows();
ofSetColor(mHighlightCells[i].color, (1 - (gTime - mHighlightCells[i].time) / mHighlightCells[i].duration) * 255);
ofRect(pos.x, pos.y, xsize, ysize);
}
}
else
{
mHighlightCells[i].time = -1;
}
}
}
ofPopStyle();
}
void GridModule::HighlightCell(int col, int row, double time, double duration, int colorIndex)
{
for (size_t i = 0; i < mHighlightCells.size(); ++i)
{
if (mHighlightCells[i].time == -1)
{
mHighlightCells[i].time = time;
mHighlightCells[i].position = Vec2i(col, row);
mHighlightCells[i].duration = duration;
mHighlightCells[i].color = GetColor(colorIndex);
break;
}
}
}
void GridModule::SetCellColor(int col, int row, int colorIndex)
{
mGridOverlay[col + row * kGridOverlayMaxDim] = colorIndex;
}
void GridModule::SetLabel(int row, std::string label)
{
if (row >= (int)mLabels.size())
mLabels.resize(row + 1);
mLabels[row] = label;
}
void GridModule::SetColor(int colorIndex, ofColor color)
{
if (colorIndex >= (int)mColors.size())
mColors.resize(colorIndex + 1);
mColors[colorIndex] = color;
}
ofColor GridModule::GetColor(int colorIndex) const
{
if (colorIndex < (int)mColors.size())
return mColors[colorIndex];
return ofColor::magenta;
}
void GridModule::AddListener(ScriptModule* listener)
{
if (!ListContains(listener, mScriptListeners))
mScriptListeners.push_back(listener);
}
void GridModule::Clear()
{
mGrid->Clear();
for (size_t i = 0; i < mGridOverlay.size(); ++i)
mGridOverlay[i] = -1;
UpdateLights();
}
void GridModule::GetModuleDimensions(float& width, float& height)
{
ofRectangle rect = mGrid->GetRect(true);
width = rect.x + rect.width + 2;
height = rect.y + rect.height + 6;
}
void GridModule::Resize(float w, float h)
{
float curW, curH;
GetModuleDimensions(curW, curH);
mGrid->SetDimensions(mGrid->GetWidth() + w - curW, mGrid->GetHeight() + h - curH);
}
void GridModule::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
mGrid->TestClick(x, y, right);
}
void GridModule::MouseReleased()
{
IDrawableModule::MouseReleased();
mGrid->MouseReleased();
}
void GridModule::SetLight(int x, int y, GridColor color, bool force)
{
if (x >= GetCols() || y >= GetRows())
return;
int colorIdx = (int)color;
SetLightDirect(x, y, colorIdx, force);
}
void GridModule::SetLightDirect(int x, int y, int color, bool force)
{
if (mGridControlTarget->GetGridController())
mGridControlTarget->GetGridController()->SetLightDirect(x, y, color, force);
SetCellColor(x, y, color);
mGrid->SetVal(x, y, color > 0 ? 1 : 0, false);
}
void GridModule::ResetLights()
{
if (mGridControlTarget->GetGridController())
mGridControlTarget->GetGridController()->ResetLights();
Clear();
}
bool GridModule::HasInput() const
{
return false;
}
void GridModule::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
if (cableSource == mGridOutputCable)
{
auto* target = dynamic_cast<GridControlTarget*>(cableSource->GetTarget());
if (target == mGridControlTarget) //patched into ourself
cableSource->Clear();
else if (target)
target->SetGridController(this);
}
}
void GridModule::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadBool("direct_color_mode", moduleInfo, true);
SetUpFromSaveData();
}
void GridModule::SetUpFromSaveData()
{
mDirectColorMode = mModuleSaveData.GetBool("direct_color_mode");
}
void GridModule::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mMomentaryCheckbox)
mGrid->SetMomentary(mMomentary);
}
void GridModule::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
mGrid->SaveState(out);
out << mGrid->GetWidth();
out << mGrid->GetHeight();
out << mGrid->GetCols();
out << mGrid->GetRows();
out << mGrid->GetMajorColSize();
out << (int)mLabels.size();
for (auto label : mLabels)
out << label;
out << (int)mColors.size();
for (auto color : mColors)
out << color.r << color.g << color.b;
for (auto overlay : mGridOverlay)
out << overlay;
}
void GridModule::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
if (rev >= 1)
{
mGrid->LoadState(in);
float w, h;
in >> w;
in >> h;
mGrid->SetDimensions(w, h);
}
if (rev >= 2)
{
int cols, rows, divisions, numLabels;
in >> cols;
in >> rows;
in >> divisions;
mGrid->SetGrid(cols, rows);
mGrid->SetMajorColSize(divisions);
in >> numLabels;
mLabels.resize(numLabels);
for (int i = 0; i < numLabels; ++i)
in >> mLabels[i];
}
if (rev >= 3)
{
int numColors;
in >> numColors;
mColors.resize(numColors);
for (int i = 0; i < numColors; ++i)
in >> mColors[i].r >> mColors[i].g >> mColors[i].b;
}
if (rev >= 4)
{
for (size_t i = 0; i < mGridOverlay.size(); ++i)
in >> mGridOverlay[i];
}
}
``` | /content/code_sandbox/Source/GridModule.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,986 |
```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
**/
/*
==============================================================================
NoteChance.h
Created: 29 Jan 2020 9:17:02pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "NoteEffectBase.h"
#include "Slider.h"
#include "ClickButton.h"
#include "TextEntry.h"
class NoteChance : public NoteEffectBase, public IFloatSliderListener, public IIntSliderListener, public IDrawableModule, public ITextEntryListener, public IButtonListener
{
public:
NoteChance();
virtual ~NoteChance();
static IDrawableModule* Create() { return new NoteChance(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override {}
void 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 mLength{ 4 };
IntSlider* mLengthSlider{ nullptr };
int mSeed{ 0 };
TextEntry* mSeedEntry{ nullptr };
ClickButton* mReseedButton{ nullptr };
ClickButton* mPrevSeedButton{ nullptr };
ClickButton* mNextSeedButton{ nullptr };
};
``` | /content/code_sandbox/Source/NoteChance.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 589 |
```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
**/
//
// LaunchpadInterpreter.h
// modularSynth
//
// Created by Ryan Challinor on 11/24/12.
//
//
#pragma once
#include "OpenFrameworksPort.h"
class MidiController;
struct MidiNote;
struct MidiControl;
struct LightUpdate
{
LightUpdate(int x, int y, char r, char g, float intensity = 1)
: mX(x)
, mY(y)
, mR(r)
, mG(g)
, mIntensity(intensity)
{}
int mX{ 0 };
int mY{ 0 };
char mR{ 0 };
char mG{ 0 };
float mIntensity{ 1 };
};
class ILaunchpadListener
{
public:
virtual ~ILaunchpadListener() {}
virtual void OnButtonPress(int x, int y, bool bOn) = 0;
};
class LaunchpadInterpreter
{
public:
LaunchpadInterpreter(ILaunchpadListener* listener);
void SetController(MidiController* controller, int controllerPage);
void OnMidiNote(MidiNote& note);
void OnMidiControl(MidiControl& control);
void UpdateLights(std::vector<LightUpdate> lightUpdates, bool force = false);
void Draw(ofVec2f vPos);
void ResetLaunchpad();
bool HasLaunchpad() { return mController != nullptr; }
static int LaunchpadColor(int r, int g);
private:
bool IsMonome() const;
ILaunchpadListener* mListener{ nullptr };
int mLights[64 + 8 + 8]{}; //grid + side + top
MidiController* mController{ nullptr };
int mControllerPage{ 0 };
};
``` | /content/code_sandbox/Source/LaunchpadInterpreter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 467 |
```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
**/
//
// PitchBender.h
// Bespoke
//
// Created by Ryan Challinor on 9/7/14.
//
//
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "ModulationChain.h"
#include "Transport.h"
class PitchBender : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public IAudioPoller
{
public:
PitchBender();
virtual ~PitchBender();
static IDrawableModule* Create() { return new PitchBender(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
//IAudioPoller
void OnTransportAdvanced(float amount) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 120;
height = 22;
}
float mBend;
FloatSlider* mBendSlider;
float mRange;
//Checkbox mBendingCheckbox;
Modulations mModulation;
};
``` | /content/code_sandbox/Source/PitchBender.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 495 |
```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
**/
//
// Checkbox.h
// modularSynth
//
// Created by Ryan Challinor on 12/4/12.
//
//
#pragma once
#include "IUIControl.h"
#include "IPulseReceiver.h"
#include "PatchCableSource.h"
class Checkbox;
class Checkbox : public IUIControl, public IPulseReceiver
{
public:
Checkbox(IDrawableModule* owner, const char* label, int x, int y, bool* var);
Checkbox(IDrawableModule* owner, const char* label, IUIControl* anchor, AnchorDirection anchorDirection, bool* var);
void SetLabel(const char* label);
void SetVar(bool* var) { mVar = var; }
void Render() override;
void SetDisplayText(bool display);
void UseCircleLook(ofColor color);
void DisableCircleLook() { mUseCircleLook = false; }
bool MouseMoved(float x, float y) override;
//IUIControl
void SetFromMidiCC(float slider, double time, bool setViaModulator) override;
float GetValueForMidiCC(float slider) const override;
void SetValue(float value, double time, bool forceUpdate = false) override;
float GetValue() const override;
float GetMidiValue() const override;
int GetNumValues() override { return 2; }
std::string GetDisplayValue(float val) const override;
void Increment(float amount) override;
void Poll() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, bool shouldSetValue = true) override;
bool IsSliderControl() override { return false; }
bool IsButtonControl() override { return true; }
void SetBoxSize(float size) { mHeight = size; }
bool CanBeTargetedBy(PatchCableSource* source) const override;
bool CheckNeedsDraw() override;
//IPulseReceiver
void OnPulse(double time, float velocity, int flags) override;
protected:
~Checkbox(); //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 CalcSliderVal();
void UpdateWidth();
float mWidth{ 15 };
float mHeight{ 15 };
bool* mVar{ nullptr };
IDrawableModule* mOwner{ nullptr };
bool mLastDisplayedValue{ false };
bool mDisplayText{ true };
bool mUseCircleLook{ false };
ofColor mCustomColor;
float mSliderVal{ 0 };
bool mLastSetValue{ false };
};
``` | /content/code_sandbox/Source/Checkbox.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 689 |
```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
**/
//
// DrumSynth.h
// Bespoke
//
// Created by Ryan Challinor on 8/5/14.
//
//
#pragma once
#include <iostream>
#include "IAudioSource.h"
#include "Sample.h"
#include "INoteReceiver.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "DropdownList.h"
#include "ClickButton.h"
#include "EnvOscillator.h"
#include "ADSR.h"
#include "RadioButton.h"
#include "PeakTracker.h"
#include "BiquadFilter.h"
#include "TextEntry.h"
#include "PatchCableSource.h"
class MidiController;
class ADSRDisplay;
#define DRUMSYNTH_PAD_WIDTH 180
#define DRUMSYNTH_PAD_HEIGHT 236
#define DRUMSYNTH_PADS_HORIZONTAL 4
#define DRUMSYNTH_PADS_VERTICAL 2
#define DRUMSYNTH_NO_CUTOFF 10000
class DrumSynth : public IAudioSource, public INoteReceiver, public IDrawableModule, public IFloatSliderListener, public IDropdownListener, public IButtonListener, public IIntSliderListener, public IRadioButtonListener, public ITextEntryListener
{
public:
DrumSynth();
~DrumSynth();
static IDrawableModule* Create() { return new DrumSynth(); }
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 { mEnabled = enabled; }
int GetNumTargets() override { return mUseIndividualOuts ? (int)mHits.size() + 1 : 1; }
//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 FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) override;
void TextEntryComplete(TextEntry* entry) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
struct DrumSynthHitSerialData
{
DrumSynthHitSerialData();
EnvOscillator mTone{ OscillatorType::kOsc_Sin };
EnvOscillator mNoise{ OscillatorType::kOsc_Random };
::ADSR mFreqAdsr;
::ADSR mFilterAdsr;
float mFreqMax{ 150 };
float mFreqMin{ 10 };
float mVol{ 0 };
float mVolNoise{ 0 };
float mCutoffMax{ DRUMSYNTH_NO_CUTOFF };
float mCutoffMin{ 10 };
float mQ{ float(sqrt(2)) / 2 };
};
struct IndividualOutput;
class DrumSynthHit
{
public:
DrumSynthHit(DrumSynth* parent, int index, int x, int y);
~DrumSynthHit();
void CreateUIControls();
void Play(double time, float velocity);
void Process(double time, float* out, int bufferSize, int oversampling, double sampleRate, double sampleIncrementMs);
float Level() { return mLevel.GetPeak(); }
void Draw();
DrumSynthHitSerialData mData;
float mPhase{ 0 };
ADSRDisplay* mToneAdsrDisplay{ nullptr };
ADSRDisplay* mFreqAdsrDisplay{ nullptr };
ADSRDisplay* mNoiseAdsrDisplay{ nullptr };
ADSRDisplay* mFilterAdsrDisplay{ nullptr };
FloatSlider* mVolSlider{ nullptr };
FloatSlider* mFreqMaxSlider{ nullptr };
FloatSlider* mFreqMinSlider{ nullptr };
RadioButton* mToneType{ nullptr };
PeakTracker mLevel;
FloatSlider* mVolNoiseSlider{ nullptr };
FloatSlider* mFilterCutoffMaxSlider{ nullptr };
FloatSlider* mFilterCutoffMinSlider{ nullptr };
FloatSlider* mFilterQSlider{ nullptr };
DrumSynth* mParent;
int mIndex{ 0 };
int mX{ 0 };
int mY{ 0 };
BiquadFilter mFilter;
IndividualOutput* mIndividualOutput{ nullptr };
};
struct IndividualOutput
{
IndividualOutput(DrumSynthHit* owner)
: mHit(owner)
{
mVizBuffer = new RollingBuffer(VIZ_BUFFER_SECONDS * gSampleRate);
mPatchCableSource = new PatchCableSource(owner->mParent, kConnectionType_Audio);
mPatchCableSource->SetOverrideVizBuffer(mVizBuffer);
mPatchCableSource->SetManualSide(PatchCableSource::Side::kRight);
owner->mParent->AddPatchCableSource(mPatchCableSource);
mPatchCableSource->SetManualPosition(mHit->mX + 30, mHit->mY + 8);
}
~IndividualOutput()
{
delete mVizBuffer;
}
DrumSynthHit* mHit{ nullptr };
RollingBuffer* mVizBuffer{ nullptr };
PatchCableSource* mPatchCableSource{ nullptr };
};
int GetAssociatedSampleIndex(int x, int y);
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void OnClicked(float x, float y, bool right) override;
std::array<DrumSynthHit*, DRUMSYNTH_PADS_HORIZONTAL * DRUMSYNTH_PADS_VERTICAL> mHits;
std::array<float, DRUMSYNTH_PADS_HORIZONTAL * DRUMSYNTH_PADS_VERTICAL> mVelocity{};
float mVolume{ 1 };
FloatSlider* mVolSlider{ nullptr };
bool mUseIndividualOuts{ false };
bool mMonoOutput{ false };
int mOversampling{ 1 };
};
``` | /content/code_sandbox/Source/DrumSynth.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,538 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// PressureToVibrato.cpp
// Bespoke
//
// Created by Ryan Challinor on 1/4/16.
//
//
#include "PressureToVibrato.h"
#include "OpenFrameworksPort.h"
#include "ModularSynth.h"
PressureToVibrato::PressureToVibrato()
{
}
PressureToVibrato::~PressureToVibrato()
{
}
void PressureToVibrato::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 PressureToVibrato::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mVibratoSlider->Draw();
mIntervalSelector->Draw();
}
void PressureToVibrato::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mEnabled)
{
mModulation.GetPitchBend(voiceIdx)->AppendTo(modulation.pitchBend);
mModulation.GetPitchBend(voiceIdx)->SetLFO(mVibratoInterval, mVibratoAmount);
mModulation.GetPitchBend(voiceIdx)->MultiplyIn(modulation.pressure);
modulation.pitchBend = mModulation.GetPitchBend(voiceIdx);
modulation.pressure = nullptr;
}
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
void PressureToVibrato::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void PressureToVibrato::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void PressureToVibrato::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void PressureToVibrato::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void PressureToVibrato::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/PressureToVibrato.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 751 |
```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
**/
//
// OscController.cpp
// Bespoke
//
// Created by Ryan Challinor on 5/1/14.
//
//
#include "OscController.h"
#include "SynthGlobals.h"
#include "IPulseReceiver.h"
#include "TitleBar.h"
OscController::OscController(MidiDeviceListener* listener, std::string outAddress, int outPort, int inPort)
: mListener(listener)
, mOutAddress(outAddress)
, mOutPort(outPort)
, mInPort(inPort)
{
Connect();
}
OscController::~OscController()
{
OSCReceiver::disconnect();
}
void OscController::Connect()
{
try
{
bool connected = OSCReceiver::connect(mInPort);
assert(connected);
OSCReceiver::addListener(this);
ConnectOutput();
mConnected = true;
}
catch (std::exception e)
{
}
}
void OscController::ConnectOutput()
{
if (mOutAddress != "" && mOutPort > 0)
{
mOutputConnected = mOscOut.connect(mOutAddress, mOutPort);
}
}
bool OscController::SetInPort(int port)
{
if (mInPort != port)
{
mInPort = port;
OSCReceiver::disconnect();
return OSCReceiver::connect(mInPort);
}
return false;
}
std::string OscController::GetControlTooltip(MidiMessageType type, int control)
{
if (type == kMidiMessage_Control && control >= 0 && control < mOscMap.size())
return mOscMap[control].mAddress;
return "[unmapped]";
}
void OscController::SendValue(int page, int control, float value, bool forceNoteOn /*= false*/, int channel /*= -1*/)
{
if (!mConnected)
return;
for (int i = 0; i < mOscMap.size(); ++i)
{
if (control == mOscMap[i].mControl) // && mOscMap[i].mLastChangedTime + 50 < gTime)
{
juce::OSCMessage msg(mOscMap[i].mAddress.c_str());
if (mOscMap[i].mIsFloat)
{
mOscMap[i].mFloatValue = value;
msg.addFloat32(mOscMap[i].mFloatValue);
}
else
{
mOscMap[i].mIntValue = value * 127;
msg.addInt32(mOscMap[i].mIntValue);
}
if (mOutputConnected)
mOscOut.send(msg);
}
}
}
void OscController::oscMessageReceived(const juce::OSCMessage& msg)
{
std::string address = msg.getAddressPattern().toString().toStdString();
if (address == "/jockey/sync") //support for handshake with Jockey OSC app
{
std::string outputAddress = msg[0].getString().toStdString();
std::vector<std::string> tokens = ofSplitString(outputAddress, ":");
if (tokens.size() == 2)
{
mOutAddress = tokens[0];
mOutPort = ofToInt(tokens[1]);
ConnectOutput();
}
return;
}
if (msg.size() == 0)
return; // Code beyond this point expects at least one parameter.
if (address.rfind("/bespoke/console", 0) == 0)
{
if (msg[0].isString())
TheSynth->OnConsoleInput(msg[0].getString().toStdString());
return;
}
bool is_percentage = false;
std::string control_prefix = "/bespoke/control/";
std::string control_scaled_prefix = "/bespoke/control_scaled/";
if (address.rfind(control_prefix, 0) == 0 || address.rfind(control_scaled_prefix, 0) == 0)
{
std::string control_path;
if (address.rfind(control_prefix, 0) == 0)
{
control_path = address.substr(control_prefix.length());
}
else if (address.rfind(control_scaled_prefix, 0) == 0)
{
is_percentage = true;
control_path = address.substr(control_scaled_prefix.length());
}
control_path = juce::URL::removeEscapeChars(control_path).toStdString();
IUIControl* control = control = TheSynth->FindUIControl(control_path);
if (control != nullptr)
{
if (msg[0].isFloat32() || msg[0].isInt32())
{
float new_value = msg[0].isFloat32() ? msg[0].getFloat32() : msg[0].getInt32();
DropdownList* dropdown = dynamic_cast<DropdownList*>(control);
if (is_percentage)
control->SetFromMidiCC(new_value, gTime, false);
else if (dropdown)
dropdown->SetIndex(new_value, gTime, true);
else
control->SetValue(new_value, gTime);
}
else if (msg[0].isString())
{
TextEntry* textEntry = dynamic_cast<TextEntry*>(control);
if (textEntry != nullptr)
textEntry->SetText(msg[0].getString().toStdString());
else
TheSynth->LogEvent("Could not find TextEntry " + control_path + " when trying to set string value through OSC.", kLogEventType_Error);
}
}
else
{
TheSynth->LogEvent("Could not find UI Control " + control_path + " when trying to set a value through OSC.", kLogEventType_Error);
}
return;
}
// Handle module direct messaging
std::string module_prefix = "/bespoke/module/";
if (address.rfind(module_prefix, 0) == 0)
{
auto parts = ofSplitString(address, "/", true, true);
if (parts.size() < 4)
return;
auto subcommand = parts[2];
auto module_path = juce::URL::removeEscapeChars(parts[3]).toStdString();
auto selected_module = TheSynth->FindModule(module_path);
if (!selected_module)
return;
if (subcommand == "note")
{
if (msg.size() < 2)
return;
auto selected_note_receiver = dynamic_cast<INoteReceiver*>(selected_module);
if (!selected_note_receiver)
return;
float pitch = msg[0].isFloat32() ? msg[0].getFloat32() : msg[0].getInt32();
float velocity = msg[1].isFloat32() ? msg[1].getFloat32() : msg[1].getInt32();
selected_note_receiver->PlayNote(gTime, pitch, velocity);
}
else if (subcommand == "pulse")
{
auto selected_pulse_receiver = dynamic_cast<IPulseReceiver*>(selected_module);
if (!selected_pulse_receiver)
return;
float velocity = msg[0].isFloat32() ? msg[0].getFloat32() : msg[0].getInt32();
selected_pulse_receiver->OnPulse(gTime, velocity, PulseFlags::kPulseFlag_None);
}
else if (subcommand == "minimize")
{
float minimize = msg[0].isFloat32() ? msg[0].getFloat32() : msg[0].getInt32();
if (minimize == 0)
selected_module->SetMinimized(false);
else if (minimize == 1)
selected_module->SetMinimized(true);
else
selected_module->SetMinimized(!selected_module->Minimized());
}
else if (subcommand == "enable")
{
float enable = msg[0].isFloat32() ? msg[0].getFloat32() : msg[0].getInt32();
if (enable == 0)
selected_module->SetEnabled(false);
else if (enable == 1)
selected_module->SetEnabled(true);
else
selected_module->SetEnabled(!selected_module->IsEnabled());
}
else if (subcommand == "focus")
{
ofRectangle module_rect = selected_module->GetRect();
float zoom = msg[0].isFloat32() ? msg[0].getFloat32() : msg[0].getInt32();
if (zoom >= 0.1)
gDrawScale = ofClamp(zoom, 0.1, 8);
else if (fabs(zoom) < 0.1) // Close to 0
{
//calculate zoom to view the entire module
float margin = 60;
float w_ratio = ofGetWidth() / (module_rect.width + margin);
float h_ratio = ofGetHeight() / (module_rect.height + margin);
float ratio = (w_ratio < h_ratio) ? w_ratio : h_ratio;
gDrawScale = ofClamp(ratio, 0.1, 8);
}
// Move viewport to centered on the module
float w, h;
TheTitleBar->GetDimensions(w, h);
TheSynth->SetDrawOffset(ofVec2f(-module_rect.x + ofGetWidth() / gDrawScale / 2 - module_rect.width / 2, -module_rect.y + ofGetHeight() / gDrawScale / 2 - (module_rect.height - h / 2) / 2));
}
return;
}
if (!msg[0].isFloat32() && !msg[0].isInt32())
return; // Code beyond this point expects at least one parameter of type int or float.
// Handle note data and output these as notes instead of CC's.
if (
(address.rfind("/note", 0) == 0 || address.rfind("/bespoke/note", 0) == 0) && msg.size() >= 2 &&
((msg[0].isFloat32() && msg[1].isFloat32()) || (msg[0].isInt32() && msg[1].isFloat32() && msg[2].isFloat32())))
{
MidiNote note;
note.mDeviceName = "osccontroller";
note.mChannel = 1;
int offset = 0;
if (msg.size() >= 3 && msg[0].isInt32())
{
note.mChannel = msg[0].getInt32();
offset = 1;
}
note.mPitch = msg[0 + offset].getFloat32();
if (msg[1 + offset].getFloat32() < 1 / 127)
note.mVelocity = 0;
else
note.mVelocity = msg[1 + offset].getFloat32() * 127;
//ofLog() << "OSCNote: P: " << note.mPitch << " V: " << note.mVelocity << " ch:" << note.mChannel;
if (mListener != nullptr)
mListener->OnMidiNote(note);
return;
}
// Handle special command to zoom the location (and allow suffixes, as some OSC software doesn't allow duplicate addresses on controls)
if (address.rfind("/bespoke/location/recall", 0) == 0 && msg.size() == 1 && (msg[0].isInt32() || msg[0].isFloat32()))
{
int number = msg[0].isInt32() ? msg[0].getInt32() : static_cast<int>(msg[0].getFloat32());
TheSynth->GetLocationZoomer()->MoveToLocation(number);
return; // Stop the midicontroller from mapping this to a CC value.
}
// Handle special command to store current viewport as a location (and allow suffixes, as some OSC software doesn't allow duplicate addresses on controls)
if (address.rfind("/bespoke/location/store", 0) == 0 && msg.size() == 1 && (msg[0].isInt32() || msg[0].isFloat32()))
{
int number = msg[0].isInt32() ? msg[0].getInt32() : static_cast<int>(msg[0].getFloat32());
TheSynth->GetLocationZoomer()->WriteCurrentLocation(number);
return; // Stop the midicontroller from mapping this to a CC value.
}
for (int i = 0; i < msg.size(); ++i)
{
auto calculated_address = (i > 0) ? address + "_" + std::to_string(i + 1) : address;
int mapIndex = FindControl(calculated_address);
bool isNew = false;
if (mapIndex == -1) //create a new map entry
{
isNew = true;
mapIndex = AddControl(calculated_address, msg[i].isFloat32());
}
MidiControl control;
control.mControl = mOscMap[mapIndex].mControl;
control.mDeviceName = "osccontroller";
control.mChannel = 1;
mOscMap[mapIndex].mLastChangedTime = gTime;
if (mOscMap[mapIndex].mIsFloat)
{
assert(msg[i].isFloat32());
mOscMap[mapIndex].mFloatValue = msg[i].getFloat32();
control.mValue = mOscMap[mapIndex].mFloatValue * 127;
}
else
{
assert(msg[i].isInt32());
mOscMap[mapIndex].mIntValue = msg[i].getInt32();
control.mValue = mOscMap[mapIndex].mIntValue;
}
if (isNew)
{
MidiController* midiController = dynamic_cast<MidiController*>(mListener);
if (midiController)
{
auto& layoutControl = midiController->GetLayoutControl(control.mControl, kMidiMessage_Control);
layoutControl.mConnectionType = mOscMap[mapIndex].mIsFloat ? kControlType_Slider : kControlType_Direct;
}
}
if (mListener != nullptr)
mListener->OnMidiControl(control);
}
}
int OscController::FindControl(std::string address)
{
for (int i = 0; i < mOscMap.size(); ++i)
{
if (address == mOscMap[i].mAddress)
return i;
}
return -1;
}
int OscController::AddControl(std::string address, bool isFloat)
{
int existing = FindControl(address);
if (existing != -1)
return existing;
OscMap entry;
int mapIndex = (int)mOscMap.size();
entry.mControl = mapIndex;
entry.mAddress = address;
entry.mIsFloat = isFloat;
mOscMap.push_back(entry);
return mapIndex;
}
namespace
{
const int kSaveStateRev = 1;
}
void OscController::SaveState(FileStreamOut& out)
{
out << kSaveStateRev;
out << (int)mOscMap.size();
for (size_t i = 0; i < mOscMap.size(); ++i)
{
out << mOscMap[i].mControl;
out << mOscMap[i].mAddress;
out << mOscMap[i].mIsFloat;
out << mOscMap[i].mFloatValue;
out << mOscMap[i].mIntValue;
out << mOscMap[i].mLastChangedTime;
}
}
void OscController::LoadState(FileStreamIn& in)
{
int rev;
in >> rev;
LoadStateValidate(rev <= kSaveStateRev);
int mapSize;
in >> mapSize;
mOscMap.resize(mapSize);
for (size_t i = 0; i < mOscMap.size(); ++i)
{
in >> mOscMap[i].mControl;
in >> mOscMap[i].mAddress;
in >> mOscMap[i].mIsFloat;
in >> mOscMap[i].mFloatValue;
in >> mOscMap[i].mIntValue;
in >> mOscMap[i].mLastChangedTime;
}
}
``` | /content/code_sandbox/Source/OscController.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 3,602 |
```c++
#include "PSMoveMgr.h"
#include <chrono>
#include <thread>
//--------------------------------------------------------------
void PSMoveMgr::Setup()
{
for (int i = 0; i < MAX_NUM_PS_MOVES; ++i)
mMove[i] = NULL;
AddMoves();
}
void PSMoveMgr::AddMoves()
{
for (int i = 0; i < MAX_NUM_PS_MOVES; ++i)
{
if (mMove[i] == NULL)
mMove[i] = SetUpMove(i);
}
}
_PSMove* PSMoveMgr::SetUpMove(int id)
{
_PSMove* move = NULL;
int lastBTController = -1;
for (int i = 0; i <= id; ++i)
{
enum PSMove_Connection_Type ctype = Conn_Unknown; //valid: Conn_Unknown, Conn_USB, Conn_Bluetooth
for (int j = lastBTController + 1; ctype != Conn_Bluetooth; ++j) //find the next bluetooth one
{
move = psmove_connect_by_id(j);
if (move == NULL)
{
return NULL;
}
ctype = psmove_connection_type(move);
lastBTController = j;
}
}
for (int i = 0; i < 10; i++)
{
psmove_set_leds(move, 0, 255 * (i % 3 == 0), 0);
//psmove_set_rumble(move, 255*(i%2));
psmove_update_leds(move);
std::this_thread::sleep_for(std::chrono::milliseconds{ 10 * (i % 10) });
}
for (int i = 250; i >= 0; i -= 5)
{
psmove_set_leds(move, i, i, 0);
psmove_set_rumble(move, 0);
psmove_update_leds(move);
}
psmove_set_leds(move, 0, 0, 0);
psmove_set_rumble(move, 0);
psmove_update_leds(move);
mButtons[id] = 0;
printf("Connected Move #%d\n", id);
return move;
}
void PSMoveMgr::GetGyros(int id, ofVec3f& gyros)
{
if (mMove[id])
{
int x, y, z;
psmove_get_gyroscope(mMove[id], &x, &y, &z);
gyros.x = x;
gyros.y = y;
gyros.z = z;
}
}
void PSMoveMgr::GetAccel(int id, ofVec3f& accel)
{
if (mMove[id])
{
int x, y, z;
psmove_get_accelerometer(mMove[id], &x, &y, &z);
accel.x = x;
accel.y = y;
accel.z = z;
}
}
bool PSMoveMgr::IsButtonDown(int id, PSMove_Button button)
{
if (mMove[id])
{
int currentButtons = psmove_get_buttons(mMove[id]);
return currentButtons & button;
}
return false;
}
float PSMoveMgr::GetBattery(int id)
{
if (mMove[id])
{
return psmove_get_battery(mMove[id]) / 5.0f;
}
return 0;
}
//--------------------------------------------------------------
void PSMoveMgr::Update()
{
for (int i = 0; i < MAX_NUM_PS_MOVES; ++i)
{
if (mMove[i])
{
_PSMove* move = mMove[i];
int res = 1;
while (res)
res = psmove_poll(move); //poll until there's no new data, so we have the freshest
int currentButtons = psmove_get_buttons(move);
int change = currentButtons ^ mButtons[i];
int pressed = currentButtons & change;
int released = mButtons[i] & change;
mButtons[i] = currentButtons;
if (Btn_TRIANGLE & pressed)
SendButtonMessage(i, "triangle", 1);
if (Btn_TRIANGLE & released)
SendButtonMessage(i, "triangle", 0);
if (Btn_CIRCLE & pressed)
SendButtonMessage(i, "circle", 1);
if (Btn_CIRCLE & released)
SendButtonMessage(i, "circle", 0);
if (Btn_CROSS & pressed)
SendButtonMessage(i, "cross", 1);
if (Btn_CROSS & released)
SendButtonMessage(i, "cross", 0);
if (Btn_SQUARE & pressed)
SendButtonMessage(i, "square", 1);
if (Btn_SQUARE & released)
SendButtonMessage(i, "square", 0);
if (Btn_SELECT & pressed)
SendButtonMessage(i, "select", 1);
if (Btn_SELECT & released)
SendButtonMessage(i, "select", 0);
if (Btn_START & pressed)
SendButtonMessage(i, "start", 1);
if (Btn_START & released)
SendButtonMessage(i, "start", 0);
if (Btn_PS & pressed)
SendButtonMessage(i, "ps", 1);
if (Btn_PS & released)
SendButtonMessage(i, "ps", 0);
if (Btn_MOVE & pressed)
SendButtonMessage(i, "move", 1);
if (Btn_MOVE & released)
SendButtonMessage(i, "move", 0);
if (Btn_T & pressed)
SendButtonMessage(i, "trigger", 1);
if (Btn_T & released)
SendButtonMessage(i, "trigger", 0);
psmove_update_leds(move);
}
}
}
void PSMoveMgr::SendButtonMessage(int id, std::string button, int val)
{
std::string address = "/" + ofToString(id) + "/button/" + button;
//TheMessenger->SendIntMessage(address,val);
if (mListener)
mListener->OnPSMoveButton(id, button, val);
}
void PSMoveMgr::Exit()
{
for (int i = 0; i < MAX_NUM_PS_MOVES; ++i)
{
if (mMove[i])
{
psmove_disconnect(mMove[i]);
}
}
}
void PSMoveMgr::SetVibration(int id, float amount)
{
if (mMove[id] == NULL)
return;
psmove_set_rumble(mMove[id], int(amount * 255));
}
void PSMoveMgr::SetColor(int id, float r, float g, float b)
{
if (mMove[id] == NULL)
return;
psmove_set_leds(mMove[id], int(r * 255), int(g * 255), int(b * 255));
}
``` | /content/code_sandbox/Source/PSMoveMgr.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,491 |
```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
**/
//
// ModWheel.h
// Bespoke
//
// Created by Ryan Challinor on 1/4/16.
//
//
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "ModulationChain.h"
#include "Transport.h"
class ModWheel : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public IAudioPoller
{
public:
ModWheel();
virtual ~ModWheel();
static IDrawableModule* Create() { return new ModWheel(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
//IAudioPoller
void OnTransportAdvanced(float amount) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 120;
height = 22;
}
float mModWheel{ 0 };
FloatSlider* mModWheelSlider{ nullptr };
Modulations mModulation{ true };
};
``` | /content/code_sandbox/Source/ModWheel.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 484 |
```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
**/
//
// Ramp.cpp
// modularSynth
//
// Created by Ryan Challinor on 11/26/12.
//
//
#include "Ramp.h"
#include "SynthGlobals.h"
void Ramp::Start(double curTime, float end, double endTime)
{
float startValue = Value(curTime);
Start(curTime, startValue, end, endTime);
}
void Ramp::Start(double curTime, float start, float end, double endTime)
{
mRampDatas[mRampDataPointer].mStartTime = curTime;
mRampDatas[mRampDataPointer].mStartValue = start;
mRampDatas[mRampDataPointer].mEndValue = end;
mRampDatas[mRampDataPointer].mEndTime = endTime;
mRampDataPointer = (mRampDataPointer + 1) % mRampDatas.size();
}
void Ramp::SetValue(float val)
{
for (size_t i = 0; i < mRampDatas.size(); ++i)
{
mRampDatas[i].mStartValue = val;
mRampDatas[i].mEndValue = val;
mRampDatas[i].mStartTime = 0;
}
}
bool Ramp::HasValue(double time) const
{
const RampData* rampData = GetCurrentRampData(time);
if (rampData->mStartTime == -1)
return false;
return true;
}
float Ramp::Value(double time) const
{
const RampData* rampData = GetCurrentRampData(time);
if (rampData->mStartTime == -1 || time <= rampData->mStartTime)
return rampData->mStartValue;
if (time >= rampData->mEndTime)
return rampData->mEndValue;
double blend = (time - rampData->mStartTime) / (rampData->mEndTime - rampData->mStartTime);
float retVal = rampData->mStartValue + blend * (rampData->mEndValue - rampData->mStartValue);
if (fabsf(retVal) < FLT_EPSILON)
return 0;
return retVal;
}
const Ramp::RampData* Ramp::GetCurrentRampData(double time) const
{
int ret = 0;
double latestTime = -1;
for (int i = 0; i < (int)mRampDatas.size(); ++i)
{
if (mRampDatas[i].mStartTime < time && mRampDatas[i].mStartTime > latestTime)
{
ret = i;
latestTime = mRampDatas[i].mStartTime;
}
}
return &(mRampDatas[ret]);
}
``` | /content/code_sandbox/Source/Ramp.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 678 |
```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
**/
//
// KarplusStrong.h
// modularSynth
//
// Created by Ryan Challinor on 2/11/13.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "PolyphonyMgr.h"
#include "KarplusStrongVoice.h"
#include "INoteReceiver.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "DropdownList.h"
#include "Checkbox.h"
#include "BiquadFilterEffect.h"
#include "ChannelBuffer.h"
class KarplusStrong : public IAudioProcessor, public INoteReceiver, public IDrawableModule, public IDropdownListener, public IFloatSliderListener
{
public:
KarplusStrong();
~KarplusStrong();
static IDrawableModule* Create() { return new KarplusStrong(); }
static bool AcceptsAudio() { return true; }
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 DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
bool HasDebugDraw() const override { return true; }
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void DrawModuleUnclipped() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 275;
height = 126;
}
PolyphonyMgr mPolyMgr;
NoteInputBuffer mNoteInputBuffer;
KarplusStrongVoiceParams mVoiceParams;
FloatSlider* mFilterSlider{ nullptr };
FloatSlider* mFeedbackSlider{ nullptr };
float mVolume{ 1 };
FloatSlider* mVolSlider{ nullptr };
DropdownList* mSourceDropdown{ nullptr };
Checkbox* mInvertCheckbox{ nullptr };
BiquadFilterEffect mBiquad;
BiquadFilter mDCRemover[ChannelBuffer::kMaxNumChannels];
Checkbox* mStretchCheckbox{ nullptr };
FloatSlider* mExciterFreqSlider{ nullptr };
FloatSlider* mExciterAttackSlider{ nullptr };
FloatSlider* mExciterDecaySlider{ nullptr };
FloatSlider* mPitchToneSlider{ nullptr };
FloatSlider* mVelToVolumeSlider{ nullptr };
FloatSlider* mVelToEnvelopeSlider{ nullptr };
Checkbox* mLiteCPUModeCheckbox{ nullptr };
ChannelBuffer mWriteBuffer;
};
``` | /content/code_sandbox/Source/KarplusStrong.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 767 |
```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
**/
//
// FormantFilterEffect.cpp
// Bespoke
//
// Created by Ryan Challinor on 4/21/16.
//
//
#include "FormantFilterEffect.h"
#include "SynthGlobals.h"
#include "FloatSliderLFOControl.h"
#include "Profiler.h"
#include "UIControlMacros.h"
FormantFilterEffect::FormantFilterEffect()
{
mOutputBuffer = new float[gBufferSize];
for (int i = 0; i < NUM_FORMANT_BANDS; ++i)
mBiquads[i].SetFilterType(kFilterType_Bandpass);
mFormants.push_back(Formants(400, 1, 1700, .35f, 2300, .4f)); //EE
mFormants.push_back(Formants(360, 1, 750, .25f, 2400, .035f)); //OO
mFormants.push_back(Formants(238, 1, 1741, .1f, 2450, .15f)); //I
mFormants.push_back(Formants(300, 1, 1600, .2f, 2150, .25f)); //E
mFormants.push_back(Formants(415, 1, 1400, .25f, 2200, .15f)); //U
mFormants.push_back(Formants(609, 1, 1000, .5f, 2450, .25f)); //A
}
void FormantFilterEffect::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
FLOATSLIDER(mEESlider, "ee", &mEE, 0, 1);
FLOATSLIDER(mOOSlider, "oo", &mOO, 0, 1);
FLOATSLIDER(mISlider, "i", &mI, 0, 1);
FLOATSLIDER(mESlider, "e", &mE, 0, 1);
FLOATSLIDER(mUSlider, "u", &mU, 0, 1);
FLOATSLIDER(mASlider, "a", &mA, 0, 1);
ENDUIBLOCK(mWidth, mHeight);
mSliders.push_back(mEESlider);
mSliders.push_back(mOOSlider);
mSliders.push_back(mISlider);
mSliders.push_back(mESlider);
mSliders.push_back(mUSlider);
mSliders.push_back(mASlider);
}
FormantFilterEffect::~FormantFilterEffect()
{
}
void FormantFilterEffect::Init()
{
IDrawableModule::Init();
}
void FormantFilterEffect::ProcessAudio(double time, ChannelBuffer* buffer)
{
PROFILER(FormantFilterEffect);
if (!mEnabled)
return;
float bufferSize = buffer->BufferSize();
ComputeSliders(0);
assert(gBufferSize == bufferSize);
Clear(mOutputBuffer, bufferSize);
//TODO(Ryan)
/*for (int i=0; i<NUM_FORMANT_BANDS; ++i)
{
BufferCopy(gWorkBuffer, audio, bufferSize);
mBiquads[i].Filter(gWorkBuffer, bufferSize);
Add(mOutputBuffer, gWorkBuffer, bufferSize);
}
BufferCopy(audio, gWorkBuffer, bufferSize);*/
}
void FormantFilterEffect::DrawModule()
{
mEESlider->Draw();
mOOSlider->Draw();
mISlider->Draw();
mESlider->Draw();
mUSlider->Draw();
mASlider->Draw();
}
float FormantFilterEffect::GetEffectAmount()
{
if (!mEnabled)
return 0;
return 1;
}
void FormantFilterEffect::ResetFilters()
{
for (int i = 0; i < NUM_FORMANT_BANDS; ++i)
mBiquads[i].Clear();
}
void FormantFilterEffect::UpdateFilters()
{
assert(NUM_FORMANT_BANDS == 3);
float total = 0;
for (int i = 0; i < mSliders.size(); ++i)
total += mSliders[i]->GetValue();
if (total == 0)
return;
std::vector<float> formant;
formant.resize(NUM_FORMANT_BANDS);
formant.assign(NUM_FORMANT_BANDS, 0);
assert(mSliders.size() == mFormants.size());
for (int i = 0; i < mSliders.size(); ++i)
{
float weight = mSliders[i]->GetValue() / total;
for (int j = 0; j < NUM_FORMANT_BANDS; ++j)
formant[j] += mFormants[i].mFreqs[j] * mFormants[i].mGains[j] * weight;
}
const float bandwidth = 100;
for (int i = 0; i < NUM_FORMANT_BANDS; ++i)
mBiquads[i].SetFilterParams(formant[i], formant[i] / (bandwidth / 2));
}
void FormantFilterEffect::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void FormantFilterEffect::RadioButtonUpdated(RadioButton* list, int oldVal, double time)
{
}
void FormantFilterEffect::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
ResetFilters();
}
}
void FormantFilterEffect::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (!mRescaling)
{
mRescaling = true;
for (int i = 0; i < mSliders.size(); ++i)
{
if (mSliders[i] != slider)
{
mSliders[i]->SetValue(mSliders[i]->GetValue() * (1 - (slider->GetValue() - oldVal)), time);
}
}
UpdateFilters();
mRescaling = false;
}
}
void FormantFilterEffect::LoadLayout(const ofxJSONElement& info)
{
}
void FormantFilterEffect::SetUpFromSaveData()
{
ResetFilters();
}
void FormantFilterEffect::SaveLayout(ofxJSONElement& info)
{
mModuleSaveData.Save(info);
}
``` | /content/code_sandbox/Source/FormantFilterEffect.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,458 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NoteEcho.cpp
Created: 29 March 2022
Author: Ryan Challinor
==============================================================================
*/
#include "NoteEcho.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
#include "UIControlMacros.h"
NoteEcho::NoteEcho()
{
for (int i = 0; i < kMaxDestinations; ++i)
mDelay[i] = i * .125f;
}
void NoteEcho::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
for (int i = 0; i < kMaxDestinations; ++i)
{
FLOATSLIDER(mDelaySlider[i], ("delay " + ofToString(i)).c_str(), &mDelay[i], 0, 1);
mDestinationCables[i] = 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 = mDelaySlider[i]->GetRect(true);
mDestinationCables[i]->GetPatchCableSource()->SetManualPosition(rect.getMaxX() + 10, rect.y + rect.height / 2);
}
ENDUIBLOCK(mWidth, mHeight);
mWidth += 20;
GetPatchCableSource()->SetEnabled(false);
}
void NoteEcho::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
for (int i = 0; i < kMaxDestinations; ++i)
mDelaySlider[i]->Draw();
}
void NoteEcho::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
ComputeSliders(0);
for (int i = 0; i < kMaxDestinations; ++i)
{
double delayMs = mDelay[i] / (float(TheTransport->GetTimeSigTop()) / TheTransport->GetTimeSigBottom()) * TheTransport->MsPerBar();
SendNoteToIndex(i, time + delayMs, pitch, velocity, voiceIdx, modulation);
}
}
void NoteEcho::SendNoteToIndex(int index, double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
mDestinationCables[index]->PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
void NoteEcho::SendCC(int control, int value, int voiceIdx)
{
SendCCOutput(control, value, voiceIdx);
}
void NoteEcho::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void NoteEcho::SetUpFromSaveData()
{
}
void NoteEcho::SaveLayout(ofxJSONElement& moduleInfo)
{
}
``` | /content/code_sandbox/Source/NoteEcho.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 754 |
```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
**/
/*
==============================================================================
PressureToCV.h
Created: 28 Nov 2017 9:44:30pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "INoteReceiver.h"
#include "IModulator.h"
#include "Slider.h"
class PatchCableSource;
class PressureToCV : public IDrawableModule, public INoteReceiver, public IModulator, public IFloatSliderListener
{
public:
PressureToCV();
virtual ~PressureToCV();
static IDrawableModule* Create() { return new PressureToCV(); }
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 {}
//IModulator
virtual float Value(int samplesIn = 0) override;
virtual bool Active() const override { return mEnabled; }
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void SaveLayout(ofxJSONElement& moduleInfo) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 106;
height = 17 * 2 + 2;
}
ModulationChain* mPressure{ nullptr };
};
``` | /content/code_sandbox/Source/PressureToCV.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 539 |
```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
**/
/*
==============================================================================
OSCOutput.h
Created: 27 Sep 2018 9:35:59pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "OpenFrameworksPort.h"
#include "TextEntry.h"
#include "Slider.h"
#include "INoteReceiver.h"
#include "juce_osc/juce_osc.h"
#define OSC_OUTPUT_MAX_PARAMS 50
class OSCOutput : public IDrawableModule, public ITextEntryListener, public IFloatSliderListener, public INoteReceiver
{
public:
OSCOutput();
virtual ~OSCOutput();
static IDrawableModule* Create() { return new OSCOutput(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void Init() override;
void Poll() override;
void CreateUIControls() override;
void SendFloat(std::string address, float val);
void SendInt(std::string address, int val);
void SendString(std::string address, std::string val);
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) override;
void SendCC(int control, int value, int voiceIdx = -1) override {}
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void TextEntryComplete(TextEntry* entry) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
std::string mLabels[OSC_OUTPUT_MAX_PARAMS];
std::list<TextEntry*> mLabelEntry{};
float mParams[OSC_OUTPUT_MAX_PARAMS];
std::list<FloatSlider*> mSliders{};
std::string mOscOutAddress{ "127.0.0.1" };
TextEntry* mOscOutAddressEntry{ nullptr };
int mOscOutPort{ 7000 };
TextEntry* mOscOutPortEntry{ nullptr };
std::string mNoteOutLabel{ "note" };
TextEntry* mNoteOutLabelEntry{ nullptr };
juce::OSCSender mOscOut;
float mWidth{ 200 };
float mHeight{ 20 };
};
``` | /content/code_sandbox/Source/OSCOutput.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 663 |
```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
**/
//
// Vocoder.cpp
// modularSynth
//
// Created by Ryan Challinor on 4/17/13.
//
//
#include "Vocoder.h"
#include "ModularSynth.h"
#include "Profiler.h"
Vocoder::Vocoder()
: IAudioProcessor(gBufferSize)
{
// Generate a window with a single raised cosine from N/4 to 3N/4
mWindower = new float[VOCODER_WINDOW_SIZE];
for (int i = 0; i < VOCODER_WINDOW_SIZE; ++i)
mWindower[i] = -.5 * cos(FTWO_PI * i / VOCODER_WINDOW_SIZE) + .5;
mCarrierInputBuffer = new float[GetBuffer()->BufferSize()];
Clear(mCarrierInputBuffer, GetBuffer()->BufferSize());
AddChild(&mGate);
mGate.SetPosition(110, 20);
mGate.SetEnabled(false);
}
void Vocoder::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mInputSlider = new FloatSlider(this, "input", 5, 29, 100, 15, &mInputPreamp, 0, 2);
mCarrierSlider = new FloatSlider(this, "carrier", 5, 47, 100, 15, &mCarrierPreamp, 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);
mFricativeSlider = new FloatSlider(this, "fric thresh", 5, 101, 100, 15, &mFricativeThresh, 0, 1);
mWhisperSlider = new FloatSlider(this, "whisper", 5, 119, 100, 15, &mWhisper, 0, 1);
mPhaseOffsetSlider = new FloatSlider(this, "phase off", 5, 137, 100, 15, &mPhaseOffset, 0, FTWO_PI);
mCutSlider = new IntSlider(this, "cut", 5, 155, 100, 15, &mCut, 0, 100);
mGate.CreateUIControls();
}
Vocoder::~Vocoder()
{
delete[] mWindower;
delete[] mCarrierInputBuffer;
}
void Vocoder::SetCarrierBuffer(float* carrier, int bufferSize)
{
assert(bufferSize == GetBuffer()->BufferSize());
BufferCopy(mCarrierInputBuffer, carrier, bufferSize);
mCarrierDataSet = true;
}
void Vocoder::Process(double time)
{
PROFILER(Vocoder);
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();
int zerox = 0; //count up zero crossings
bool positive = true;
for (int i = 0; i < bufferSize; ++i)
{
if ((GetBuffer()->GetChannel(0)[i] < 0 && positive) ||
(GetBuffer()->GetChannel(0)[i] > 0 && !positive))
{
++zerox;
positive = !positive;
}
}
bool fricative = zerox > (bufferSize * mFricativeThresh); //if a % of the samples are zero crossings, this is a fricative
if (fricative)
mFricDetected = true; //draw that we detected a fricative
mGate.ProcessAudio(time, GetBuffer());
mRollingInputBuffer.WriteChunk(GetBuffer()->GetChannel(0), bufferSize, 0);
//copy rolling input buffer into working buffer and window it
mRollingInputBuffer.ReadChunk(mFFTData.mTimeDomain, VOCODER_WINDOW_SIZE, 0, 0);
Mult(mFFTData.mTimeDomain, mWindower, VOCODER_WINDOW_SIZE);
Mult(mFFTData.mTimeDomain, inputPreampSq, VOCODER_WINDOW_SIZE);
mFFT.Forward(mFFTData.mTimeDomain,
mFFTData.mRealValues,
mFFTData.mImaginaryValues);
if (!fricative)
{
mRollingCarrierBuffer.WriteChunk(mCarrierInputBuffer, bufferSize, 0);
}
else
{
//use noise as carrier signal if it's a fricative
//but make the noise the same-ish volume as input carrier
for (int i = 0; i < bufferSize; ++i)
mRollingCarrierBuffer.Write(mCarrierInputBuffer[gRandom() % bufferSize] * 2, 0);
}
//copy rolling carrier buffer into working buffer and window it
mRollingCarrierBuffer.ReadChunk(mCarrierFFTData.mTimeDomain, VOCODER_WINDOW_SIZE, 0, 0);
Mult(mCarrierFFTData.mTimeDomain, mWindower, VOCODER_WINDOW_SIZE);
Mult(mCarrierFFTData.mTimeDomain, carrierPreampSq, VOCODER_WINDOW_SIZE);
mFFT.Forward(mCarrierFFTData.mTimeDomain,
mCarrierFFTData.mRealValues,
mCarrierFFTData.mImaginaryValues);
for (int i = 0; i < FFT_FREQDOMAIN_SIZE; ++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);
float carrierReal = mCarrierFFTData.mRealValues[i];
float carrierImag = mCarrierFFTData.mImaginaryValues[i];
//cartesian to polar
float carrierAmp = 2. * sqrtf(carrierReal * carrierReal + carrierImag * carrierImag);
float carrierPhase = atan2(carrierImag, carrierReal);
amp *= carrierAmp;
float phase = carrierPhase;
phase += ofRandom(mWhisper * FTWO_PI);
mPhaseOffsetSlider->Compute();
phase = FloatWrap(phase + mPhaseOffset, FTWO_PI);
if (i < mCut) //cut out superbass
amp = 0;
//polar to cartesian
real = amp * cos(phase);
imag = amp * sin(phase);
mFFTData.mRealValues[i] = real;
mFFTData.mImaginaryValues[i] = imag;
}
mFFT.Inverse(mFFTData.mRealValues,
mFFTData.mImaginaryValues,
mFFTData.mTimeDomain);
for (int i = 0; i < bufferSize; ++i)
mRollingOutputBuffer.Write(0, 0);
//copy rolling input buffer into working buffer and window it
for (int i = 0; i < VOCODER_WINDOW_SIZE; ++i)
mRollingOutputBuffer.Accum(VOCODER_WINDOW_SIZE - i - 1, mFFTData.mTimeDomain[i] * mWindower[i] * .0001f, 0);
Mult(GetBuffer()->GetChannel(0), (1 - mDryWet) * inputPreampSq, GetBuffer()->BufferSize());
for (int i = 0; i < bufferSize; ++i)
GetBuffer()->GetChannel(0)[i] += mRollingOutputBuffer.GetSample(VOCODER_WINDOW_SIZE - i - 1, 0) * volSq * mDryWet;
Add(target->GetBuffer()->GetChannel(0), GetBuffer()->GetChannel(0), bufferSize);
GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(0), bufferSize, 0);
GetBuffer()->Reset();
}
void Vocoder::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
if (!mCarrierDataSet)
{
ofPushStyle();
ofSetColor(255, 0, 0);
DrawTextNormal("no vocodercarrier!", 5, 15);
ofPopStyle();
}
mInputSlider->Draw();
mCarrierSlider->Draw();
mVolumeSlider->Draw();
mDryWetSlider->Draw();
mFricativeSlider->Draw();
mWhisperSlider->Draw();
mPhaseOffsetSlider->Draw();
mCutSlider->Draw();
if (mFricDetected)
{
ofPushStyle();
ofFill();
ofSetColor(255, 0, 0, gModuleDrawAlpha * .4f);
ofRect(5, 101, 100, 14);
ofPopStyle();
mFricDetected = false;
}
mGate.Draw();
}
void Vocoder::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
mGate.SetEnabled(mEnabled);
}
}
void Vocoder::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void Vocoder::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
``` | /content/code_sandbox/Source/Vocoder.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,276 |
```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
**/
//
// Amplifier.h
// modularSynth
//
// Created by Ryan Challinor on 7/13/13.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "Slider.h"
class Amplifier : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener
{
public:
Amplifier();
virtual ~Amplifier();
static IDrawableModule* Create() { return new Amplifier(); }
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 {}
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 = 22;
}
float mGain{ 1 };
FloatSlider* mGainSlider{ nullptr };
};
``` | /content/code_sandbox/Source/Amplifier.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 409 |
```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
**/
//
// DelayEffect.h
// modularSynth
//
// Created by Ryan Challinor on 11/25/12.
//
//
#pragma once
#include <iostream>
#include "IAudioEffect.h"
#include "RollingBuffer.h"
#include "Slider.h"
#include "Checkbox.h"
#include "DropdownList.h"
#include "Transport.h"
#include "Ramp.h"
#define DELAY_BUFFER_SIZE 5 * gSampleRate
class DelayEffect : public IAudioEffect, public IFloatSliderListener, public IDropdownListener
{
public:
DelayEffect();
static IAudioEffect* Create() { return new DelayEffect(); }
void CreateUIControls() override;
bool IsEnabled() const override { return mEnabled; }
void SetDelay(float delay);
void SetShortMode(bool on);
void SetFeedback(float feedback) { mFeedback = feedback; }
void Clear() { mDelayBuffer.ClearBuffer(); }
void SetDry(bool dry) { mDry = dry; }
void SetFeedbackModuleMode();
//IAudioEffect
void ProcessAudio(double time, ChannelBuffer* buffer) override;
void SetEnabled(bool enabled) override;
float GetEffectAmount() override;
std::string GetType() override { return "delay"; }
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 SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 0; }
private:
//IDrawableModule
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void DrawModule() override;
float GetMinDelayMs() const;
float mDelay{ 500 };
float mFeedback{ 0 };
bool mEcho{ true };
RollingBuffer mDelayBuffer;
FloatSlider* mFeedbackSlider{ nullptr };
FloatSlider* mDelaySlider{ nullptr };
Checkbox* mEchoCheckbox{ nullptr };
NoteInterval mInterval{ NoteInterval::kInterval_8nd };
DropdownList* mIntervalSelector{ nullptr };
bool mShortTime{ false };
Checkbox* mShortTimeCheckbox{ nullptr };
Ramp mDelayRamp;
Ramp mAmountRamp;
bool mAcceptInput{ true };
bool mDry{ true };
bool mInvert{ false };
Checkbox* mDryCheckbox{ nullptr };
Checkbox* mAcceptInputCheckbox{ nullptr };
Checkbox* mInvertCheckbox{ nullptr };
float mWidth{ 200 };
float mHeight{ 20 };
bool mFeedbackModuleMode{ false }; //special mode when this delay effect is being used in a FeedbackModule
};
``` | /content/code_sandbox/Source/DelayEffect.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 722 |
```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
**/
//
// KarplusStrongVoice.h
// modularSynth
//
// Created by Ryan Challinor on 2/11/13.
//
//
#pragma once
#include "IMidiVoice.h"
#include "IVoiceParams.h"
#include "ADSR.h"
#include "EnvOscillator.h"
#include "RollingBuffer.h"
#include "Ramp.h"
class IDrawableModule;
class KarplusStrong;
enum KarplusStrongSourceType
{
kSourceTypeSin,
kSourceTypeNoise,
kSourceTypeMix,
kSourceTypeSaw,
kSourceTypeInput,
kSourceTypeInputNoEnvelope
};
class KarplusStrongVoiceParams : public IVoiceParams
{
public:
KarplusStrongVoiceParams()
{
}
float mFilter{ 1 };
float mFeedback{ .98 };
KarplusStrongSourceType mSourceType{ KarplusStrongSourceType::kSourceTypeMix };
bool mInvert{ false };
float mExciterFreq{ 100 };
float mExciterAttack{ 1 };
float mExciterDecay{ 3 };
float mExcitation{ 0 };
float mPitchTone{ 0 };
float mVelToVolume{ .5 };
float mVelToEnvelope{ .5 };
bool mLiteCPUMode{ false };
};
class KarplusStrongVoice : public IMidiVoice
{
public:
KarplusStrongVoice(IDrawableModule* owner = nullptr);
~KarplusStrongVoice();
// IMidiVoice
void Start(double time, float amount) override;
void Stop(double time) override;
void ClearVoice() override;
bool Process(double time, ChannelBuffer* out, int oversampling) override;
void SetVoiceParams(IVoiceParams* params) override;
bool IsDone(double time) override;
private:
void DoParameterUpdate(int samplesIn,
int oversampling,
float& pitch,
float& freq,
float& filterRate,
float& filterLerp,
float& oscPhaseInc);
float mOscPhase{ 0 };
EnvOscillator mOsc{ OscillatorType::kOsc_Sin };
::ADSR mEnv;
KarplusStrongVoiceParams* mVoiceParams{ nullptr };
RollingBuffer mBuffer;
float mFilteredSample{ 0 };
Ramp mMuteRamp;
float mLastBufferSample{ 0 };
bool mActive{ false };
IDrawableModule* mOwner{ nullptr };
KarplusStrong* mKarplusStrongModule{ nullptr };
};
``` | /content/code_sandbox/Source/KarplusStrongVoice.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 638 |
```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
**/
//
// DotSequencer.h
// Bespoke
//
// Created by Ryan Challinor on 12/27/23.
//
//
#pragma once
#include <iostream>
#include "ClickButton.h"
#include "IDrawableModule.h"
#include "INoteReceiver.h"
#include "INoteSource.h"
#include "Slider.h"
#include "IDrivableSequencer.h"
#include "DotGrid.h"
#include "Transport.h"
class DotSequencer : public IDrawableModule, public IButtonListener, public IDropdownListener, public IIntSliderListener, public ITimeListener, public INoteSource, public IDrivableSequencer, public IAudioPoller
{
public:
DotSequencer();
virtual ~DotSequencer();
static IDrawableModule* Create() { return new DotSequencer(); }
void CreateUIControls() override;
void Init() override;
//IDrawableModule
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//IClickable
bool MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) override;
//IAudioPoller
void OnTransportAdvanced(float amount) override;
//ITimeListener
void OnTimeEvent(double time) override;
//IDrivableSequencer
bool HasExternalPulseSource() const override { return mHasExternalPulseSource; }
void ResetExternalPulseSource() override { mHasExternalPulseSource = false; }
void DropdownUpdated(DropdownList* list, int 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;
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; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
bool IsEnabled() const override { return mEnabled; }
bool IsResizable() const override { return true; }
void Resize(float w, float h) override;
void OnStep(double time, float velocity, int flags);
int RowToPitch(int row) const;
enum class NoteMode
{
Scale,
Chromatic
};
float mWidth{ 400 }, mHeight{ 200 };
bool mHasExternalPulseSource{ false };
int mStepIdx{ -1 };
TransportListenerInfo* mTransportListenerInfo{ nullptr };
bool mShouldStopAllNotes{ false };
NoteInterval mInterval{ NoteInterval::kInterval_8n };
DropdownList* mIntervalSelector{ nullptr };
NoteMode mNoteMode{ NoteMode::Scale };
DropdownList* mNoteModeSelector{ nullptr };
ClickButton* mClearButton{ nullptr };
int mOctave{ 4 };
IntSlider* mOctaveSlider{ nullptr };
int mCols{ 16 };
IntSlider* mColsSlider{ nullptr };
int mRows{ 13 };
IntSlider* mRowsSlider{ nullptr };
int mRowOffset{ 0 };
IntSlider* mRowOffsetSlider{ nullptr };
ClickButton* mDoubleButton{ nullptr };
DotGrid* mDotGrid{ nullptr };
struct PlayingDot
{
int mRow{ 0 };
int mCol{ 0 };
int mPitch{ -1 };
double mPlayedTime{ 0 };
};
std::array<PlayingDot, 100> mPlayingDots;
};
``` | /content/code_sandbox/Source/DotSequencer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 941 |
```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.cpp
// modularSynth
//
// Created by Ryan Challinor on 1/1/13.
//
//
#include "UIGrid.h"
#include "SynthGlobals.h"
#include "FileStream.h"
#include "IDrawableModule.h"
#include "PatchCableSource.h"
#include "Snapshots.h"
#include <cstring>
UIGrid::UIGrid(std::string name, int x, int y, int w, int h, int cols, int rows, IClickable* parent)
: mWidth(w)
, mHeight(h)
{
SetName(name.c_str());
SetPosition(x, y);
SetGrid(cols, rows);
Clear();
SetParent(parent);
mDrawOffset.fill(0);
dynamic_cast<IDrawableModule*>(parent)->AddUIGrid(this);
}
UIGrid::~UIGrid()
{
}
void UIGrid::Init(int x, int y, int w, int h, int cols, int rows, IClickable* parent)
{
mWidth = w;
mHeight = h;
SetPosition(x, y);
SetGrid(cols, rows);
Clear();
SetParent(parent);
mDrawOffset.fill(0);
}
void UIGrid::Render()
{
ofPushMatrix();
ofTranslate(mX, mY);
ofPushStyle();
ofSetLineWidth(.5f);
float w, h;
GetDimensions(w, h);
float xsize = float(mWidth) / mCols;
float ysize = float(mHeight) / mRows;
for (int j = 0; j < mRows; ++j)
{
for (int i = 0; i < mCols; ++i)
{
float x = GetX(i, j);
float y = GetY(j);
float data = mData[GetDataIndex(i, j)];
if (data)
{
ofFill();
float sliderFillAmount = ofClamp(ofLerp(.15f, 1, data), 0, 1);
if (mGridMode == kNormal)
{
ofSetColor(255 * data, 255 * data, 255 * data, gModuleDrawAlpha);
ofRect(x, y, xsize, ysize);
}
else if (mGridMode == kMultislider)
{
float fadeAmount = ofClamp(ofLerp(.5f, 1, data), 0, 1);
ofSetColor(255 * fadeAmount, 255 * fadeAmount, 255 * fadeAmount, gModuleDrawAlpha);
ofRect(x + .5f, y + .5f + (ysize * (1 - sliderFillAmount)), xsize - 1, ysize * sliderFillAmount - 1, 0);
/*ofSetColor(255, 255, 255, gModuleDrawAlpha);
ofNoFill();
ofRect(x+1,y+1,xsize-2,ysize-2, gCornerRoundness*.99f);*/
}
else if (mGridMode == kHorislider)
{
ofSetColor(255, 255, 255, gModuleDrawAlpha);
ofRect(x, y, xsize * sliderFillAmount, ysize);
}
else if (mGridMode == kMultisliderBipolar)
{
float fadeAmount = ofClamp(ofLerp(.5f, 1, data), 0, 1);
ofSetColor(255 * fadeAmount, 255 * fadeAmount, 255 * fadeAmount, gModuleDrawAlpha);
ofRect(x, y + ysize * (.5f - sliderFillAmount / 2), xsize, ysize * sliderFillAmount);
if (mClick && mHoldVal != 0 && CanAdjustMultislider())
{
if (j == mHoldRow)
{
ofSetColor(0, 255, 0, gModuleDrawAlpha);
ofRect(x + .5f, y + .5f + (ysize * (1 - sliderFillAmount)), xsize - 1, 2, 0);
}
}
}
}
if (mCurrentHover == i + j * mCols && gHoveredUIControl == nullptr)
{
ofFill();
ofSetColor(180, 180, 0, 160);
ofRect(x + 2, y + 2, std::min(xsize * mCurrentHoverAmount, xsize - 4), ysize - 4);
}
}
}
ofNoFill();
ofSetColor(100, 100, 100, gModuleDrawAlpha);
for (int j = 0; j < mRows; ++j)
{
for (int i = 0; i < mCols; ++i)
ofRect(GetX(i, j), GetY(j), xsize, ysize);
}
ofNoFill();
if (mMajorCol > 0)
{
ofSetColor(255, 200, 100, gModuleDrawAlpha);
for (int j = 0; j < mRows; ++j)
{
for (int i = 0; i < mCols; i += mMajorCol)
{
ofRect(GetX(i, j), GetY(j), xsize, ysize);
}
}
if (mCols > mMajorCol * mMajorCol)
{
ofSetColor(255, 255, 100, gModuleDrawAlpha);
for (int j = 0; j < mRows; ++j)
{
for (int i = 0; i < mCols; i += mMajorCol * mMajorCol)
{
ofRect(GetX(i, j), GetY(j), xsize, ysize);
}
}
if (mCols > mMajorCol * mMajorCol * mMajorCol)
{
ofSetColor(255, 255, 200, gModuleDrawAlpha);
for (int j = 0; j < mRows; ++j)
{
for (int i = 0; i < mCols; i += mMajorCol * mMajorCol * mMajorCol)
{
ofRect(GetX(i, j), GetY(j), xsize, ysize);
}
}
}
}
}
if (GetHighlightCol(gTime) != -1)
{
ofNoFill();
ofSetColor(0, 255, 0, gModuleDrawAlpha);
for (int j = 0; j < mRows; ++j)
ofRect(GetX(GetHighlightCol(gTime), j), GetY(j), xsize, ysize);
}
if (mCurrentHover != -1 && mShouldDrawValue)
{
ofSetColor(ofColor::grey, gModuleDrawAlpha);
DrawTextNormal(ofToString(GetVal(mCurrentHover % mCols, mCurrentHover / mCols)), 0, 12);
}
ofPopStyle();
ofPopMatrix();
}
float UIGrid::GetX(int col, int row) const
{
float xsize = float(mWidth) / mCols;
return (col + mDrawOffset[std::clamp(row, 0, (int)mDrawOffset.size() - 1)]) * xsize;
}
float UIGrid::GetY(int row) const
{
float ysize = float(mHeight) / mRows;
if (mFlip)
return mHeight - (row + 1) * ysize;
else
return row * ysize;
}
GridCell UIGrid::GetGridCellAt(float x, float y, float* clickHeight, float* clickWidth)
{
if (mFlip)
y = (mHeight - 1) - y;
float xsize = float(mWidth) / mCols;
float ysize = float(mHeight) / mRows;
int col = ofClamp(x / xsize, 0, mCols - 1);
int row = ofClamp(y / ysize, 0, mRows - 1);
if (clickHeight)
{
*clickHeight = ofClamp(1 - (y / ysize - ofClamp((int)(y / ysize), 0, mRows - 1)), 0, 1);
if (mFlip)
*clickHeight = 1 - *clickHeight;
}
if (clickWidth)
{
*clickWidth = ofClamp(x / xsize - ofClamp((int)(x / xsize), 0, mCols - 1), 0, 1);
}
return GridCell(col, row);
}
ofVec2f UIGrid::GetCellPosition(int col, int row)
{
return ofVec2f(GetX(col, row), GetY(row));
}
bool UIGrid::CanAdjustMultislider() const
{
return !mRequireShiftForMultislider || (GetKeyModifiers() & kModifier_Shift);
}
float UIGrid::GetSubdividedValue(float position) const
{
return ofClamp(ceil(position * mClickSubdivisions) / mClickSubdivisions, 1.0f / mClickSubdivisions, 1);
}
bool UIGrid::CanBeTargetedBy(PatchCableSource* source) const
{
return source->GetConnectionType() == kConnectionType_UIControl && dynamic_cast<Snapshots*>(source->GetOwner()) != nullptr;
}
void UIGrid::OnClicked(float x, float y, bool right)
{
if (right)
return;
mClick = true;
mLastClickWasClear = false;
float clickHeight, clickWidth;
GridCell cell = GetGridCellAt(x, y, &clickHeight, &clickWidth);
int dataIndex = GetDataIndex(cell.mCol, cell.mRow);
float oldValue = mData[dataIndex];
if (mGridMode == kMultislider || mGridMode == kMultisliderBipolar)
{
if (CanAdjustMultislider())
{
mData[dataIndex] = clickHeight;
}
else
{
if (mData[dataIndex] > 0)
{
mData[dataIndex] = 0;
mLastClickWasClear = true;
}
else
{
mData[dataIndex] = mStrength;
}
}
}
else if (mGridMode == kHorislider)
{
if (CanAdjustMultislider())
{
mData[dataIndex] = clickWidth;
}
else
{
float val = mStrength;
if (mSingleColumn)
{
for (int i = 0; i < MAX_GRID_ROWS; ++i)
{
if (mData[GetDataIndex(cell.mCol, i)] != 0)
val = mData[GetDataIndex(cell.mCol, i)];
}
}
if (mClickSubdivisions != 1)
val = GetSubdividedValue(clickWidth);
if (mData[dataIndex] == val)
{
mData[dataIndex] = 0;
mLastClickWasClear = true;
}
else
{
mData[dataIndex] = val;
}
}
}
else
{
if (mData[dataIndex] > 0)
{
mData[dataIndex] = 0;
mLastClickWasClear = true;
}
else
{
mData[dataIndex] = mStrength;
}
}
if (mSingleColumn)
{
for (int i = 0; i < MAX_GRID_ROWS; ++i)
{
if (i != cell.mRow)
mData[GetDataIndex(cell.mCol, i)] = 0;
}
}
if (mListener)
mListener->GridUpdated(this, cell.mCol, cell.mRow, mData[dataIndex], oldValue);
mHoldVal = mData[dataIndex];
mHoldCol = cell.mCol;
mHoldRow = cell.mRow;
}
void UIGrid::MouseReleased()
{
if (mClick && mMomentary)
{
float oldValue = mData[GetDataIndex(mHoldCol, mHoldRow)];
mData[GetDataIndex(mHoldCol, mHoldRow)] = 0;
mListener->GridUpdated(this, mHoldCol, mHoldRow, 0, oldValue);
}
mClick = false;
}
bool UIGrid::MouseMoved(float x, float y)
{
bool isMouseOver = (x >= 0 && x < mWidth && y >= 0 && y < mHeight);
float clickHeight, clickWidth;
GridCell cell = GetGridCellAt(x, y, &clickHeight, &clickWidth);
if (mClick && mRestrictDragToRow)
{
if (cell.mRow > mHoldRow)
clickHeight = mFlip ? 1 : 0;
if (cell.mRow < mHoldRow)
clickHeight = mFlip ? 0 : 1;
cell.mRow = mHoldRow;
}
if (mClick && mGridMode == kHorislider && CanAdjustMultislider())
{
if (cell.mCol > mHoldCol)
clickWidth = 1;
if (cell.mCol < mHoldCol)
clickWidth = 0;
cell.mCol = mHoldCol;
}
if (isMouseOver)
{
mCurrentHover = cell.mCol + cell.mRow * mCols;
if (mGridMode == kHorislider && CanAdjustMultislider())
mCurrentHoverAmount = clickWidth;
else if (mClickSubdivisions != -1)
mCurrentHoverAmount = GetSubdividedValue(clickWidth);
else
mCurrentHoverAmount = 1;
}
else if (!mClick)
{
mCurrentHover = -1;
}
if (mClick && !mMomentary)
{
int dataIndex = GetDataIndex(cell.mCol, cell.mRow);
float oldValue = mData[dataIndex];
if (mGridMode == kMultislider && mHoldVal != 0 && CanAdjustMultislider())
{
mData[dataIndex] = clickHeight;
}
else if (mGridMode == kMultisliderBipolar && mHoldVal != 0 && CanAdjustMultislider())
{
mData[dataIndex] = clickHeight;
}
else if (mGridMode == kHorislider)
{
float val = mHoldVal;
mHoldCol = cell.mCol;
if (mSingleColumn)
{
for (int i = 0; i < MAX_GRID_ROWS; ++i)
{
if (mData[GetDataIndex(cell.mCol, i)] != 0)
val = mData[GetDataIndex(cell.mCol, i)];
}
}
if (CanAdjustMultislider())
val = clickWidth;
else if (mClickSubdivisions != 1)
val = GetSubdividedValue(clickWidth);
mData[dataIndex] = val;
}
else
{
mData[dataIndex] = mHoldVal;
}
if (mSingleColumn)
{
for (int i = 0; i < MAX_GRID_ROWS; ++i)
{
if (i != cell.mRow || mLastClickWasClear)
mData[GetDataIndex(cell.mCol, i)] = 0;
}
}
if (mListener)
mListener->GridUpdated(this, cell.mCol, cell.mRow, mData[dataIndex], oldValue);
}
return false;
}
bool UIGrid::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll)
{
if (mGridMode == kMultislider || mGridMode == kHorislider || mGridMode == kMultisliderBipolar)
{
bool isMouseOver = (x >= 0 && x < mWidth && y >= 0 && y < mHeight);
float clickHeight, clickWidth;
GridCell cell = GetGridCellAt(x, y, &clickHeight, &clickWidth);
if (isMouseOver)
{
float& data = mData[GetDataIndex(cell.mCol, cell.mRow)];
if (!mSingleColumn || data > 0)
{
float oldValue = data;
data = ofClamp(data + scrollY / 100, FLT_EPSILON, 1);
if (mListener)
mListener->GridUpdated(this, cell.mCol, cell.mRow, data, oldValue);
}
}
}
return false;
}
void UIGrid::SetGrid(int cols, int rows)
{
cols = ofClamp(cols, 0, MAX_GRID_COLS);
rows = ofClamp(rows, 0, MAX_GRID_ROWS);
mRows = rows;
mCols = cols;
}
void UIGrid::Clear()
{
mData.fill(0);
}
float& UIGrid::GetVal(int col, int row)
{
col = ofClamp(col, 0, MAX_GRID_COLS - 1);
row = ofClamp(row, 0, MAX_GRID_ROWS - 1);
return mData[GetDataIndex(col, row)];
}
void UIGrid::SetVal(int col, int row, float val, bool notifyListener)
{
col = ofClamp(col, 0, MAX_GRID_COLS - 1);
row = ofClamp(row, 0, MAX_GRID_ROWS - 1);
if (val != mData[GetDataIndex(col, row)])
{
float oldValue = mData[GetDataIndex(col, row)];
mData[GetDataIndex(col, row)] = val;
if (mSingleColumn && val > 0)
{
for (int i = 0; i < MAX_GRID_ROWS; ++i)
{
if (i != row)
mData[GetDataIndex(col, i)] = 0;
}
}
if (notifyListener && mListener)
mListener->GridUpdated(this, col, row, val, oldValue);
}
}
void UIGrid::SetHighlightCol(double time, int col)
{
mHighlightColBuffer[mNextHighlightColPointer].time = time;
mHighlightColBuffer[mNextHighlightColPointer].col = col;
mNextHighlightColPointer = (mNextHighlightColPointer + 1) % mHighlightColBuffer.size();
}
int UIGrid::GetHighlightCol(double time) const
{
int ret = -1;
double latestTime = -1;
for (size_t i = 0; i < mHighlightColBuffer.size(); ++i)
{
if (mHighlightColBuffer[i].time <= time && mHighlightColBuffer[i].time > latestTime)
{
ret = mHighlightColBuffer[i].col;
latestTime = mHighlightColBuffer[i].time;
}
}
return ret;
}
namespace
{
const int kSaveStateRev = 2;
}
void UIGrid::SaveState(FileStreamOut& out)
{
out << kSaveStateRev;
out << mCols;
out << mRows;
for (int col = 0; col < mCols; ++col)
{
for (int row = 0; row < mRows; ++row)
out << mData[GetDataIndex(col, row)];
}
}
void UIGrid::LoadState(FileStreamIn& in, bool shouldSetValue)
{
int rev;
in >> rev;
LoadStateValidate(rev <= kSaveStateRev);
int cols;
int rows;
if (rev < 1)
{
cols = 100;
rows = 100;
}
else if (rev == 1)
{
cols = 128;
rows = 128;
}
else
{
in >> mCols;
in >> mRows;
cols = mCols;
rows = mRows;
}
for (int col = 0; col < cols; ++col)
{
for (int row = 0; row < rows; ++row)
{
int dataIndex;
if (rev < 2)
dataIndex = GetDataIndex(row, col);
else
dataIndex = GetDataIndex(col, row);
float oldVal = mData[dataIndex];
in >> mData[dataIndex];
if (mListener)
mListener->GridUpdated(this, col, row, mData[dataIndex], oldVal);
}
}
}
``` | /content/code_sandbox/Source/UIGrid.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 4,525 |
```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.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/3/12.
//
//
#include "Razor.h"
#include "SynthGlobals.h"
#include "IAudioReceiver.h"
#include "Scale.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "ModulationChain.h"
#include <cstring>
namespace
{
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 };
}
Razor::Razor()
{
std::memset(mAmp, 0, sizeof(float) * NUM_PARTIALS);
std::memset(mPeakHistory, 0, sizeof(float) * (VIZ_WIDTH + 1) * RAZOR_HISTORY);
std::memset(mPhases, 0, sizeof(float) * NUM_PARTIALS);
for (int i = 0; i < NUM_PARTIALS; ++i)
mDetune[i] = 1;
}
void Razor::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mNumPartialsSlider = new IntSlider(this, "partials", 5, 40, 320, 15, &mUseNumPartials, 1, NUM_PARTIALS);
mBumpAmpSlider = new FloatSlider(this, "bump freq 1", 5, 60, 320, 15, &mBumps[0].mFreq, 0, 10000);
mBumpAmpAmtSlider = new FloatSlider(this, "amt 1", 5, 80, 320, 15, &mBumps[0].mAmt, -1, 1);
mBumpAmpDecaySlider = new FloatSlider(this, "decay 1", 5, 100, 320, 15, &mBumps[0].mDecay, 0.00001f, .01f, 4);
mBumpAmpSlider2 = new FloatSlider(this, "bump freq 2", 330, 60, 320, 15, &mBumps[1].mFreq, 0, 10000);
mBumpAmpAmtSlider2 = new FloatSlider(this, "amt 2", 330, 80, 320, 15, &mBumps[1].mAmt, -1, 1);
mBumpAmpDecaySlider2 = new FloatSlider(this, "decay 2", 330, 100, 320, 15, &mBumps[1].mDecay, 0.00001f, .01f, 4);
mBumpAmpSlider3 = new FloatSlider(this, "bump freq 3", 660, 60, 320, 15, &mBumps[2].mFreq, 0, 10000);
mBumpAmpAmtSlider3 = new FloatSlider(this, "amt 3", 660, 80, 320, 15, &mBumps[2].mAmt, -1, 1);
mBumpAmpDecaySlider3 = new FloatSlider(this, "decay 3", 660, 100, 320, 15, &mBumps[2].mDecay, 0.00001f, .01f, 4);
mASlider = new FloatSlider(this, "A", 450, 342, 80, 15, &mA, 1, 1000);
mDSlider = new FloatSlider(this, "D", 450, 358, 80, 15, &mD, 1, 1000);
mSSlider = new FloatSlider(this, "S", 450, 374, 80, 15, &mS, 0, 1);
mRSlider = new FloatSlider(this, "R", 450, 390, 80, 15, &mR, 1, 1000);
mHarmonicSelectorSlider = new IntSlider(this, "harmonics", 5, 120, 160, 15, &mHarmonicSelector, -1, 10);
mPowFalloffSlider = new FloatSlider(this, "pow falloff", 170, 120, 160, 15, &mPowFalloff, .1f, 2);
mNegHarmonicsSlider = new IntSlider(this, "neg harmonics", 335, 120, 160, 15, &mNegHarmonics, 1, 10);
mHarshnessCutSlider = new FloatSlider(this, "harshness cut", 500, 120, 160, 15, &mHarshnessCut, 0, 20000);
mManualControlCheckbox = new Checkbox(this, "manual control", 4, 145, &mManualControl);
for (int i = 0; i < NUM_AMP_SLIDERS; ++i)
{
mAmpSliders[i] = new FloatSlider(this, ("amp" + ofToString(i)).c_str(), 4, 160 + i * 16, 200, 15, &mAmp[i], -1, 1);
mDetuneSliders[i] = new FloatSlider(this, ("detune" + ofToString(i)).c_str(), 210, 160 + i * 16, 200, 15, &mDetune[i], .98f, 1.02f);
}
mResetDetuneButton = new ClickButton(this, "reset detune", 210, 145);
mASlider->SetMode(FloatSlider::kSquare);
mDSlider->SetMode(FloatSlider::kSquare);
mRSlider->SetMode(FloatSlider::kSquare);
}
Razor::~Razor()
{
}
void Razor::Process(double time)
{
PROFILER(Razor);
IAudioReceiver* target = GetTarget();
if (!mEnabled || target == nullptr)
return;
ComputeSliders(0);
int bufferSize = target->GetBuffer()->BufferSize();
float* out = target->GetBuffer()->GetChannel(0);
assert(bufferSize == gBufferSize);
if (!mManualControl)
CalcAmp();
for (int i = 0; i < bufferSize; ++i)
{
float freq = TheScale->PitchToFreq(mPitch + (mPitchBend ? mPitchBend->GetValue(i) : 0));
int oscNyquistLimitIdx = int(gNyquistLimit / freq);
float write = 0;
for (int j = 0; j < mUseNumPartials && j < oscNyquistLimitIdx; ++j)
{
float phaseInc = 512. / (gSampleRate / (freq)) * (j + 1) * mDetune[j];
mPhases[j] += phaseInc;
while (mPhases[j] >= 512)
{
mPhases[j] -= 512;
}
float sample = SinSample(mPhases[j]) * mAdsr[j].Value(time) * mAmp[j] * mVol;
write += sample;
}
GetVizBuffer()->Write(write, 0);
out[i] += write;
time += gInvSampleRateMs;
}
}
void Razor::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (!mEnabled)
return;
if (velocity > 0)
{
float amount = velocity / 127.0f;
mPitch = pitch;
for (int i = 1; i <= NUM_PARTIALS; ++i)
{
mAdsr[i - 1].Start(time, amount,
mA,
mD,
mS,
mR);
}
mPitchBend = modulation.pitchBend;
mModWheel = modulation.modWheel;
mPressure = modulation.pressure;
}
else if (mPitch == pitch)
{
for (int i = 0; i < NUM_PARTIALS; ++i)
mAdsr[i].Stop(time);
}
}
void Razor::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
if (mEnabled)
{
DrawViz();
mNumPartialsSlider->Draw();
mBumpAmpSlider->Draw();
mBumpAmpAmtSlider->Draw();
mBumpAmpDecaySlider->Draw();
mBumpAmpSlider2->Draw();
mBumpAmpAmtSlider2->Draw();
mBumpAmpDecaySlider2->Draw();
mBumpAmpSlider3->Draw();
mBumpAmpAmtSlider3->Draw();
mBumpAmpDecaySlider3->Draw();
mHarmonicSelectorSlider->Draw();
mPowFalloffSlider->Draw();
mNegHarmonicsSlider->Draw();
mHarshnessCutSlider->Draw();
mASlider->Draw();
mDSlider->Draw();
mSSlider->Draw();
mRSlider->Draw();
mManualControlCheckbox->Draw();
for (int i = 0; i < NUM_AMP_SLIDERS; ++i)
{
mAmpSliders[i]->Draw();
mDetuneSliders[i]->Draw();
}
mResetDetuneButton->Draw();
}
}
void Razor::DrawViz()
{
ofPushStyle();
int zeroHeight = 240;
float baseFreq = TheScale->PitchToFreq(mPitch);
int oscNyquistLimitIdx = int(gNyquistLimit / baseFreq);
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 <= mUseNumPartials && i <= oscNyquistLimitIdx; ++i)
{
float height = mAdsr[i - 1].Value(gTime) * mAmp[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);
}
float freq = baseFreq * i;
int x = int(ofMap(log2(freq), 4, log2(gNyquistLimit), 0, VIZ_WIDTH, true));
//int x = int(ofMap(freq,0,gNyquistLimit,0,VIZ_WIDTH,true));
ofLine(10 + x, zeroHeight, 10 + x, zeroHeight - intHeight);
mPeakHistory[mHistoryPtr][x] = intHeight;
}
mHistoryPtr = (mHistoryPtr - 1 + RAZOR_HISTORY) % RAZOR_HISTORY;
ofPopStyle();
}
float Razor::SinSample(float phase)
{
int intPhase = int(phase) % 512;
float remainder = phase - int(phase);
return ((1 - remainder) * sineBuffer[intPhase] + remainder * sineBuffer[1 + intPhase]);
}
bool IsPrime(int n)
{
if (n == 1)
return true;
if (n % 2 == 0)
return (n == 2);
if (n % 3 == 0)
return (n == 3);
int m = sqrt(n);
for (int i = 5; i <= m; i += 6)
{
if (n % i == 0)
return false;
if (n % (i + 2) == 0)
return false;
}
return true;
}
bool IsPow2(int n)
{
while (n)
{
if (n == 1)
return true;
if (n % 2 && n != 1)
return false;
n >>= 1;
}
return false;
}
void Razor::CalcAmp()
{
float baseFreq = TheScale->PitchToFreq(mPitch);
int oscNyquistLimitIdx = int(gNyquistLimit / baseFreq);
std::memset(mAmp, 0, sizeof(float) * NUM_PARTIALS);
for (int i = 1; i <= mUseNumPartials && i <= oscNyquistLimitIdx; ++i)
{
if ((mHarmonicSelector == 0 && IsPrime(i)) ||
(mHarmonicSelector == -1 && IsPow2(i)) ||
mHarmonicSelector == 1 ||
(mHarmonicSelector > 0 && i % mHarmonicSelector == 1))
{
float freq = baseFreq * i;
mAmp[i - 1] = 1.0f / powf(i, mPowFalloff);
for (int j = 0; j < NUM_BUMPS; ++j)
{
float freqDist = fabs(mBumps[j].mFreq - freq);
float dist = PI / 2 - freqDist * mBumps[j].mDecay;
float bumpAmt = mBumps[j].mAmt * (MIN(1, (tanh(dist) + 1) / 2)); // * ofRandom(1);
mAmp[i - 1] += bumpAmt;
}
if (mNegHarmonics > 0 && i % mNegHarmonics == 1)
mAmp[i - 1] *= -1;
if (mHarshnessCut > 0)
{
float cutPoint = gNyquistLimit - mHarshnessCut;
if (freq > cutPoint)
mAmp[i - 1] *= 1 - ((freq - cutPoint) / mHarshnessCut);
}
}
}
}
void Razor::SetEnabled(bool enabled)
{
mEnabled = enabled;
}
void Razor::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
SetEnabled(mEnabled);
if (checkbox == mManualControlCheckbox)
{
if (mManualControl)
mUseNumPartials = NUM_AMP_SLIDERS;
}
}
void Razor::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void Razor::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
if (slider == mNumPartialsSlider)
{
std::memset(mPhases, 0, sizeof(float) * NUM_PARTIALS);
}
}
void Razor::ButtonClicked(ClickButton* button, double time)
{
if (button == mResetDetuneButton)
{
for (int i = 0; i < NUM_PARTIALS; ++i)
mDetune[i] = 1;
}
}
void Razor::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void Razor::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
``` | /content/code_sandbox/Source/Razor.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 6,756 |
```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
**/
//
// PerformanceTimer.cpp
// Bespoke
//
// Created by Ryan Challinor on 3/26/15.
//
//
#include "PerformanceTimer.h"
#include "SynthGlobals.h"
TimerInstance::TimerInstance(std::string name, PerformanceTimer& manager)
: mName(name)
, mManager(manager)
{
mTimerStart = ofGetSystemTimeNanos();
}
TimerInstance::~TimerInstance()
{
mManager.RecordCost(mName, ofGetSystemTimeNanos() - mTimerStart);
}
void PerformanceTimer::RecordCost(std::string name, long cost)
{
mCostTable.push_back(PerformanceTimer::Cost(name, cost));
}
bool PerformanceTimer::SortCosts(const PerformanceTimer::Cost& a, const PerformanceTimer::Cost& b)
{
return a.mCost < b.mCost;
}
void PerformanceTimer::PrintCosts()
{
sort(mCostTable.begin(), mCostTable.end(), SortCosts);
for (Cost cost : mCostTable)
ofLog() << cost.mName << " " << ofToString(cost.mCost);
}
``` | /content/code_sandbox/Source/PerformanceTimer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 324 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Sampler.h
// modularSynth
//
// Created by Ryan Challinor on 2/5/14.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "PolyphonyMgr.h"
#include "SampleVoice.h"
#include "INoteReceiver.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "DropdownList.h"
#include "ADSRDisplay.h"
#include "Checkbox.h"
#include "PitchDetector.h"
class ofxJSONElement;
#define MAX_SAMPLER_LENGTH 2 * 48000
class Sampler : public IAudioProcessor, public INoteReceiver, public IDrawableModule, public IDropdownListener, public IFloatSliderListener, public IIntSliderListener
{
public:
Sampler();
~Sampler();
static IDrawableModule* Create() { return new Sampler(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Poll() override;
//IAudioProcessor
InputMode GetInputMode() override { return kInputMode_Mono; }
//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 FilesDropped(std::vector<std::string> files, int x, int y) override;
void SampleDropped(int x, int y, Sample* sample) override;
bool CanDropSample() const override { return true; }
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void 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 2; }
bool IsEnabled() const override { return mEnabled; }
private:
void StopRecording();
float DetectSampleFrequency();
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
PolyphonyMgr mPolyMgr;
NoteInputBuffer mNoteInputBuffer;
SampleVoiceParams mVoiceParams;
FloatSlider* mVolSlider{ nullptr };
ADSRDisplay* mADSRDisplay{ nullptr };
float mThresh{ .2 };
FloatSlider* mThreshSlider{ nullptr };
float* mSampleData{ nullptr };
int mRecordPos{ 0 };
bool mRecording{ false };
Checkbox* mRecordCheckbox{ nullptr };
bool mPitchCorrect{ false };
Checkbox* mPitchCorrectCheckbox{ nullptr };
bool mPassthrough{ false };
Checkbox* mPassthroughCheckbox{ nullptr };
ChannelBuffer mWriteBuffer;
PitchDetector mPitchDetector;
bool mWantDetectPitch{ false };
};
``` | /content/code_sandbox/Source/Sampler.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 835 |
```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
**/
//
// MultibandCompressor.h
// Bespoke
//
// Created by Ryan Challinor on 3/27/14.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "RollingBuffer.h"
#include "LinkwitzRileyFilter.h"
#include "PeakTracker.h"
#define COMPRESSOR_MAX_BANDS 10
class MultibandCompressor : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public IIntSliderListener
{
public:
MultibandCompressor();
virtual ~MultibandCompressor();
static IDrawableModule* Create() { return new MultibandCompressor(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IAudioReceiver
InputMode GetInputMode() override { return kInputMode_Mono; }
//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;
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 = 210;
h = 150;
}
void CalcFilters();
float* mWorkBuffer{ nullptr };
float* mOutBuffer{ nullptr };
float mDryWet{ 1 };
FloatSlider* mDryWetSlider{ nullptr };
IntSlider* mNumBandsSlider{ nullptr };
int mNumBands{ 4 };
float mFreqMin{ 150 };
float mFreqMax{ 7500 };
FloatSlider* mFMinSlider{ nullptr };
FloatSlider* mFMaxSlider{ nullptr };
float mRingTime{ .01 };
FloatSlider* mRingTimeSlider{ nullptr };
float mMaxBand{ .3 };
FloatSlider* mMaxBandSlider{ nullptr };
CLinkwitzRiley_4thOrder mFilters[COMPRESSOR_MAX_BANDS];
PeakTracker mPeaks[COMPRESSOR_MAX_BANDS];
};
``` | /content/code_sandbox/Source/MultibandCompressor.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 656 |
```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
**/
//
// Metronome.cpp
// modularSynth
//
// Created by Ryan Challinor on 3/16/13.
//
//
#include "Metronome.h"
#include "IAudioReceiver.h"
#include "ModularSynth.h"
#include "Profiler.h"
Metronome::Metronome()
{
}
void Metronome::Init()
{
IDrawableModule::Init();
mTransportListenerInfo = TheTransport->AddListener(this, kInterval_4n, OffsetInfo(0, true), false);
}
void Metronome::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mVolumeSlider = new FloatSlider(this, "vol", 5, 18, 70, 15, &mVolume, 0, 1);
}
Metronome::~Metronome()
{
TheTransport->RemoveListener(this);
}
void Metronome::Process(double time)
{
PROFILER(Metronome);
IAudioReceiver* target = GetTarget();
if (!mEnabled || target == nullptr)
return;
int bufferSize = target->GetBuffer()->BufferSize();
float* out = target->GetBuffer()->GetChannel(0);
assert(bufferSize == gBufferSize);
for (int i = 0; i < bufferSize; ++i)
{
float sample = mOsc.Audio(time, mPhase) * mVolume / 10;
out[i] += sample;
GetVizBuffer()->Write(sample, 0);
mPhase += mPhaseInc;
while (mPhase > FTWO_PI)
{
mPhase -= FTWO_PI;
}
time += gInvSampleRateMs;
}
}
void Metronome::OnTimeEvent(double time)
{
int step = TheTransport->GetQuantized(time, mTransportListenerInfo);
if (step == 0)
{
mPhaseInc = GetPhaseInc(880);
mOsc.Start(gTime, 1, 0, 100, 0, 0);
}
else if (step == 2)
{
mPhaseInc = GetPhaseInc(480);
mOsc.Start(gTime, 1, 0, 70, 0, 0);
}
else
{
mPhaseInc = GetPhaseInc(440);
mOsc.Start(gTime, .8f, 0, 50, 0, 0);
}
}
void Metronome::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mVolumeSlider->Draw();
}
void Metronome::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void Metronome::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
``` | /content/code_sandbox/Source/Metronome.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 721 |
```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.cpp
Created: 4 Feb 2020 12:17:59pm
Author: Ryan Challinor
==============================================================================
*/
#include "PulseChance.h"
#include "SynthGlobals.h"
#include "UIControlMacros.h"
#include "Transport.h"
PulseChance::PulseChance()
{
Reseed();
}
PulseChance::~PulseChance()
{
}
void PulseChance::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
FLOATSLIDER(mChanceSlider, "chance", &mChance, 0, 1);
CHECKBOX(mDeterministicCheckbox, "deterministic", &mDeterministic);
UIBLOCK_SHIFTY(5);
TEXTENTRY_NUM(mSeedEntry, "seed", 4, &mSeed, 0, 9999);
UIBLOCK_SHIFTRIGHT();
BUTTON(mPrevSeedButton, "<");
UIBLOCK_SHIFTRIGHT();
BUTTON(mReseedButton, "*");
UIBLOCK_SHIFTRIGHT();
BUTTON(mNextSeedButton, ">");
ENDUIBLOCK0();
mSeedEntry->DrawLabel(true);
mPrevSeedButton->PositionTo(mSeedEntry, kAnchor_Right);
mReseedButton->PositionTo(mPrevSeedButton, kAnchor_Right);
mNextSeedButton->PositionTo(mReseedButton, kAnchor_Right);
}
void PulseChance::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mChanceSlider->Draw();
mDeterministicCheckbox->Draw();
if (gTime - mLastAcceptTime > 0 && gTime - mLastAcceptTime < 200)
{
ofPushStyle();
ofSetColor(0, 255, 0, 255 * (1 - (gTime - mLastAcceptTime) / 200));
ofFill();
ofRect(106, 2, 10, 7);
ofPopStyle();
}
if (gTime - mLastRejectTime > 0 && gTime - mLastRejectTime < 200)
{
ofPushStyle();
ofSetColor(255, 0, 0, 255 * (1 - (gTime - mLastRejectTime) / 200));
ofFill();
ofRect(106, 9, 10, 7);
ofPopStyle();
}
mSeedEntry->SetShowing(mDeterministic);
mSeedEntry->Draw();
mPrevSeedButton->SetShowing(mDeterministic);
mPrevSeedButton->Draw();
mReseedButton->SetShowing(mDeterministic);
mReseedButton->Draw();
mNextSeedButton->SetShowing(mDeterministic);
mNextSeedButton->Draw();
}
void PulseChance::OnPulse(double time, float velocity, int flags)
{
ComputeSliders(0);
if (!mEnabled)
{
DispatchPulse(GetPatchCableSource(), time, velocity, flags);
return;
}
if (flags & kPulseFlag_Reset)
mRandomIndex = 0;
float random;
if (mDeterministic)
{
random = ((abs(DeterministicRandom(mSeed, mRandomIndex)) % 10000) / 10000.0f);
++mRandomIndex;
}
else
{
random = ofRandom(1);
}
bool accept = random <= mChance;
if (accept)
DispatchPulse(GetPatchCableSource(), time, velocity, flags);
if (accept)
mLastAcceptTime = gTime;
else
mLastRejectTime = gTime;
}
void PulseChance::Reseed()
{
mSeed = gRandom() % 10000;
}
void PulseChance::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 PulseChance::GetModuleDimensions(float& width, float& height)
{
width = 118;
height = mDeterministic ? 61 : 38;
}
void PulseChance::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void PulseChance::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/PulseChance.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,093 |
```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
**/
/*
==============================================================================
AudioToCV.h
Created: 18 Nov 2017 10:46:05pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "IModulator.h"
class PatchCableSource;
class AudioToCV : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public IModulator
{
public:
AudioToCV();
virtual ~AudioToCV();
static IDrawableModule* Create() { return new AudioToCV(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
bool ShouldSuppressAutomaticOutputCable() override { return true; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void Process(double time) override;
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
//IModulator
float Value(int samplesIn = 0) override;
bool Active() const override { return mEnabled; }
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void SaveLayout(ofxJSONElement& moduleInfo) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 1; }
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = 106;
h = 17 * 3 + 2;
}
float mGain{ 1 };
float* mModulationBuffer{ nullptr };
FloatSlider* mGainSlider{ nullptr };
};
``` | /content/code_sandbox/Source/AudioToCV.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 566 |
```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
**/
//
// NamedMutex.cpp
// modularSynth
//
// Created by Ryan Challinor on 1/20/14.
//
//
#include "NamedMutex.h"
void NamedMutex::Lock(std::string locker)
{
if (mLocker == locker)
{
++mExtraLockCount;
return;
}
mMutex.lock();
mLocker = locker;
}
void NamedMutex::Unlock()
{
if (mExtraLockCount == 0)
{
mLocker = "<none>";
mMutex.unlock();
}
else
{
--mExtraLockCount;
}
}
ScopedMutex::ScopedMutex(NamedMutex* mutex, std::string locker)
: mMutex(mutex)
{
mMutex->Lock(locker);
}
ScopedMutex::~ScopedMutex()
{
mMutex->Unlock();
}
``` | /content/code_sandbox/Source/NamedMutex.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 271 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// FFTtoAdditive.h
// modularSynth
//
// Created by Ryan Challinor on 4/24/13.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "FFT.h"
#include "RollingBuffer.h"
#include "Slider.h"
#include "BiquadFilterEffect.h"
#define VIZ_WIDTH 1000
#define RAZOR_HISTORY 100
class FFTtoAdditive : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener
{
public:
FFTtoAdditive();
virtual ~FFTtoAdditive();
static IDrawableModule* Create() { return new FFTtoAdditive(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IAudioReceiver
InputMode GetInputMode() override { return kInputMode_Mono; }
//IAudioSource
void Process(double time) override;
//IButtonListener
void CheckboxUpdated(Checkbox* checkbox, double time) override;
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
void DrawViz();
float SinSample(float phase);
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = 235;
h = 170;
}
FFTData mFFTData;
float* mWindower{ nullptr };
::FFT mFFT;
RollingBuffer mRollingInputBuffer;
RollingBuffer mRollingOutputBuffer;
float mInputPreamp{ 1 };
float mValue1{ 1 };
float mVolume{ 1 };
FloatSlider* mInputSlider{ nullptr };
FloatSlider* mValue1Slider{ nullptr };
FloatSlider* mVolumeSlider{ nullptr };
float mDryWet{ 1 };
FloatSlider* mDryWetSlider{ nullptr };
float mValue2{ 1 };
FloatSlider* mValue2Slider{ nullptr };
float mValue3{ 0 };
FloatSlider* mValue3Slider{ nullptr };
float mPhaseOffset{ 0 };
FloatSlider* mPhaseOffsetSlider{ nullptr };
float mPeakHistory[RAZOR_HISTORY][VIZ_WIDTH + 1]{};
int mHistoryPtr{ 0 };
float* mPhaseInc{ nullptr };
};
``` | /content/code_sandbox/Source/FFTtoAdditive.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 696 |
```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
**/
//
// VelocitySetter.h
// modularSynth
//
// Created by Ryan Challinor on 5/16/13.
//
//
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Slider.h"
class VelocitySetter : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener
{
public:
VelocitySetter();
static IDrawableModule* Create() { return new VelocitySetter(); }
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 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 = 90;
height = 38;
}
float mVelocity{ 1 };
FloatSlider* mVelocitySlider{ nullptr };
float mRandomness{ 0 };
FloatSlider* mRandomnessSlider{ nullptr };
};
``` | /content/code_sandbox/Source/VelocitySetter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 453 |
```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
**/
//
// VelocityCurve.h
// Bespoke
//
// Created by Ryan Challinor on 4/17/22.
//
//
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "INoteSource.h"
#include "EnvelopeEditor.h"
class VelocityCurve : public NoteEffectBase, public IDrawableModule
{
public:
VelocityCurve();
static IDrawableModule* Create() { return new VelocityCurve(); }
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 MouseReleased() override;
bool MouseMoved(float x, float y) 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 1; }
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = 106;
h = 105;
}
void OnClicked(float x, float y, bool right) override;
EnvelopeControl mEnvelopeControl{ ofVec2f{ 3, 3 }, ofVec2f{ 100, 100 } };
::ADSR mAdsr;
float mLastInputVelocity{ 0 };
double mLastInputTime{ -9999 };
};
``` | /content/code_sandbox/Source/VelocityCurve.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 515 |
```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
**/
//
// Scale.cpp
// modularSynth
//
// Created by Ryan Challinor on 11/24/12.
//
//
#include "Scale.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "ofxJSONElement.h"
#include "Tunings.h"
#include "libMTSClient.h"
#include "juce_gui_basics/juce_gui_basics.h"
Scale* TheScale = nullptr;
namespace
{
std::string kChromaticScale = "chromatic";
}
Scale::Scale()
{
assert(TheScale == nullptr);
TheScale = this;
SetName("scale");
}
Scale::~Scale()
{
if (mOddsoundMTSClient)
{
MTS_DeregisterClient(mOddsoundMTSClient);
mOddsoundMTSClient = nullptr;
}
}
void Scale::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mRootSelector = new DropdownList(this, "root", 4, 5, &mScale.mScaleRoot);
mScaleSelector = new DropdownList(this, "scale", 58, 5, &mScaleIndex);
mScaleDegreeSlider = new IntSlider(this, "degree", HIDDEN_UICONTROL, HIDDEN_UICONTROL, 115, 15, &mScaleDegree, -7, 7);
mIntonationSelector = new DropdownList(this, "intonation", 58, 24, (int*)(&mIntonation));
mPitchesPerOctaveEntry = new TextEntry(this, "PPO", 4, 24, 2, &mPitchesPerOctave, 1, 99);
mReferenceFreqEntry = new TextEntry(this, "tuning", 4, 43, 3, &mReferenceFreq, 1, 999);
mReferencePitchEntry = new TextEntry(this, "note", 76, 43, 3, &mReferencePitch, 0, 127);
mLoadSCLButton = new ClickButton(this, "load SCL", 4, 62);
mLoadKBMButton = new ClickButton(this, "load KBM", 74, 62);
mPitchesPerOctaveEntry->DrawLabel(true);
mReferenceFreqEntry->DrawLabel(true);
mReferencePitchEntry->DrawLabel(true);
SetUpRootList();
mIntonationSelector->AddLabel("equal", kIntonation_Equal);
mIntonationSelector->AddLabel("ratio", kIntonation_Rational);
mIntonationSelector->AddLabel("just", kIntonation_Just);
mIntonationSelector->AddLabel("pyth", kIntonation_Pythagorean);
mIntonationSelector->AddLabel("mean", kIntonation_Meantone);
mIntonationSelector->AddLabel("scl/kbm", kIntonation_SclFile);
mIntonationSelector->AddLabel("oddsound", kIntonation_Oddsound);
}
void Scale::SetUpRootList()
{
mRootSelector->Clear();
if (mPitchesPerOctave == 12)
{
mRootSelector->AddLabel("A", 9);
mRootSelector->AddLabel("A#/Bb", 10);
mRootSelector->AddLabel("B", 11);
mRootSelector->AddLabel("C", 0);
mRootSelector->AddLabel("C#/Db", 1);
mRootSelector->AddLabel("D", 2);
mRootSelector->AddLabel("D#/Eb", 3);
mRootSelector->AddLabel("E", 4);
mRootSelector->AddLabel("F", 5);
mRootSelector->AddLabel("F#/Gb", 6);
mRootSelector->AddLabel("G", 7);
mRootSelector->AddLabel("G#/Ab", 8);
}
else
{
for (int i = 0; i < mPitchesPerOctave; ++i)
mRootSelector->AddLabel(ofToString(i), i);
if (mScale.mScaleRoot >= mPitchesPerOctave)
SetRoot(0);
}
}
void Scale::Init()
{
IDrawableModule::Init();
ofxJSONElement root;
root.open(ofToDataPath("scales.json"));
Json::Value& scales = root["scales"];
mScales.push_back(ScaleInfo(kChromaticScale, std::vector<int>{})); //this list is intentionally empty: 0 pitches means "chromatic"
mScaleSelector->AddLabel(kChromaticScale, 0);
for (int i = 0; i < scales.size(); ++i)
{
try
{
Json::Value& scale = scales[i];
ScaleInfo scaleInfo;
scaleInfo.mName = scale.begin().key().asString();
if (scaleInfo.mName == kChromaticScale) //this is a reserved word now
continue;
Json::Value& pitches = scale[scaleInfo.mName];
for (int j = 0; j < pitches.size(); ++j)
{
int pitch = pitches[j].asInt();
scaleInfo.mPitches.push_back(pitch);
}
mScales.push_back(scaleInfo);
mScaleSelector->AddLabel(scaleInfo.mName.c_str(), mScaleSelector->GetNumValues());
if (scaleInfo.mPitches.size() == 7)
{
++mNumSeptatonicScales;
assert(mNumSeptatonicScales == i + 1); //make sure septatonic scales come first (after initial chromatic scale)
}
}
catch (Json::LogicError& e)
{
TheSynth->LogEvent(__PRETTY_FUNCTION__ + std::string(" json error: ") + e.what(), kLogEventType_Error);
}
}
if (mNumSeptatonicScales == 0) //dumb-but-acceptable handling of an assumption
{
mScales.clear();
mScales.push_back(ScaleInfo(kChromaticScale, std::vector<int>{})); //this list is intentionally empty: 0 pitches means "chromatic"
mScaleSelector->AddLabel(kChromaticScale, 0);
mScales.push_back(ScaleInfo("ionian", std::vector<int>{ 0, 2, 4, 5, 7, 9, 11 }));
mScaleSelector->AddLabel("ionian", 1);
mNumSeptatonicScales = 1;
}
SetRandomRootAndScale();
}
float Scale::PitchToFreq(float pitch)
{
if (mIntonation == kIntonation_SclFile)
{
auto ip = (int)pitch + 128;
if (ip < 0 || ip > 256)
return 440;
// Interpolate in log space
auto lt = mTuningTable[ip];
auto nt = mTuningTable[ip + ((ip != 255) ? 1 : 0)];
auto fp = (pitch + 128) - ip;
auto interplt = (1 - fp) * lt + fp * nt;
// Then pow2 it and multiply by freq0
return Pow2(interplt) * Tunings::MIDI_0_FREQ;
}
if (mIntonation == kIntonation_Oddsound)
{
if (mOddsoundMTSClient && MTS_HasMaster(mOddsoundMTSClient))
{
if (pitch < 0 || pitch > 127)
return Pow2((pitch - mReferencePitch) / mPitchesPerOctave) * mReferenceFreq; // Improve this obviously
else
return MTS_NoteToFrequency(mOddsoundMTSClient, (int)pitch, 0);
}
else
{
return Pow2((pitch - mReferencePitch) / mPitchesPerOctave) * mReferenceFreq;
}
}
switch (mIntonation)
{
case kIntonation_Equal:
return Pow2((pitch - mReferencePitch) / mPitchesPerOctave) * mReferenceFreq;
/*case kIntonation_Rational:
{
int referencePitch = ScaleRoot();
do
{
referencePitch += mPitchesPerOctave;
}while (referencePitch < mReferencePitch && abs(referencePitch - mReferencePitch) > mPitchesPerOctave);
float referenceFreq = Pow2((referencePitch-mReferencePitch)/mPitchesPerOctave)*mReferenceFreq;
int intPitch = (int)pitch;
float remainder = pitch - intPitch;
float ratio1 = RationalizeNumber(Pow2(float(intPitch-referencePitch)/mPitchesPerOctave));
float ratio2 = RationalizeNumber(Pow2(float((intPitch+1)-referencePitch)/mPitchesPerOctave));
return ofLerp(ratio1,ratio2,remainder)*referenceFreq;
}*/
case kIntonation_Pythagorean:
case kIntonation_Just:
case kIntonation_Rational:
case kIntonation_Meantone:
{
int referencePitch = ScaleRoot();
do
{
referencePitch += mPitchesPerOctave;
} while (referencePitch < mReferencePitch && abs(referencePitch - mReferencePitch) > mPitchesPerOctave);
float referenceFreq = Pow2((referencePitch - mReferencePitch) / mPitchesPerOctave) * mReferenceFreq;
int intPitch = (int)pitch;
float remainder = pitch - intPitch;
float ratio1 = GetTuningTableRatio(intPitch - referencePitch);
float ratio2 = GetTuningTableRatio((intPitch + 1) - referencePitch);
float freq = MAX(ofLerp(ratio1, ratio2, remainder), .001f) * referenceFreq;
return freq;
break;
}
default:
assert(false);
}
assert(false);
return 0;
}
float Scale::FreqToPitch(float freq)
{
//TODO(Ryan) always use equal for now
//switch (mIntonation)
//{
// case kIntonation_Equal:
return mReferencePitch + mPitchesPerOctave * log2(freq / mReferenceFreq);
// default:
// assert(false);
//}
//assert(false);
//return 0;
}
int Scale::MakeDiatonic(int pitch)
{
if (mScale.GetPitches().empty()) //empty list means "chromatic"
return pitch;
assert(mScale.mScaleRoot >= 0 && mScale.mScaleRoot < mPitchesPerOctave);
int pitchOut = (pitch - mScale.mScaleRoot) % mPitchesPerOctave; //transform into 0-12 scale space
for (int i = (int)mScale.GetPitches().size() - 1; i >= 0; --i)
{
if (mScale.GetScalePitch(i) <= pitchOut)
{
pitchOut = mScale.GetScalePitch(i);
break;
}
}
pitchOut += mPitchesPerOctave * ((pitch - mScale.mScaleRoot) / mPitchesPerOctave) + mScale.mScaleRoot; //transform back
return pitchOut;
}
void Scale::GetChordDegreeAndAccidentals(const Chord& chord, int& degree, std::vector<Accidental>& accidentals)
{
mScale.GetChordDegreeAndAccidentals(chord, degree, accidentals);
}
int Scale::GetPitchFromTone(int n)
{
return mScale.GetPitchFromTone(n);
}
int Scale::GetToneFromPitch(int pitch)
{
return mScale.GetToneFromPitch(pitch);
}
void Scale::SetScale(int root, std::string type)
{
SetRoot(root);
SetScaleType(type);
}
void Scale::SetRoot(int root, bool force)
{
if (root == mScale.mScaleRoot && !force)
return;
mScale.SetRoot(root);
NotifyListeners();
}
void Scale::SetScaleType(std::string type, bool force)
{
int oldScaleIndex = mScaleIndex;
for (int i = 0; i < mScales.size(); ++i)
{
if (mScales[i].mName == type)
{
mScaleIndex = i;
break;
}
}
if (mScaleIndex == oldScaleIndex && !force)
return;
mScale.SetScaleType(type);
NotifyListeners();
}
void Scale::SetRandomRootAndScale()
{
SetRoot(gRandom() % TheScale->GetPitchesPerOctave());
SetRandomSeptatonicScale();
}
void Scale::SetRandomSeptatonicScale()
{
mScaleIndex = gRandom() % mNumSeptatonicScales + 1;
mScale.SetScaleType(mScales[mScaleIndex].mName);
}
void Scale::SetAccidentals(const std::vector<Accidental>& accidentals)
{
if (accidentals == mScale.mAccidentals)
return;
mScale.SetAccidentals(accidentals);
NotifyListeners();
}
bool Scale::IsRoot(int pitch)
{
return mScale.IsRoot(pitch);
}
bool Scale::IsInPentatonic(int pitch)
{
return mScale.IsInPentatonic(pitch);
}
bool Scale::IsInScale(int pitch)
{
return mScale.IsInScale(pitch);
}
void Scale::AddListener(IScaleListener* listener)
{
mListeners.push_back(listener);
}
void Scale::RemoveListener(IScaleListener* listener)
{
mListeners.remove(listener);
}
void Scale::ClearListeners()
{
mListeners.clear();
}
void Scale::NotifyListeners()
{
for (std::list<IScaleListener*>::iterator i = mListeners.begin(); i != mListeners.end(); ++i)
{
(*i)->OnScaleChanged();
}
}
void Scale::SetScaleDegree(int degree)
{
if (degree == mScaleDegree)
return;
mScaleDegree = degree;
NotifyListeners();
}
void Scale::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mPitchesPerOctaveEntry->SetShowing(mIntonation != kIntonation_SclFile && mIntonation != kIntonation_Oddsound);
mReferenceFreqEntry->SetShowing(mIntonation != kIntonation_Oddsound && (mIntonation != kIntonation_SclFile || mKbmContents.empty()));
mReferencePitchEntry->SetShowing(mIntonation != kIntonation_Oddsound && (mIntonation != kIntonation_SclFile || mKbmContents.empty()));
mLoadSCLButton->SetShowing(mIntonation == kIntonation_SclFile && mIntonation != kIntonation_Oddsound);
mLoadKBMButton->SetShowing(mIntonation == kIntonation_SclFile && mIntonation != kIntonation_Oddsound);
mRootSelector->Draw();
mScaleSelector->Draw();
mPitchesPerOctaveEntry->Draw();
mReferenceFreqEntry->Draw();
mReferencePitchEntry->Draw();
mIntonationSelector->Draw();
mLoadSCLButton->Draw();
mLoadKBMButton->Draw();
if (mIntonation == kIntonation_SclFile)
{
DrawTextNormal("PPO: " + ofToString(mPitchesPerOctave), 5, 36);
DrawTextNormal(mCustomScaleDescription, 5, 91);
}
if (mIntonation == kIntonation_Oddsound)
{
DrawTextNormal("PPO: " + ofToString(mPitchesPerOctave), 5, 36);
DrawTextNormal(mCustomScaleDescription, 5, 45);
}
}
void Scale::GetModuleDimensions(float& width, float& height)
{
width = 164;
height = mIntonation == kIntonation_SclFile ? 109 : 62;
}
std::vector<int> Scale::GetPitchesForScale(std::string scaleType)
{
for (int i = 0; i < mScales.size(); ++i)
{
if (mScales[i].mName == scaleType)
return mScales[i].mPitches;
}
assert(false);
return std::vector<int>();
}
void Scale::Poll()
{
ComputeSliders(0);
if (mWantSetRandomRootAndScale)
{
SetRandomRootAndScale();
mWantSetRandomRootAndScale = false;
}
if (mQueuedButtonPress)
{
ClickButton* button = mQueuedButtonPress;
mQueuedButtonPress = nullptr;
if (button == mLoadSCLButton || button == mLoadKBMButton)
{
std::string prompt = "Load ";
prompt += (button == mLoadSCLButton) ? "SCL" : "KBM";
std::string pat = (button == mLoadSCLButton) ? "*.scl;*.SCL" : "*.kbm;*.KBM";
juce::FileChooser chooser(prompt, juce::File(""), pat, true, false, TheSynth->GetFileChooserParent());
if (chooser.browseForFileToOpen())
{
auto file = chooser.getResult();
std::cout << file.getFullPathName().toStdString() << std::endl;
if (button == mLoadSCLButton)
{
mSclContents = file.loadFileAsString().toStdString();
}
else
{
mKbmContents = file.loadFileAsString().toStdString();
}
UpdateTuningTable();
}
}
}
}
float Scale::RationalizeNumber(float input)
{
int m[2][2];
float x = input;
int maxden = 32;
int ai;
/* initialize matrix */
m[0][0] = m[1][1] = 1;
m[0][1] = m[1][0] = 0;
/* loop finding terms until denom gets too big */
while (m[1][0] * (ai = (int)x) + m[1][1] <= maxden)
{
int t;
t = m[0][0] * ai + m[0][1];
m[0][1] = m[0][0];
m[0][0] = t;
t = m[1][0] * ai + m[1][1];
m[1][1] = m[1][0];
m[1][0] = t;
if (x == (float)ai)
break; // AF: division by zero
x = 1 / (x - (float)ai);
if (x > (float)0x7FFFFFFF)
break; // AF: representation failure
}
int numerator = m[0][0];
int denominator = m[1][0];
if (m[1][0] == 0) //avoid div by zero
return input;
ai = (maxden - m[1][1]) / m[1][0];
int otherNumerator = m[0][0] * ai + m[0][1];
int otherDenominator = m[1][0] * ai + m[1][1];
if (otherDenominator < denominator)
{
numerator = otherNumerator;
denominator = otherDenominator;
// printf("*");
}
if (denominator == 0) //avoid div by zero
return input;
float output = float(numerator) / denominator;
//printf("input: %f, output: %f, %d/%d, error = %e\n", input, output, numerator, denominator, input - output);
return output;
}
void Scale::UpdateTuningTable()
{
if (mIntonation == kIntonation_Oddsound)
{
//TODO(Ryan): should be smarter about making scale choices based on incoming pitches-per-octave from oddsound
SetScaleType(kChromaticScale);
if (mOddsoundMTSClient == nullptr)
{
ofLog() << "Connecting to oddsound mts";
mOddsoundMTSClient = MTS_RegisterClient();
mCustomScaleDescription = "connected to oddsound";
}
if (mOddsoundMTSClient == nullptr)
{
mIntonation = kIntonation_Equal;
mCustomScaleDescription = "connection to oddsound failed";
}
}
else if (mIntonation == kIntonation_SclFile)
{
try
{
Tunings::Scale scale;
Tunings::KeyboardMapping mapping;
if (mSclContents.empty())
scale = Tunings::evenTemperament12NoteScale();
else
scale = Tunings::parseSCLData(mSclContents);
if (scale.count != 12)
SetScaleType(kChromaticScale);
if (mPitchesPerOctave != scale.count)
{
mPitchesPerOctave = scale.count;
SetUpRootList();
NotifyListeners();
}
if (mKbmContents.empty())
mapping = Tunings::startScaleOnAndTuneNoteTo(60, (int)mReferencePitch, mReferenceFreq);
else
mapping = Tunings::parseKBMData(mKbmContents);
auto tuning = Tunings::Tuning(scale, mapping);
for (int i = 0; i < 256; ++i)
{
mTuningTable[i] = tuning.logScaledFrequencyForMidiNote(i - 128);
}
mCustomScaleDescription = "scale: " + scale.description + "\nmapping: " + mapping.rawText;
}
catch (const Tunings::TuningError& e)
{
mSclContents.clear();
mKbmContents.clear();
mIntonation = kIntonation_Equal;
mPitchesPerOctave = 12;
ofLog() << e.what();
}
}
else if (mIntonation == kIntonation_Equal)
{
//no table
}
else if (mIntonation == kIntonation_Rational)
{
for (int i = 0; i < 256; ++i)
mTuningTable[i] = RationalizeNumber(Pow2(float(i - 128) / mPitchesPerOctave));
}
else if (mIntonation == kIntonation_Pythagorean ||
mIntonation == kIntonation_Just ||
mIntonation == kIntonation_Meantone)
{
if (mPitchesPerOctave != 12)
{
mPitchesPerOctave = 12; //only 12-PPO supported for these
SetUpRootList();
NotifyListeners();
}
float tunings[12];
if (mIntonation == kIntonation_Pythagorean)
{
tunings[0] = 1;
tunings[1] = 256.0f / 243.0f;
tunings[2] = 9.0f / 8.0f;
tunings[3] = 32.0f / 27.0f;
tunings[4] = 81.0f / 64.0f;
tunings[5] = 4.0f / 3.0f;
tunings[6] = 729.f / 512.f;
tunings[7] = 3.0f / 2.0f;
tunings[8] = 128.0f / 81.0f;
tunings[9] = 27.0f / 16.0f;
tunings[10] = 16.0f / 9.0f;
tunings[11] = 243.0f / 128.0f;
}
if (mIntonation == kIntonation_Just)
{
tunings[0] = 1;
tunings[1] = 25.0f / 24.0f;
tunings[2] = 9.0f / 8.0f;
tunings[3] = 6.0f / 5.0f;
tunings[4] = 5.0f / 4.0f;
tunings[5] = 4.0f / 3.0f;
tunings[6] = 45.0f / 32.0f;
tunings[7] = 3.0f / 2.0f;
tunings[8] = 8.0f / 5.0f;
tunings[9] = 5.0f / 3.0f;
tunings[10] = 9.0f / 5.0f;
tunings[11] = 15.0f / 8.0f;
}
if (mIntonation == kIntonation_Meantone)
{
float fifth = pow(5, .25f);
float rootFive = sqrtf(5);
tunings[0] = 1;
tunings[1] = 8 * fifth * rootFive / 25;
tunings[2] = rootFive / 2;
tunings[3] = 4 * fifth / 5;
tunings[4] = 5.0f / 4.0f;
tunings[5] = 2 * rootFive * fifth / 5;
tunings[6] = 16 * rootFive / 25;
tunings[7] = fifth;
tunings[8] = 8.0f / 5.0f;
tunings[9] = rootFive * fifth / 2;
tunings[10] = 4 * rootFive / 5;
tunings[11] = 5 * fifth / 4;
}
for (int i = 0; i < 256; ++i)
{
int octave = floor((i - 128) / 12.0f);
float ratio = powf(2, octave);
mTuningTable[i] = tunings[(i - 128 + 144) % 12] * ratio; //+144 to keep modulo arithmetic positive
}
/*
* At this point we need to make sure the tuning table matches the reference pitch
*/
auto idx = (int)mReferencePitch + 128;
if (idx >= 0 && idx < 256)
{
auto ttRP = mTuningTable[idx];
auto lf = mReferenceFreq / Tunings::MIDI_0_FREQ;
auto ratio = lf / ttRP;
for (int i = 0; i < 256; ++i)
mTuningTable[i] *= ratio;
}
}
}
float Scale::GetTuningTableRatio(int semitonesFromCenter)
{
return mTuningTable[CLAMP(128 + semitonesFromCenter, 0, 255)];
}
void Scale::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mRootSelector)
SetRoot(mScale.mScaleRoot, true);
if (list == mScaleSelector)
SetScaleType(list->GetLabel(mScaleIndex), true);
if (list == mIntonationSelector)
UpdateTuningTable();
}
void Scale::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void Scale::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void Scale::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void Scale::TextEntryComplete(TextEntry* entry)
{
if (entry == mPitchesPerOctaveEntry)
{
UpdateTuningTable();
SetUpRootList();
NotifyListeners();
}
if (entry == mReferenceFreqEntry || entry == mReferencePitchEntry)
UpdateTuningTable();
}
void Scale::ButtonClicked(ClickButton* button, double time)
{
mQueuedButtonPress = button;
}
void Scale::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadBool("randomize_scale_on_load", moduleInfo, false);
SetUpFromSaveData();
}
void Scale::SetUpFromSaveData()
{
if (mModuleSaveData.GetBool("randomize_scale_on_load"))
mWantSetRandomRootAndScale = true;
}
void Scale::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out << mIntonation;
out << mSclContents;
out << mKbmContents;
}
void Scale::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());
int inton;
in >> inton;
mIntonation = (Scale::IntonationMode)inton;
in >> mSclContents;
in >> mKbmContents;
if (!(mSclContents.empty() && mKbmContents.empty()))
{
ofLog() << "Restoring SCL/KBM from streaming";
UpdateTuningTable();
}
}
void ScalePitches::SetRoot(int root)
{
assert(root >= 0);
mScaleRoot = root % TheScale->GetPitchesPerOctave();
}
void ScalePitches::SetScaleType(std::string type)
{
mScaleType = type;
int newFlip = (mScalePitchesFlip == 0) ? 1 : 0;
mScalePitches[newFlip] = TheScale->GetPitchesForScale(type);
mScalePitchesFlip = newFlip;
}
void ScalePitches::SetAccidentals(const std::vector<Accidental>& accidentals)
{
mAccidentals = accidentals;
}
void ScalePitches::GetChordDegreeAndAccidentals(const Chord& chord, int& degree, std::vector<Accidental>& accidentals) const
{
int pitch = chord.mRootPitch;
ChordType type = chord.mType;
//assert(IsInScale(pitch)); //don't support nondiatonic roots yet until I find an example
degree = GetToneFromPitch(pitch);
std::vector<int> chordForm;
if (type == kChord_Maj)
{
chordForm.push_back(0);
chordForm.push_back(4);
chordForm.push_back(7);
}
if (type == kChord_Min)
{
chordForm.push_back(0);
chordForm.push_back(3);
chordForm.push_back(7);
}
if (type == kChord_Aug)
{
chordForm.push_back(0);
chordForm.push_back(4);
chordForm.push_back(8);
}
if (type == kChord_Dim)
{
chordForm.push_back(0);
chordForm.push_back(3);
chordForm.push_back(6);
}
for (int i = 0; i < chordForm.size(); ++i)
{
int chordPitch = (chordForm[i] + pitch - mScaleRoot + TheScale->GetPitchesPerOctave()) % TheScale->GetPitchesPerOctave();
if (!VectorContains(chordPitch, mScalePitches[mScalePitchesFlip]))
{
if (type == kChord_Maj || type == kChord_Aug)
{
if (VectorContains(chordPitch - 1, mScalePitches[mScalePitchesFlip]))
accidentals.push_back(Accidental(chordPitch - 1, 1)); //sharpen
else if (VectorContains(chordPitch + 1, mScalePitches[mScalePitchesFlip]))
accidentals.push_back(Accidental(chordPitch + 1, -1)); //flatten
}
else if (type == kChord_Min || type == kChord_Dim)
{
if (VectorContains(chordPitch + 1, mScalePitches[mScalePitchesFlip]))
accidentals.push_back(Accidental(chordPitch + 1, -1)); //flatten
else if (VectorContains(chordPitch - 1, mScalePitches[mScalePitchesFlip]))
accidentals.push_back(Accidental(chordPitch - 1, 1)); //sharpen
}
else
{
assert(false);
}
}
}
}
int ScalePitches::NumTonesInScale() const
{
int numTones = (int)mScalePitches[mScalePitchesFlip].size();
if (numTones == 0)
numTones = TheScale->GetPitchesPerOctave();
return numTones;
}
int ScalePitches::GetScalePitch(int index) const
{
if (mScalePitches[mScalePitchesFlip].empty())
return index;
assert(index >= 0 && index < mScalePitches[mScalePitchesFlip].size());
int pitch = mScalePitches[mScalePitchesFlip][index];
for (int i = 0; i < mAccidentals.size(); ++i)
{
if (mAccidentals[i].mPitch == pitch)
pitch += mAccidentals[i].mDirection;
}
return pitch;
}
bool ScalePitches::IsRoot(int pitch) const
{
pitch -= mScaleRoot;
pitch += TheScale->GetPitchesPerOctave();
assert(pitch >= 0);
pitch %= TheScale->GetPitchesPerOctave();
return pitch == GetScalePitch(0);
}
bool ScalePitches::IsInPentatonic(int pitch) const
{
if (!IsInScale(pitch))
return false;
pitch -= mScaleRoot;
pitch += TheScale->GetPitchesPerOctave();
assert(pitch >= 0);
pitch %= TheScale->GetPitchesPerOctave();
bool isMinor = IsInScale(mScaleRoot + 3);
if (isMinor)
return pitch == 0 || pitch == 3 || pitch == 5 || pitch == 7 || pitch == 10;
else
return pitch == 0 || pitch == 2 || pitch == 4 || pitch == 7 || pitch == 9;
}
bool ScalePitches::IsInScale(int pitch) const
{
if (mScalePitches[mScalePitchesFlip].empty())
return true;
pitch -= mScaleRoot;
pitch += TheScale->GetPitchesPerOctave();
if (pitch < 0)
return false;
pitch %= TheScale->GetPitchesPerOctave();
for (int i = 0; i < mScalePitches[mScalePitchesFlip].size(); ++i)
{
if (pitch == GetScalePitch(i))
return true;
}
return false;
}
int ScalePitches::GetPitchFromTone(int n) const
{
int numTones = NumTonesInScale();
int octave = n / numTones;
while (n < 0)
{
n += numTones;
--octave;
}
int degree = n % numTones;
return GetScalePitch(degree) + TheScale->GetPitchesPerOctave() * octave + mScaleRoot;
}
int ScalePitches::GetToneFromPitch(int pitch) const
{
if (mScalePitches[mScalePitchesFlip].empty()) //empty list means "chromatic"
return pitch;
assert(mScaleRoot >= 0 && mScaleRoot < TheScale->GetPitchesPerOctave());
int numTones = (int)mScalePitches[mScalePitchesFlip].size();
int rootRel = pitch - mScaleRoot;
while (rootRel < 0)
rootRel += TheScale->GetPitchesPerOctave();
int tone = 0;
for (int i = 0; i < 999; ++i)
{
tone = i;
int octave = i / numTones;
if (GetScalePitch(i % numTones) + octave * TheScale->GetPitchesPerOctave() >= rootRel)
break;
}
return tone;
}
``` | /content/code_sandbox/Source/Scale.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 8,128 |
```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
**/
//
// Granulator.h
// modularSynth
//
// Created by Ryan Challinor on 9/12/13.
//
//
#pragma once
#include "BiquadFilter.h"
#include "ChannelBuffer.h"
#define MAX_GRAINS 32
class Granulator;
class Grain
{
public:
void Spawn(Granulator* owner, double time, double pos, float speedMult, float lengthInMs, float vol, float width);
void Process(double time, ChannelBuffer* buffer, int bufferLength, float* output);
void DrawGrain(int idx, float x, float y, float w, float h, int bufferStart, int viewLength, int bufferLength);
void Clear() { mVol = 0; }
private:
double GetWindow(double time);
double mPos{ 0 };
float mSpeedMult{ 1 };
double mStartTime{ 0 };
double mEndTime{ 1 };
double mStartToEnd{ 1 }, mStartToEndInv{ 1 };
float mVol{ 0 };
float mStereoPosition{ 0 };
float mDrawPos{ .5 };
Granulator* mOwner{ nullptr };
};
class Granulator
{
public:
Granulator();
void ProcessFrame(double time, ChannelBuffer* buffer, int bufferLength, double offset, float* output);
void Draw(float x, float y, float w, float h, int bufferStart, int viewLength, int bufferLength);
void Reset();
void ClearGrains();
void SetLiveMode(bool live) { mLiveMode = live; }
float mSpeed{ 1 };
float mGrainLengthMs{ 60 };
float mGrainOverlap{ 10 };
float mPosRandomizeMs{ 5 };
float mSpeedRandomize{ 0 };
float mSpacingRandomize{ 1 };
bool mOctaves{ false };
float mWidth{ 1 };
private:
void SpawnGrain(double time, double offset, float width);
double mNextGrainSpawnMs{ 0 };
int mNextGrainIdx{ 0 };
Grain mGrains[MAX_GRAINS]{};
bool mLiveMode{ false };
BiquadFilter mBiquad[ChannelBuffer::kMaxNumChannels]{};
};
``` | /content/code_sandbox/Source/Granulator.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 589 |
```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
**/
//
// Sampler.cpp
// modularSynth
//
// Created by Ryan Challinor on 2/5/14.
//
//
#include "Sampler.h"
#include "OpenFrameworksPort.h"
#include "SynthGlobals.h"
#include "IAudioReceiver.h"
#include "ofxJSONElement.h"
#include "ModularSynth.h"
#include "Sample.h"
#include "Profiler.h"
#include "Scale.h"
Sampler::Sampler()
: IAudioProcessor(gBufferSize)
, mPolyMgr(this)
, mNoteInputBuffer(this)
, mWriteBuffer(gBufferSize)
{
mSampleData = new float[MAX_SAMPLER_LENGTH]; //store up to 2 seconds
Clear(mSampleData, MAX_SAMPLER_LENGTH);
mVoiceParams.mVol = .5f;
mVoiceParams.mAdsr.Set(10, 0, 1, 10);
mVoiceParams.mSampleData = mSampleData;
mVoiceParams.mSampleLength = 0;
mVoiceParams.mDetectedFreq = -1;
mVoiceParams.mLoop = false;
mPolyMgr.Init(kVoiceType_Sampler, &mVoiceParams);
//mWriteBuffer.SetNumActiveChannels(2);
}
void Sampler::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mVolSlider = new FloatSlider(this, "vol", 5, 73, 80, 15, &mVoiceParams.mVol, 0, 1);
mADSRDisplay = new ADSRDisplay(this, "env", 5, 15, 80, 40, &mVoiceParams.mAdsr);
mRecordCheckbox = new Checkbox(this, "rec", 5, 57, &mRecording);
mThreshSlider = new FloatSlider(this, "thresh", 90, 73, 80, 15, &mThresh, 0, 1);
mPitchCorrectCheckbox = new Checkbox(this, "pitch", 60, 57, &mPitchCorrect);
mPassthroughCheckbox = new Checkbox(this, "passthrough", 70, 0, &mPassthrough);
mADSRDisplay->SetVol(mVoiceParams.mVol);
}
Sampler::~Sampler()
{
delete[] mSampleData;
}
void Sampler::Poll()
{
if (mWantDetectPitch)
{
mVoiceParams.mDetectedFreq = DetectSampleFrequency();
mWantDetectPitch = false;
}
}
void Sampler::Process(double time)
{
PROFILER(Sampler);
IAudioReceiver* target = GetTarget();
if (!mEnabled || target == nullptr)
return;
mNoteInputBuffer.Process(time);
ComputeSliders(0);
SyncBuffers();
int bufferSize = GetBuffer()->BufferSize();
mWriteBuffer.Clear();
if (mRecording)
{
for (int i = 0; i < gBufferSize; ++i)
{
//if we've already started recording, or if it's a new recording and there's sound
if (mRecordPos > 0 || fabsf(GetBuffer()->GetChannel(0)[i]) > mThresh)
{
mSampleData[mRecordPos] = GetBuffer()->GetChannel(0)[i];
if (mPassthrough)
{
for (int ch = 0; ch < mWriteBuffer.NumActiveChannels(); ++ch)
mWriteBuffer.GetChannel(ch)[i] += mSampleData[mRecordPos];
}
++mRecordPos;
}
if (mRecordPos >= MAX_SAMPLER_LENGTH)
{
StopRecording();
break;
}
}
}
mPolyMgr.Process(time, &mWriteBuffer, bufferSize);
SyncOutputBuffer(mWriteBuffer.NumActiveChannels());
for (int ch = 0; ch < mWriteBuffer.NumActiveChannels(); ++ch)
{
GetVizBuffer()->WriteChunk(mWriteBuffer.GetChannel(ch), mWriteBuffer.BufferSize(), ch);
Add(target->GetBuffer()->GetChannel(ch), mWriteBuffer.GetChannel(ch), gBufferSize);
}
GetBuffer()->Reset();
}
void Sampler::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (!mEnabled)
return;
if (!NoteInputBuffer::IsTimeWithinFrame(time) && GetTarget())
{
mNoteInputBuffer.QueueNote(time, pitch, velocity, voiceIdx, modulation);
return;
}
if (velocity > 0)
{
mPolyMgr.Start(time, pitch, velocity / 127.0f, voiceIdx, modulation);
mVoiceParams.mAdsr.Start(time, 1); //for visualization
}
else
{
mPolyMgr.Stop(time, pitch, voiceIdx);
mVoiceParams.mAdsr.Stop(time); //for visualization
}
}
void Sampler::SetEnabled(bool enabled)
{
mEnabled = enabled;
}
void Sampler::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mVolSlider->Draw();
mADSRDisplay->Draw();
mRecordCheckbox->Draw();
mThreshSlider->Draw();
mPitchCorrectCheckbox->Draw();
mPassthroughCheckbox->Draw();
ofPushMatrix();
ofTranslate(100, 15);
DrawAudioBuffer(100, 50, mSampleData, 0, mVoiceParams.mSampleLength, -1);
ofPushStyle();
ofNoFill();
ofSetColor(255, 0, 0);
if (mRecording && mRecordPos > 0)
ofRect(0, 0, 100, 50);
ofPopStyle();
ofPopMatrix();
}
void Sampler::StopRecording()
{
mRecording = false;
mVoiceParams.mSampleLength = mRecordPos;
if (mPitchCorrect)
mWantDetectPitch = true;
}
float Sampler::DetectSampleFrequency()
{
/*EnvOscillator osc(kOsc_Sin);
osc.Start(0,1);
float time = 0;
float phase = 0;
float phaseInc = GetPhaseInc(440);
for (int i=0; i<MAX_SAMPLER_LENGTH; ++i)
{
phase += phaseInc;
while (phase > FTWO_PI) { phase -= FTWO_PI; }
mSampleData[i] = osc.Audio(time, phase);
time += gInvSampleRateMs;
}*/
float pitch = mPitchDetector.DetectPitch(mSampleData, MAX_SAMPLER_LENGTH);
float freq = TheScale->PitchToFreq(pitch);
ofLog() << "Detected frequency: " << freq;
return freq;
}
void Sampler::GetModuleDimensions(float& width, float& height)
{
width = 210;
height = 90;
}
void Sampler::FilesDropped(std::vector<std::string> files, int x, int y)
{
Sample sample;
sample.Read(files[0].c_str());
SampleDropped(x, y, &sample);
}
void Sampler::SampleDropped(int x, int y, Sample* sample)
{
assert(sample);
//TODO(Ryan) multichannel
const float* data = sample->Data()->GetChannel(0);
int numSamples = sample->LengthInSamples();
if (numSamples <= 0)
return;
mVoiceParams.mSampleLength = MIN(MAX_SAMPLER_LENGTH, numSamples);
Clear(mSampleData, MAX_SAMPLER_LENGTH);
for (int i = 0; i < mVoiceParams.mSampleLength; ++i)
mSampleData[i] = data[i];
}
void Sampler::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadBool("loop", moduleInfo, false);
SetUpFromSaveData();
}
void Sampler::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
mVoiceParams.mLoop = mModuleSaveData.GetBool("loop");
}
void Sampler::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void Sampler::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mVolSlider)
mADSRDisplay->SetVol(mVoiceParams.mVol);
}
void Sampler::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void Sampler::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mRecordCheckbox)
{
if (mRecording)
{
mRecordPos = 0;
mVoiceParams.mSampleLength = 0;
Clear(mSampleData, MAX_SAMPLER_LENGTH);
}
else
{
StopRecording();
}
}
if (checkbox == mPitchCorrectCheckbox)
{
if (mPitchCorrect)
mVoiceParams.mDetectedFreq = DetectSampleFrequency();
else
mVoiceParams.mDetectedFreq = -1;
}
}
void Sampler::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out.Write(mSampleData, MAX_SAMPLER_LENGTH);
out << mVoiceParams.mSampleLength;
}
void Sampler::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
int length = MAX_SAMPLER_LENGTH;
if (rev < 2)
length = 2 * gSampleRate;
in.Read(mSampleData, length);
if (rev >= 1)
in >> mVoiceParams.mSampleLength;
if (mPitchCorrect)
mWantDetectPitch = true;
}
``` | /content/code_sandbox/Source/Sampler.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,226 |
```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
**/
/*
==============================================================================
NoteHumanizer.h
Created: 2 Nov 2016 7:56:20pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "INoteSource.h"
#include "Slider.h"
#include "Transport.h"
class NoteHumanizer : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener
{
public:
NoteHumanizer();
~NoteHumanizer();
static IDrawableModule* Create() { return new NoteHumanizer(); }
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 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;
}
float mTime{ 33 };
FloatSlider* mTimeSlider{ nullptr };
float mVelocity{ .1 };
FloatSlider* mVelocitySlider{ nullptr };
std::array<float, 128> mLastDelayMs{};
};
``` | /content/code_sandbox/Source/NoteHumanizer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 491 |
```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
**/
//
// ComboGridController.h
// Bespoke
//
// Created by Ryan Challinor on 2/10/15.
//
//
#pragma once
#include "GridController.h"
class ComboGridController : public IDrawableModule, public IGridController, public IGridControllerListener
{
public:
ComboGridController();
~ComboGridController() {}
static IDrawableModule* Create() { return new ComboGridController(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetGridControllerOwner(IGridControllerListener* owner) override { mOwner = owner; }
void SetLight(int x, int y, GridColor color, bool force = false) override;
void SetLightDirect(int x, int y, int color, bool force = false) override;
void ResetLights() override;
int NumCols() override { return mCols; }
int NumRows() override { return mRows; }
bool HasInput() const override;
bool IsConnected() const override { return true; }
void OnControllerPageSelected() override {}
void OnGridButton(int x, int y, float velocity, IGridController* grid) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return true; }
private:
enum Arrangements
{
kHorizontal,
kVertical,
kSquare
};
void InitializeCombo();
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
unsigned int mRows{ 0 };
unsigned int mCols{ 0 };
std::vector<IGridController*> mGrids;
Arrangements mArrangement{ Arrangements::kHorizontal };
IGridControllerListener* mOwner{ nullptr };
};
``` | /content/code_sandbox/Source/ComboGridController.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 552 |
```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
**/
//
// NoteLooper.cpp
// modularSynth
//
// Created by Ryan Challinor on 3/31/13.
//
//
#include "NoteLooper.h"
#include "SynthGlobals.h"
#include "Scale.h"
#include "MidiController.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "UIControlMacros.h"
NoteLooper::NoteLooper()
{
}
void NoteLooper::Init()
{
IDrawableModule::Init();
TheTransport->AddAudioPoller(this);
}
void NoteLooper::CreateUIControls()
{
IDrawableModule::CreateUIControls();
float w, h;
UIBLOCK(80);
CHECKBOX(mWriteCheckbox, "write", &mWrite);
CHECKBOX(mDeleteOrMuteCheckbox, "del/mute", &mDeleteOrMute);
UIBLOCK_NEWCOLUMN();
INTSLIDER(mNumMeasuresSlider, "num bars", &mNumMeasures, 1, 8);
BUTTON(mClearButton, "clear");
ENDUIBLOCK(w, h);
UIBLOCK(w + 10, 3, 45);
for (size_t i = 0; i < mSavedPatterns.size(); ++i)
{
BUTTON(mSavedPatterns[i].mStoreButton, ("store" + ofToString(i)).c_str());
BUTTON(mSavedPatterns[i].mLoadButton, ("load" + ofToString(i)).c_str());
UIBLOCK_NEWCOLUMN();
}
ENDUIBLOCK0();
mCanvas = new Canvas(this, 3, 45, mWidth - 6, mHeight - 48, L(length, 1), L(rows, 128), L(cols, 16), &(NoteCanvasElement::Create));
AddUIControl(mCanvas);
mCanvas->SetNumVisibleRows(1);
mCanvas->SetRowOffset(0);
SetNumMeasures(mNumMeasures);
}
NoteLooper::~NoteLooper()
{
TheTransport->RemoveAudioPoller(this);
}
void NoteLooper::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mWriteCheckbox->Draw();
mNumMeasuresSlider->Draw();
mDeleteOrMuteCheckbox->Draw();
mClearButton->Draw();
for (size_t i = 0; i < mSavedPatterns.size(); ++i)
{
mSavedPatterns[i].mStoreButton->Draw();
mSavedPatterns[i].mLoadButton->Draw();
if (mSavedPatterns[i].mNotes.size() > 0)
{
ofPushStyle();
ofFill();
ofSetColor(0, 255, 0, 80);
ofRectangle rect = mSavedPatterns[i].mLoadButton->GetRect(K(local));
ofRect(rect);
ofPopStyle();
}
}
if (mMinRow <= mMaxRow)
{
mCanvas->SetRowOffset(mMinRow);
mCanvas->SetNumVisibleRows(mMaxRow - mMinRow + 1);
}
mCanvas->SetCursorPos(GetCurPos(gTime));
mCanvas->Draw();
}
bool NoteLooper::DrawToPush2Screen()
{
ofRectangle rect = mCanvas->GetRect(true);
mCanvas->SetPosition(125, 3);
mCanvas->SetDimensions(600, 40);
mCanvas->SetCursorPos(GetCurPos(gTime));
mCanvas->Draw();
mCanvas->SetPosition(rect.x, rect.y);
mCanvas->SetDimensions(rect.width, rect.height);
return false;
}
void NoteLooper::Resize(float w, float h)
{
mWidth = MAX(w, 370);
mHeight = MAX(h, 140);
mCanvas->SetDimensions(mWidth - 6, mHeight - 48);
}
double NoteLooper::GetCurPos(double time) const
{
return ((TheTransport->GetMeasure(time) % mNumMeasures) + TheTransport->GetMeasurePos(time)) / mNumMeasures;
}
void NoteLooper::OnTransportAdvanced(float amount)
{
PROFILER(NoteLooper);
if (!mEnabled)
{
mCanvas->SetCursorPos(-1);
return;
}
double cursorPlayTime = NextBufferTime(mAllowLookahead);
double curPos = GetCurPos(cursorPlayTime);
if (mDeleteOrMute)
{
if (mWrite)
mCanvas->EraseElementsAt(curPos);
}
else
{
mCanvas->FillElementsAt(curPos, mNoteChecker);
}
for (int i = 0; i < 128; ++i)
{
int pitch = 128 - i - 1;
bool wasOn = mCurrentNotes[pitch] != nullptr || mInputNotes[pitch];
bool nowOn = mNoteChecker[i] != nullptr || mInputNotes[pitch];
bool hasChanged = (nowOn || wasOn) && mCurrentNotes[pitch] != static_cast<NoteCanvasElement*>(mNoteChecker[i]);
if (wasOn && mInputNotes[pitch] == nullptr && hasChanged)
{
//note off
if (mCurrentNotes[pitch])
{
double cursorAdvanceSinceEvent = curPos - mCurrentNotes[pitch]->GetEnd();
if (cursorAdvanceSinceEvent < 0)
cursorAdvanceSinceEvent += 1;
double time = cursorPlayTime - cursorAdvanceSinceEvent * TheTransport->MsPerBar() * mNumMeasures;
if (time < gTime)
time = gTime;
mNoteOutput.PlayNote(time, pitch, 0, mCurrentNotes[pitch]->GetVoiceIdx());
mCurrentNotes[pitch] = nullptr;
}
}
if (nowOn && mInputNotes[pitch] == nullptr && hasChanged)
{
//note on
NoteCanvasElement* note = static_cast<NoteCanvasElement*>(mNoteChecker[i]);
assert(note);
double cursorAdvanceSinceEvent = curPos - note->GetStart();
if (cursorAdvanceSinceEvent < 0)
cursorAdvanceSinceEvent += 1;
double time = cursorPlayTime - cursorAdvanceSinceEvent * TheTransport->MsPerBar() * mNumMeasures;
if (time > gTime)
{
mCurrentNotes[pitch] = note;
mNoteOutput.PlayNote(time, pitch, note->GetVelocity() * 127, note->GetVoiceIdx(), ModulationParameters(note->GetPitchBend(), note->GetModWheel(), note->GetPressure(), note->GetPan()));
}
}
mNoteChecker[i] = nullptr;
}
for (int pitch = 0; pitch < 128; ++pitch)
{
if (mInputNotes[pitch])
{
float endPos = curPos;
if (mInputNotes[pitch]->GetStart() > endPos)
endPos += 1; //wrap
mInputNotes[pitch]->SetEnd(endPos);
int modIdx = mInputNotes[pitch]->GetVoiceIdx();
if (modIdx == -1)
modIdx = kNumVoices;
float bend = ModulationParameters::kDefaultPitchBend;
float mod = ModulationParameters::kDefaultModWheel;
float pressure = ModulationParameters::kDefaultPressure;
if (mVoiceModulations[modIdx].pitchBend)
bend = mVoiceModulations[modIdx].pitchBend->GetValue(0);
if (mVoiceModulations[modIdx].modWheel)
mod = mVoiceModulations[modIdx].modWheel->GetValue(0);
if (mVoiceModulations[modIdx].pressure)
pressure = mVoiceModulations[modIdx].pressure->GetValue(0);
mInputNotes[pitch]->WriteModulation(curPos, bend, mod, pressure, mVoiceModulations[modIdx].pan);
}
else if (mCurrentNotes[pitch])
{
mCurrentNotes[pitch]->UpdateModulation(curPos);
}
}
}
void NoteLooper::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (voiceIdx != -1) //try to pick a voice that is unique, to avoid stomping on the voices of already-recorded notes when overdubbing
{
if (velocity > 0)
voiceIdx = GetNewVoice(voiceIdx);
else
voiceIdx = mVoiceMap[voiceIdx];
}
mNoteOutput.PlayNote(time, pitch, velocity, voiceIdx, modulation);
if ((mEnabled && mWrite) || (mInputNotes[pitch] && velocity == 0))
{
if (mInputNotes[pitch]) //handle note-offs or retriggers
{
double endPos = GetCurPos(time);
if (mInputNotes[pitch]->GetStart() > endPos)
endPos += 1; //wrap
mInputNotes[pitch]->SetEnd(endPos);
mInputNotes[pitch] = nullptr;
}
if (velocity > 0)
{
double measurePos = GetCurPos(time) * mNumMeasures;
NoteCanvasElement* element = AddNote(measurePos, pitch, velocity, 1 / mCanvas->GetNumCols(), voiceIdx, modulation);
mInputNotes[pitch] = element;
}
}
}
NoteCanvasElement* NoteLooper::AddNote(double measurePos, int pitch, int velocity, double length, int voiceIdx /*=-1*/, ModulationParameters modulation /* = ModulationParameters()*/)
{
double canvasPos = measurePos / mNumMeasures * mCanvas->GetNumCols();
int col = int(canvasPos + .5f); //round off
int row = mCanvas->GetNumRows() - pitch - 1;
NoteCanvasElement* element = static_cast<NoteCanvasElement*>(mCanvas->CreateElement(col, row));
element->mOffset = canvasPos - element->mCol; //the rounded off part
element->mLength = length / mNumMeasures * mCanvas->GetNumCols();
element->SetVelocity(velocity / 127.0f);
element->SetVoiceIdx(voiceIdx);
int modIdx = voiceIdx;
if (modIdx == -1)
modIdx = kNumVoices;
mVoiceModulations[modIdx] = modulation;
mCanvas->AddElement(element);
if (row < mMinRow)
mMinRow = row;
if (row > mMaxRow)
mMaxRow = row;
return element;
}
int NoteLooper::GetNewVoice(int voiceIdx)
{
int ret = voiceIdx;
if (voiceIdx >= 0 && voiceIdx < kNumVoices)
{
//TODO(Ryan) do a round robin for now, maybe in the future do something smarter like looking at what voices are already recorded and pick an unused one
ret = mVoiceRoundRobin;
const int kMinVoiceNumber = 2; //MPE synths seem to reserve channels <2 for global params
mVoiceRoundRobin = ((mVoiceRoundRobin - kMinVoiceNumber) + 1) % (kNumVoices - kMinVoiceNumber) + kMinVoiceNumber; //wrap around a 2-15 range
mVoiceMap[voiceIdx] = ret;
}
return ret;
}
void NoteLooper::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
for (int i = 0; i < (int)mCurrentNotes.size(); ++i)
{
if (mCurrentNotes[i] != nullptr)
{
mNoteOutput.PlayNote(time, i, 0, mCurrentNotes[i]->GetVoiceIdx());
mCurrentNotes[i] = nullptr;
}
}
}
}
void NoteLooper::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void NoteLooper::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
if (slider == mNumMeasuresSlider)
SetNumMeasures(mNumMeasures);
}
void NoteLooper::ButtonClicked(ClickButton* button, double time)
{
if (button == mClearButton)
{
for (int i = 0; i < (int)mCurrentNotes.size(); ++i)
{
if (mCurrentNotes[i] != nullptr)
{
mNoteOutput.PlayNote(time, i, 0, mCurrentNotes[i]->GetVoiceIdx());
mCurrentNotes[i] = nullptr;
}
}
for (int i = 0; i < (int)mInputNotes.size(); ++i)
{
if (mInputNotes[i] != nullptr)
{
mNoteOutput.PlayNote(time, i, 0, mInputNotes[i]->GetVoiceIdx());
mInputNotes[i] = nullptr;
}
}
mCanvas->Clear();
mMinRow = 127;
mMaxRow = 0;
}
for (size_t i = 0; i < mSavedPatterns.size(); ++i)
{
if (button == mSavedPatterns[i].mStoreButton)
mSavedPatterns[i].mNotes = mCanvas->GetElements();
if (button == mSavedPatterns[i].mLoadButton)
{
mCanvas->Clear();
mMinRow = 127;
mMaxRow = 0;
for (auto& element : mSavedPatterns[i].mNotes)
{
mCanvas->AddElement(element);
int row = element->mRow;
if (row < mMinRow)
mMinRow = row;
if (row > mMaxRow)
mMaxRow = row;
}
}
}
}
void NoteLooper::SetNumMeasures(int numMeasures)
{
mNumMeasures = numMeasures;
mCanvas->SetLength(mNumMeasures);
mCanvas->SetNumCols(TheTransport->CountInStandardMeasure(kInterval_8n) * mNumMeasures);
mCanvas->SetMajorColumnInterval(TheTransport->CountInStandardMeasure(kInterval_8n));
mCanvas->mViewStart = 0;
mCanvas->mViewEnd = mNumMeasures;
mCanvas->mLoopStart = 0;
mCanvas->mLoopEnd = mNumMeasures;
}
void NoteLooper::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void NoteLooper::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadBool("allow_lookahead", moduleInfo, false);
SetUpFromSaveData();
}
void NoteLooper::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
mAllowLookahead = mModuleSaveData.GetBool("allow_lookahead");
}
void NoteLooper::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out << mWidth;
out << mHeight;
out << mMinRow;
out << mMaxRow;
out << (int)mSavedPatterns.size();
for (size_t i = 0; i < mSavedPatterns.size(); ++i)
{
out << (int)mSavedPatterns[i].mNotes.size();
for (auto& note : mSavedPatterns[i].mNotes)
{
out << note->mCol;
out << note->mRow;
note->SaveState(out);
}
}
}
void NoteLooper::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());
in >> mWidth;
in >> mHeight;
Resize(mWidth, mHeight);
in >> mMinRow;
in >> mMaxRow;
int numPatterns;
in >> numPatterns;
LoadStateValidate(numPatterns == mSavedPatterns.size());
for (size_t i = 0; i < mSavedPatterns.size(); ++i)
{
int numNotes;
in >> numNotes;
mSavedPatterns[i].mNotes.resize(numNotes);
for (int j = 0; j < numNotes; ++j)
{
int col, row;
in >> col;
in >> row;
mSavedPatterns[i].mNotes[j] = NoteCanvasElement::Create(mCanvas, col, row);
mSavedPatterns[i].mNotes[j]->LoadState(in);
}
}
}
``` | /content/code_sandbox/Source/NoteLooper.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 3,734 |
```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
**/
/*
==============================================================================
AudioLevelToCV.h
Created: 9 Oct 2018 10:26:30pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "IModulator.h"
class PatchCableSource;
class AudioLevelToCV : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public IModulator
{
public:
AudioLevelToCV();
virtual ~AudioLevelToCV();
static IDrawableModule* Create() { return new AudioLevelToCV(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
bool ShouldSuppressAutomaticOutputCable() override { return true; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void Process(double time) override;
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
//IModulator
float Value(int samplesIn = 0) override;
bool Active() const override { return mEnabled; }
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 1; }
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = 106;
h = 17 * 5 + 2;
}
float mGain{ 1 };
float* mModulationBuffer;
FloatSlider* mGainSlider{ nullptr };
FloatSlider* mAttackSlider{ nullptr };
FloatSlider* mReleaseSlider{ nullptr };
float mVal{ 0 };
float mAttack{ 10 };
float mRelease{ 10 };
float mAttackFactor{ .99 };
float mReleaseFactor{ .99 };
};
``` | /content/code_sandbox/Source/AudioLevelToCV.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 631 |
```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
**/
/*
==============================================================================
PulseGate.h
Created: 22 Feb 2020 10:39:40pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "IPulseReceiver.h"
#include "Slider.h"
class PulseGate : public IDrawableModule, public IPulseSource, public IPulseReceiver
{
public:
PulseGate();
virtual ~PulseGate();
static IDrawableModule* Create() { return new PulseGate(); }
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 LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
bool mAllow{ true };
Checkbox* mAllowCheckbox{ nullptr };
float mWidth{ 200 };
float mHeight{ 20 };
};
``` | /content/code_sandbox/Source/PulseGate.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 405 |
```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
**/
//
// Compressor.h
// modularSynth
//
// Created by Ryan Challinor on 2/11/13.
//
//
#pragma once
#include <iostream>
#include "IAudioEffect.h"
#include "Slider.h"
#include "Checkbox.h"
#include "RollingBuffer.h"
//-------------------------------------------------------------
// DC offset (to prevent denormal)
//-------------------------------------------------------------
// USE:
// 1. init envelope state to DC_OFFSET before processing
// 2. add to input before envelope runtime function
static const double DC_OFFSET = 1.0E-25;
//-------------------------------------------------------------
// envelope detector
//-------------------------------------------------------------
class EnvelopeDetector
{
public:
EnvelopeDetector(double ms = 1.0);
virtual ~EnvelopeDetector() {}
// time constant
virtual void setTc(double ms);
virtual double getTc(void) const { return ms_; }
// runtime function
void run(double in, double& state)
{
state = in + coef_ * (state - in);
}
protected:
double ms_{ 1 }; // time constant in ms
double coef_{ 0 }; // runtime coefficient
virtual void setCoef(void); // coef calculation
}; // end SimpleComp class
//-------------------------------------------------------------
// attack/release envelope
//-------------------------------------------------------------
class AttRelEnvelope
{
public:
AttRelEnvelope(double att_ms = 10.0, double rel_ms = 100.0);
virtual ~AttRelEnvelope() {}
// attack time constant
virtual void setAttack(double ms);
virtual double getAttack(void) const { return att_.getTc(); }
// release time constant
virtual void setRelease(double ms);
virtual double getRelease(void) const { return rel_.getTc(); }
// runtime function
void run(double in, double& state)
{
/* assumes that:
* positive delta = attack
* negative delta = release
* good for linear & log values
*/
if (in > state)
att_.run(in, state); // attack
else
rel_.run(in, state); // release
}
private:
EnvelopeDetector att_;
EnvelopeDetector rel_;
}; // end AttRelEnvelope class
class Compressor : public IAudioEffect, public IFloatSliderListener
{
public:
Compressor();
static IAudioEffect* Create() { return new Compressor(); }
void CreateUIControls() override;
//IAudioEffect
void ProcessAudio(double time, ChannelBuffer* buffer) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
std::string GetType() override { return "compressor"; }
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
float mMix{ 1 };
float mDrive{ 1 };
float mThreshold{ -24 };
float mRatio{ 4 };
float mAttack{ .1f };
float mRelease{ 100 };
float mLookahead{ 3 };
float mOutputAdjust{ 1 };
FloatSlider* mMixSlider{ nullptr };
FloatSlider* mDriveSlider{ nullptr };
FloatSlider* mThresholdSlider{ nullptr };
FloatSlider* mRatioSlider{ nullptr };
FloatSlider* mAttackSlider{ nullptr };
FloatSlider* mReleaseSlider{ nullptr };
FloatSlider* mLookaheadSlider{ nullptr };
FloatSlider* mOutputAdjustSlider{ nullptr };
double mCurrentInputDb{ 0 };
double mOutputGain{ 1 };
float mWidth{ 200 };
float mHeight{ 20 };
// runtime variables
double envdB_{ DC_OFFSET }; // over-threshold envelope (dB)
AttRelEnvelope mEnv;
RollingBuffer mDelayBuffer;
};
``` | /content/code_sandbox/Source/Compressor.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 972 |
```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
**/
//
// SongBuilder.h
// Bespoke
//
// Created by Ryan Challinor on 11/05/22.
//
//
#pragma once
#include <iostream>
#include "ClickButton.h"
#include "IDrawableModule.h"
#include "INoteReceiver.h"
#include "IPulseReceiver.h"
#include "Slider.h"
#include "TextEntry.h"
#include "Push2Control.h"
class SongBuilder : public IDrawableModule, public IButtonListener, public IDropdownListener, public IIntSliderListener, public ITimeListener, public IPulseReceiver, public ITextEntryListener, public INoteReceiver, public IPush2GridController
{
public:
SongBuilder();
virtual ~SongBuilder();
static IDrawableModule* Create() { return new SongBuilder(); }
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; }
void Poll() override;
//ITimeListener
void OnTimeEvent(double time) override;
//IPulseReceiver
void OnPulse(double time, float velocity, int flags) override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendPressure(int pitch, int pressure) override {}
void SendCC(int control, int value, int voiceIdx = -1) override {}
//IPush2GridController
bool OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue) override;
void UpdatePush2Leds(Push2Control* push2) override;
bool DrawToPush2Screen() override;
void ButtonClicked(ClickButton* button, double time) override;
void DropdownClicked(DropdownList* list) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void TextEntryComplete(TextEntry* entry) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 1; }
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
bool IsResizable() const override { return false; }
void PostRepatch(PatchCableSource* cable, bool fromUserClick) override;
bool ShouldSavePatchCableSources() const override { return false; }
void SetActiveScene(double time, int newScene);
void SetActiveSceneById(double time, int newSceneId);
void DuplicateScene(int sceneIndex);
void AddTarget();
bool ShowSongSequencer() const { return mUseSequencer; }
void RefreshSequencerDropdowns();
void PlaySequence(double time, int startIndex);
enum class ContextMenuItems
{
kNone,
kDuplicate,
kDelete,
kMoveUp,
kMoveDown
};
struct ControlTarget
{
void CreateUIControls(SongBuilder* owner);
void Draw(float x, float y, int numRows);
void TargetControlUpdated();
IUIControl* GetTarget() const;
void CleanUp();
ofColor GetColor() { return mOwner->mColors[mColorIndex].color; }
enum class DisplayType
{
TextEntry,
Checkbox,
Dropdown,
NumDisplayTypes
};
SongBuilder* mOwner;
PatchCableSource* mCable{ nullptr };
DisplayType mDisplayType{ DisplayType::TextEntry };
ClickButton* mMoveLeftButton{ nullptr };
ClickButton* mMoveRightButton{ nullptr };
ClickButton* mCycleDisplayTypeButton{ nullptr };
DropdownList* mColorSelector{ nullptr };
bool mHadTarget{ false };
int mColorIndex{ 0 };
int mId{ -1 };
};
struct ControlValue
{
void CreateUIControls(SongBuilder* owner);
void Draw(float x, float y, int sceneIndex, ControlTarget* target);
void CleanUp();
void UpdateDropdownContents(ControlTarget* target);
float mFloatValue{ 0 };
TextEntry* mValueEntry{ nullptr };
bool mBoolValue{ false };
Checkbox* mCheckbox{ nullptr };
int mIntValue{ 0 };
DropdownList* mValueSelector{ nullptr };
int mId{ -1 };
};
struct SongScene
{
explicit SongScene(std::string name)
: mName(name)
{}
void CreateUIControls(SongBuilder* owner);
void Draw(SongBuilder* owner, float x, float y, int sceneIndex);
void TargetControlUpdated(SongBuilder::ControlTarget* target, int targetIndex, bool wasManuallyPatched);
void AddValue(SongBuilder* owner);
void MoveValue(int index, int amount);
float GetWidth() const;
void CleanUp();
std::string mName{};
TextEntry* mNameEntry{ nullptr };
ClickButton* mActivateButton{ nullptr };
DropdownList* mContextMenu{ nullptr };
ContextMenuItems mContextMenuSelection{ ContextMenuItems::kNone };
std::vector<ControlValue*> mValues{};
int mId{ -1 };
};
struct TargetColor
{
TargetColor(std::string _name, ofColor _color)
{
name = _name;
color = _color;
}
std::string name;
ofColor color;
};
int mCurrentScene{ -1 };
int mQueuedScene{ -1 };
int mSequenceStepIndex{ -1 };
int mSequenceStartStepIndex{ 0 };
bool mSequenceStartQueued{ false };
bool mSequencePaused{ false };
bool mWantResetClock{ false };
bool mJustResetClock{ false };
bool mWantRefreshValueDropdowns{ false };
std::vector<TargetColor> mColors{};
static const int kMaxSequencerScenes = 128;
static const int kSequenceEndId = -1;
bool mUseSequencer{ false };
Checkbox* mUseSequencerCheckbox{ nullptr };
bool mResetOnSceneChange{ true };
bool mActivateFirstSceneOnStop{ true };
Checkbox* mActivateFirstSceneOnStopCheckbox{ nullptr };
NoteInterval mChangeQuantizeInterval{ NoteInterval::kInterval_1n };
DropdownList* mChangeQuantizeSelector{ nullptr };
ClickButton* mAddTargetButton{ nullptr };
ClickButton* mPlaySequenceButton{ nullptr };
ClickButton* mStopSequenceButton{ nullptr };
ClickButton* mPauseSequenceButton{ nullptr };
bool mLoopSequence{ false };
Checkbox* mLoopCheckbox{ nullptr };
int mSequenceLoopStartIndex{ 0 };
TextEntry* mSequenceLoopStartEntry{ nullptr };
int mSequenceLoopEndIndex{ 0 };
TextEntry* mSequenceLoopEndEntry{ nullptr };
std::array<int, kMaxSequencerScenes> mSequencerSceneId{};
std::array<DropdownList*, kMaxSequencerScenes> mSequencerSceneSelector{};
std::array<int, kMaxSequencerScenes> mSequencerStepLength{};
std::array<TextEntry*, kMaxSequencerScenes> mSequencerStepLengthEntry{};
std::array<DropdownList*, kMaxSequencerScenes> mSequencerContextMenu{};
std::array<ContextMenuItems, kMaxSequencerScenes> mSequencerContextMenuSelection{};
std::array<ClickButton*, kMaxSequencerScenes> mSequencerPlayFromButton{};
std::vector<SongScene*> mScenes{};
std::vector<ControlTarget*> mTargets{};
};
``` | /content/code_sandbox/Source/SongBuilder.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,884 |
```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
**/
/*
==============================================================================
ModulatorGravity.h
Created: 30 Apr 2020 3:56:51pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "Slider.h"
#include "IModulator.h"
#include "Transport.h"
#include "Ramp.h"
#include "ClickButton.h"
#include "IPulseReceiver.h"
class PatchCableSource;
class ModulatorGravity : public IDrawableModule, public IFloatSliderListener, public IModulator, public IAudioPoller, public IButtonListener, public IPulseReceiver
{
public:
ModulatorGravity();
virtual ~ModulatorGravity();
static IDrawableModule* Create() { return new ModulatorGravity(); }
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; }
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
void OnPulse(double time, float velocity, int flags) override;
//IModulator
float Value(int samplesIn = 0) override;
bool Active() const override { return mEnabled; }
//IAudioPoller
void OnTransportAdvanced(float amount) override;
FloatSlider* GetTarget() { return GetSliderTarget(); }
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
//IButtonListener
void ButtonClicked(ClickButton* button, double time) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
void Kick(float strength);
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = mWidth;
h = mHeight;
}
float mWidth{ 200 };
float mHeight{ 20 };
float mValue{ 0 };
float mVelocity{ 0 };
Ramp mRamp;
float mGravity{ -.1 };
float mKickAmount{ 1 };
float mDrag{ .005 };
FloatSlider* mGravitySlider{ nullptr };
FloatSlider* mKickAmountSlider{ nullptr };
FloatSlider* mDragSlider{ nullptr };
ClickButton* mKickButton{ nullptr };
};
``` | /content/code_sandbox/Source/ModulatorGravity.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 678 |
```c++
#include "QwertyToPitchMapping.h"
#include "UserPrefs.h"
/*Returns the pitch of a computer key char, according to the user selected layout.
* May return -1 pitch for no matching key.
*/
QwertyToPitchResponse QwertyToPitchMapping::GetPitchForComputerKey(int key)
{
QwertyToPitchMappingMode mode = static_cast<QwertyToPitchMappingMode>(UserPrefs.qwerty_to_pitch_mode.GetIndex());
int pitch = -1;
int octaveShift = 0;
switch (mode)
{
case QwertyToPitchMappingMode::Ableton:
switch (key)
{
case 'a':
pitch = 0;
break;
case 'w':
pitch = 1;
break;
case 's':
pitch = 2;
break;
case 'e':
pitch = 3;
break;
case 'd':
pitch = 4;
break;
case 'f':
pitch = 5;
break;
case 't':
pitch = 6;
break;
case 'g':
pitch = 7;
break;
case 'y':
pitch = 8;
break;
case 'h':
pitch = 9;
break;
case 'u':
pitch = 10;
break;
case 'j':
pitch = 11;
break;
case 'k':
pitch = 12;
break;
case 'o':
pitch = 13;
break;
case 'l':
pitch = 14;
break;
case 'p':
pitch = 15;
break;
case ';':
pitch = 16;
break;
case 'z':
octaveShift = -1;
break;
case 'x':
octaveShift = 1;
break;
default:
pitch = -1;
break;
}
break;
case QwertyToPitchMappingMode::Fruity:
switch (key)
{
//Oct #1
case 'z':
pitch = 0;
break;
case 's':
pitch = 1;
break;
case 'x':
pitch = 2;
break;
case 'd':
pitch = 3;
break;
case 'c':
pitch = 4;
break;
case 'v':
pitch = 5;
break;
case 'g':
pitch = 6;
break;
case 'b':
pitch = 7;
break;
case 'h':
pitch = 8;
break;
case 'n':
pitch = 9;
break;
case 'j':
pitch = 10;
break;
case 'm':
pitch = 11;
break;
//Oct #2
case 'q':
pitch = 12;
break;
case '2':
pitch = 13;
break;
case 'w':
pitch = 14;
break;
case '3':
pitch = 15;
break;
case 'e':
pitch = 16;
break;
case 'r':
pitch = 17;
break;
case '5':
pitch = 18;
break;
case 't':
pitch = 19;
break;
case '6':
pitch = 20;
break;
case 'y':
pitch = 21;
break;
case '7':
pitch = 22;
break;
case 'u':
pitch = 23;
break;
case 'i':
pitch = 24;
break; //Trimmed so the layout fully supports 2 octaves +1
/*
case '9':
idx = 25;
break;
case 'o':
idx = 26;
break;
case '0':
idx = 27;
break;
case 'p':
idx = 28;
break;*/
//Oct Control
case ',':
octaveShift = -1;
break;
case '.':
octaveShift = 1;
break;
default:
pitch = -1;
break;
}
break;
}
return { pitch, octaveShift };
}
``` | /content/code_sandbox/Source/QwertyToPitchMapping.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 943 |
```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
**/
//
// NoteDelayer.cpp
// Bespoke
//
// Created by Ryan Challinor on 5/3/16.
//
//
#include "NoteDelayer.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
#include "Profiler.h"
NoteDelayer::NoteDelayer()
{
}
void NoteDelayer::Init()
{
IDrawableModule::Init();
TheTransport->AddAudioPoller(this);
}
NoteDelayer::~NoteDelayer()
{
TheTransport->RemoveAudioPoller(this);
}
void NoteDelayer::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mDelaySlider = new FloatSlider(this, "delay", 4, 4, 100, 15, &mDelay, 0, 1, 4);
}
void NoteDelayer::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mDelaySlider->Draw();
float t = (gTime - mLastNoteOnTime) / (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 NoteDelayer::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
mNoteOutput.Flush(time);
mAppendIndex = 0;
mConsumeIndex = 0;
}
}
void NoteDelayer::OnTransportAdvanced(float amount)
{
PROFILER(NoteDelayer);
ComputeSliders(0);
int end = mAppendIndex;
if (mAppendIndex < mConsumeIndex)
end += kQueueSize;
for (int i = mConsumeIndex; i < end; ++i)
{
const NoteInfo& info = mInputNotes[i % kQueueSize];
if (NextBufferTime(true) >= info.mTriggerTime)
{
PlayNoteOutput(info.mTriggerTime, info.mPitch, info.mVelocity, -1, info.mModulation);
mConsumeIndex = (mConsumeIndex + 1) % kQueueSize;
}
}
}
void NoteDelayer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (!mEnabled)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation); // Passthrough notes.
return;
}
if (velocity > 0)
mLastNoteOnTime = time;
if ((mAppendIndex + 1) % kQueueSize != mConsumeIndex)
{
NoteInfo info;
info.mPitch = pitch;
info.mVelocity = velocity;
info.mTriggerTime = time + mDelay / (float(TheTransport->GetTimeSigTop()) / TheTransport->GetTimeSigBottom()) * TheTransport->MsPerBar();
info.mModulation = modulation;
mInputNotes[mAppendIndex] = info;
mAppendIndex = (mAppendIndex + 1) % kQueueSize;
}
}
void NoteDelayer::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void NoteDelayer::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void NoteDelayer::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/NoteDelayer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 923 |
```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
**/
//
// LFO.h
// modularSynth
//
// Created by Ryan Challinor on 12/27/12.
//
//
#pragma once
#include "SynthGlobals.h"
#include "Transport.h"
#include "Oscillator.h"
#include "Ramp.h"
#include "PerlinNoise.h"
enum LFOMode
{
kLFOMode_Envelope,
kLFOMode_Oscillator
};
class LFO : public ITimeListener, public IAudioPoller
{
public:
LFO();
~LFO();
float Value(int samplesIn = 0, float forcePhase = -1) const;
void SetOffset(float offset) { mPhaseOffset = offset; }
void SetPeriod(NoteInterval interval);
void SetType(OscillatorType type);
void SetPulseWidth(float width) { mOsc.SetPulseWidth(width); }
void SetMode(LFOMode mode) { mMode = mode; }
float CalculatePhase(int samplesIn = 0, bool doTransform = true) const;
Oscillator* GetOsc() { return &mOsc; }
void SetFreeRate(float rate) { mFreeRate = rate; }
void SetLength(float length) { mLength = length; }
float TransformPhase(float phase) const;
//ITimeListener
void OnTimeEvent(double time) override;
//IAudioPoller
void OnTransportAdvanced(float amount) override;
private:
NoteInterval mPeriod{ NoteInterval::kInterval_1n };
float mPhaseOffset{ 0 };
Oscillator mOsc{ OscillatorType::kOsc_Sin };
LFOMode mMode{ LFOMode::kLFOMode_Envelope };
Ramp mRandom;
float mDrunk{ 0 };
double mFreePhase{ 0 };
float mFreeRate{ 1 };
float mLength{ 1 };
int mPerlinSeed{ 0 };
static PerlinNoise sPerlinNoise;
};
``` | /content/code_sandbox/Source/LFO.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 529 |
```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
**/
//
// MidiOutput.h
// Bespoke
//
// Created by Ryan Challinor on 5/24/15.
//
//
#pragma once
#include <iostream>
#include "MidiDevice.h"
#include "IDrawableModule.h"
#include "INoteReceiver.h"
#include "DropdownList.h"
#include "Transport.h"
class IAudioSource;
class MidiOutputModule : public IDrawableModule, public INoteReceiver, public IDropdownListener, public IAudioPoller
{
public:
MidiOutputModule();
virtual ~MidiOutputModule();
static IDrawableModule* Create() { return new MidiOutputModule(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() 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;
//IAudioPoller
void OnTransportAdvanced(float amount) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void DropdownClicked(DropdownList* list) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return true; }
private:
void InitController();
void BuildControllerList();
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = 190;
h = 25;
}
int mControllerIndex{ -1 };
DropdownList* mControllerList{ nullptr };
MidiDevice mDevice{ nullptr };
int mChannel{ 1 };
bool mUseVoiceAsChannel{ false };
float mPitchBendRange{ 2 };
int mModwheelCC{ 1 }; //or 74 in Multidimensional Polyphonic Expression (MPE) spec
struct ChannelModulations
{
ModulationParameters mModulation;
float mLastPitchBend{ 0 };
float mLastModWheel{ 0 };
float mLastPressure{ 0 };
};
std::vector<ChannelModulations> mChannelModulations;
};
``` | /content/code_sandbox/Source/MidiOutput.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 622 |
```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.cpp
Created: 10 Oct 2017 9:49:17pm
Author: Ryan Challinor
==============================================================================
*/
#include "Panner.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "PatchCableSource.h"
Panner::Panner()
: IAudioProcessor(gBufferSize)
{
}
void Panner::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mPanSlider = new FloatSlider(this, "pan", 5, 20, 110, 15, &mPan, -1, 1);
mWidenSlider = new FloatSlider(this, "widen", 55, 2, 60, 15, &mWiden, -150, 150, 0);
}
Panner::~Panner()
{
}
void Panner::Process(double time)
{
PROFILER(Panner);
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;
}
SyncBuffers(2);
mWidenerBuffer.SetNumChannels(2);
float* secondChannel;
if (GetBuffer()->NumActiveChannels() == 1) //panning mono input
{
BufferCopy(gWorkBuffer, GetBuffer()->GetChannel(0), GetBuffer()->BufferSize());
secondChannel = gWorkBuffer;
}
else
{
secondChannel = GetBuffer()->GetChannel(1);
}
ChannelBuffer* out = target->GetBuffer();
if (abs(mWiden) > 0)
{
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
mWidenerBuffer.WriteChunk(GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize(), ch);
if (mWiden < 0)
mWidenerBuffer.ReadChunk(secondChannel, GetBuffer()->BufferSize(), abs(mWiden), (GetBuffer()->NumActiveChannels() == 1) ? 0 : 1);
else
mWidenerBuffer.ReadChunk(GetBuffer()->GetChannel(0), GetBuffer()->BufferSize(), abs(mWiden), 0);
}
mPanRamp.Start(time, mPan, time + 2);
for (int i = 0; i < GetBuffer()->BufferSize(); ++i)
{
mPan = mPanRamp.Value(time);
ComputeSliders(i);
float left = GetBuffer()->GetChannel(0)[i];
float right = secondChannel[i];
GetBuffer()->GetChannel(0)[i] = left * ofMap(mPan, 0, 1, 1, 0, true) + right * ofMap(mPan, -1, 0, 1, 0, true);
secondChannel[i] = right * ofMap(mPan, -1, 0, 0, 1, true) + left * ofMap(mPan, 0, 1, 0, 1, true);
out->GetChannel(0)[i] += GetBuffer()->GetChannel(0)[i];
out->GetChannel(1)[i] += secondChannel[i];
time += gInvSampleRateMs;
}
GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(0), GetBuffer()->BufferSize(), 0);
GetVizBuffer()->WriteChunk(secondChannel, GetBuffer()->BufferSize(), 1);
GetBuffer()->Reset();
}
void Panner::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mPanSlider->Draw();
mWidenSlider->Draw();
GetLeftPanGain(mPan);
GetRightPanGain(mPan);
}
void Panner::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void Panner::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void Panner::ButtonClicked(ClickButton* button, double time)
{
}
void Panner::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void Panner::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadFloat("pan", moduleInfo, 0, mPanSlider);
SetUpFromSaveData();
}
void Panner::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
SetPan(mModuleSaveData.GetFloat("pan"));
}
``` | /content/code_sandbox/Source/Panner.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,160 |
```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
**/
//
// ModuleSaveDataPanel.cpp
// modularSynth
//
// Created by Ryan Challinor on 1/28/14.
//
//
#include "ModuleSaveDataPanel.h"
#include "IAudioSource.h"
#include "INoteSource.h"
#include "IAudioReceiver.h"
#include "INoteReceiver.h"
#include "ModuleContainer.h"
#include "IDrivableSequencer.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
#include <cstring>
ModuleSaveDataPanel* TheSaveDataPanel = nullptr;
const float kItemSpacing = 20;
ModuleSaveDataPanel::ModuleSaveDataPanel()
{
assert(TheSaveDataPanel == nullptr);
TheSaveDataPanel = this;
}
ModuleSaveDataPanel::~ModuleSaveDataPanel()
{
assert(TheSaveDataPanel == this);
TheSaveDataPanel = nullptr;
}
void ModuleSaveDataPanel::SetModule(IDrawableModule* module)
{
if (mSaveModule == module)
return;
if (module)
assert(module->IsSaveable());
mSaveModule = module;
mAppearAmount = 0;
ReloadSaveData();
}
void ModuleSaveDataPanel::ReloadSaveData()
{
for (auto iter = mSaveDataControls.begin(); iter != mSaveDataControls.end(); ++iter)
{
RemoveUIControl(*iter);
(*iter)->Delete();
}
mSaveDataControls.clear();
mLabels.clear();
mStringDropdowns.clear();
if (mSaveModule == nullptr || mSaveModule->IsSaveable() == false)
return;
UpdateTarget(mSaveModule);
int maxWidth = 40;
std::list<ModuleSaveData::SaveVal*> values = mSaveModule->GetSaveData().GetSavedValues();
for (auto iter = values.begin(); iter != values.end(); ++iter)
mLabels.push_back((*iter)->mProperty);
for (int i = 0; i < mSaveModule->GetChildren().size(); ++i)
{
IDrawableModule* child = mSaveModule->GetChildren()[i];
std::list<ModuleSaveData::SaveVal*>& childValues = child->GetSaveData().GetSavedValues();
for (auto iter = childValues.begin(); iter != childValues.end(); ++iter)
{
values.push_back(*iter);
mLabels.push_back(std::string(child->Name()) + "." + (*iter)->mProperty);
}
}
for (auto iter = mLabels.begin(); iter != mLabels.end(); ++iter)
maxWidth = MAX(maxWidth, GetStringWidth(*iter));
mAlignmentX = 10 + maxWidth;
float x = mAlignmentX;
float y = 5 + kItemSpacing;
mNameEntry = new TextEntry(this, "", x, y, 27, mSaveModule->NameMutable());
mNameEntry->SetNoHover(true);
mSaveDataControls.push_back(mNameEntry);
y += kItemSpacing;
mPresetFileSelector = new DropdownList(this, "preset", x, y, &mPresetFileIndex, 150);
mPresetFileSelector->SetNoHover(true);
mPresetFileSelector->SetUnknownItemString("[none]");
mSaveDataControls.push_back(mPresetFileSelector);
mSavePresetAsButton = new ClickButton(this, "save as", mPresetFileSelector, kAnchor_Right);
mSavePresetAsButton->SetNoHover(true);
mSaveDataControls.push_back(mSavePresetAsButton);
y += kItemSpacing;
TextEntry* prevTextEntry = mNameEntry;
for (auto iter = values.begin(); iter != values.end(); ++iter)
{
ModuleSaveData::SaveVal* save = *iter;
IUIControl* control = nullptr;
switch (save->mType)
{
case ModuleSaveData::kInt:
if (save->mEnumValues.empty() == false)
{
DropdownList* dropdown = new DropdownList(this, "", x, y, &(save->mInt));
control = dropdown;
for (auto value_iter = save->mEnumValues.begin(); value_iter != save->mEnumValues.end(); ++value_iter)
dropdown->AddLabel(value_iter->first.c_str(), value_iter->second);
}
else if (save->mIsTextField)
{
control = new TextEntry(this, "", x, y, 7, &(save->mInt), save->mMin, save->mMax);
}
else
{
control = new IntSlider(this, "", x, y, 150, 15, &(save->mInt), save->mMin, save->mMax);
}
break;
case ModuleSaveData::kFloat:
if (save->mIsTextField)
control = new TextEntry(this, "", x, y, 7, &(save->mFloat), save->mMin, save->mMax);
else
control = new FloatSlider(this, "", x, y, 150, 15, &(save->mFloat), save->mMin, save->mMax);
break;
case ModuleSaveData::kBool:
control = new Checkbox(this, "", x, y, &(save->mBool));
break;
case ModuleSaveData::kString:
if (save->mFillDropdownFn)
{
DropdownList* dropdown = new DropdownList(this, "", x, y, &(save->mInt));
mStringDropdowns[dropdown] = save;
control = dropdown;
FillDropdownList(dropdown, save);
}
else
{
control = new TextEntry(this, "", x, y, 100, save->mString);
dynamic_cast<TextEntry*>(control)->SetFlexibleWidth(true);
}
break;
}
TextEntry* textEntry = dynamic_cast<TextEntry*>(control);
if (textEntry)
{
if (prevTextEntry)
prevTextEntry->SetNextTextEntry(textEntry);
prevTextEntry = textEntry;
}
if (control != nullptr)
control->SetNoHover(true);
mSaveDataControls.push_back(control);
y += kItemSpacing;
}
y += 6;
mApplyButton = new ClickButton(this, "apply", x, y);
mApplyButton->SetNoHover(true);
mSaveDataControls.push_back(mApplyButton);
if (mSaveModule->CanBeDeleted())
{
mDeleteButton = new ClickButton(this, "delete module", x + 50, y);
mDeleteButton->SetNoHover(true);
mSaveDataControls.push_back(mDeleteButton);
}
y += kItemSpacing;
if (mSaveModule->HasDebugDraw())
{
mDrawDebugCheckbox = new Checkbox(this, "draw debug", x, y, &mSaveModule->mDrawDebug);
mDrawDebugCheckbox->SetNoHover(true);
mSaveDataControls.push_back(mDrawDebugCheckbox);
y += kItemSpacing;
}
IDrivableSequencer* sequencer = dynamic_cast<IDrivableSequencer*>(mSaveModule);
if (sequencer && sequencer->HasExternalPulseSource())
{
mResetSequencerButton = new ClickButton(this, "resume self-advance mode", x, y);
mResetSequencerButton->SetNoHover(true);
mSaveDataControls.push_back(mResetSequencerButton);
y += kItemSpacing;
}
mHeight = y + 5;
}
void ModuleSaveDataPanel::Poll()
{
using namespace juce;
if (mPresetFileUpdateQueued)
{
mPresetFileUpdateQueued = false;
if (mSaveModule != nullptr && !TheSynth->IsLoadingState() && mPresetFileIndex >= 0 && mPresetFileIndex < (int)mPresetFilePaths.size())
{
LoadPreset(mSaveModule, mPresetFilePaths[mPresetFileIndex]);
}
}
}
//static
void ModuleSaveDataPanel::LoadPreset(IDrawableModule* module, std::string presetFilePath)
{
FileStreamIn presetFile(presetFilePath);
presetFile >> ModularSynth::sLoadingFileSaveStateRev;
TheSynth->SetIsLoadingState(true);
PatchCableSource::sIsLoadingModulePreset = true;
module->LoadState(presetFile, module->LoadModuleSaveStateRev(presetFile));
PatchCableSource::sIsLoadingModulePreset = true;
TheSynth->SetIsLoadingState(false);
}
void ModuleSaveDataPanel::DrawModule()
{
if (Minimized() || mAppearAmount < 1)
return;
int x = mAlignmentX - 5;
int y = 5;
DrawTextRightJustify("type", x, y + 12);
DrawTextBold(mSaveModule->GetTypeName(), mAlignmentX, y + 12);
y += kItemSpacing;
DrawTextRightJustify("name", x, y + 12);
y += kItemSpacing;
DrawTextRightJustify("preset", x, y + 12);
y += kItemSpacing;
for (auto iter = mLabels.begin(); iter != mLabels.end(); ++iter)
{
DrawTextRightJustify(*iter, x, y + 12);
y += kItemSpacing;
}
for (auto iter = mSaveDataControls.begin(); iter != mSaveDataControls.end(); ++iter)
(*iter)->Draw();
}
void ModuleSaveDataPanel::UpdatePosition()
{
if (mSaveModule)
{
float moduleX, moduleY, moduleW, moduleH;
mSaveModule->GetPosition(moduleX, moduleY);
mSaveModule->GetDimensions(moduleW, moduleH);
SetPosition(moduleX + moduleW, moduleY);
}
if (mShowing)
mAppearAmount = ofClamp(mAppearAmount + ofGetLastFrameTime() * 5, 0, 1);
else
mAppearAmount = ofClamp(mAppearAmount - ofGetLastFrameTime() * 5, 0, 1);
}
void ModuleSaveDataPanel::ApplyChanges()
{
if (mSaveModule)
mSaveModule->SetUpFromSaveDataBase();
TheSaveDataPanel->SetModule(nullptr);
}
void ModuleSaveDataPanel::FillDropdownList(DropdownList* list, ModuleSaveData::SaveVal* save)
{
list->Clear();
FillDropdownFn fillFn = save->mFillDropdownFn;
assert(fillFn);
fillFn(list);
save->mInt = -1;
for (int i = 0; i < list->GetNumValues(); ++i)
{
if (list->GetLabel(i) == save->mString)
{
save->mInt = i;
break;
}
}
if (strlen(save->mString) > 0)
list->SetUnknownItemString(save->mString);
}
void ModuleSaveDataPanel::ButtonClicked(ClickButton* button, double time)
{
using namespace juce;
if (button == mApplyButton)
ApplyChanges();
if (button == mDeleteButton)
{
mSaveModule->GetOwningContainer()->DeleteModule(mSaveModule);
SetModule(nullptr);
}
if (button == mResetSequencerButton)
{
IDrivableSequencer* sequencer = dynamic_cast<IDrivableSequencer*>(mSaveModule);
if (sequencer && sequencer->HasExternalPulseSource())
sequencer->ResetExternalPulseSource();
}
if (button == mSavePresetAsButton && mSaveModule != nullptr)
{
juce::File(ofToDataPath("presets/" + mSaveModule->GetTypeName())).createDirectory();
FileChooser chooser("Save preset as...", File(ofToDataPath("presets/" + mSaveModule->GetTypeName() + "/preset.preset")), "*.preset", true, false, TheSynth->GetFileChooserParent());
if (chooser.browseForFileToSave(true))
{
std::string path = chooser.getResult().getFullPathName().toStdString();
FileStreamOut output(path);
output << ModularSynth::kSaveStateRev;
mSaveModule->SaveState(output);
RefreshPresetFiles();
for (size_t i = 0; i < mPresetFilePaths.size(); ++i)
{
if (mPresetFilePaths[i] == path)
{
mPresetFileIndex = (int)i;
break;
}
}
}
}
}
void ModuleSaveDataPanel::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void ModuleSaveDataPanel::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void ModuleSaveDataPanel::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void ModuleSaveDataPanel::TextEntryComplete(TextEntry* entry)
{
if (entry == mNameEntry)
{
std::string desiredName = mSaveModule->Name();
ofStringReplace(desiredName, "~", ""); //strip out illegal character
if (desiredName.empty())
desiredName = mSaveModule->GetTypeName();
mSaveModule->SetName("~~~~~~~~~~~");
std::string availableName = GetUniqueName(desiredName, mSaveModule->GetOwningContainer()->GetModuleNames<IDrawableModule*>());
mSaveModule->SetName(availableName.c_str());
}
}
void ModuleSaveDataPanel::DropdownClicked(DropdownList* list)
{
for (auto iter = mStringDropdowns.begin(); iter != mStringDropdowns.end(); ++iter)
{
if (list == iter->first)
{
FillDropdownList(list, iter->second);
}
}
if (list == mPresetFileSelector)
RefreshPresetFiles();
}
void ModuleSaveDataPanel::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
for (auto iter = mStringDropdowns.begin(); iter != mStringDropdowns.end(); ++iter)
{
if (list == iter->first)
{
ModuleSaveData::SaveVal* save = iter->second;
StringCopy(save->mString, list->GetLabel(save->mInt).c_str(), MAX_TEXTENTRY_LENGTH);
}
}
if (list == mPresetFileSelector)
mPresetFileUpdateQueued = true;
}
void ModuleSaveDataPanel::RefreshPresetFiles()
{
if (mSaveModule == nullptr)
return;
juce::File(ofToDataPath("presets/" + mSaveModule->GetTypeName())).createDirectory();
mPresetFilePaths.clear();
mPresetFileSelector->Clear();
juce::Array<juce::File> fileList;
for (const auto& entry : juce::RangedDirectoryIterator{ juce::File{ ofToDataPath("presets/" + mSaveModule->GetTypeName()) }, false, "*.preset" })
{
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 ModuleSaveDataPanel::GetModuleDimensions(float& width, float& height)
{
if (mShowing)
{
width = EaseOut(0, mAlignmentX + 250, mAppearAmount);
height = EaseIn(0, mHeight, mAppearAmount);
}
else
{
width = 0;
height = 0;
}
}
``` | /content/code_sandbox/Source/ModuleSaveDataPanel.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 3,515 |
```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
**/
//
// MacroSlider.cpp
// Bespoke
//
// Created by Ryan Challinor on 12/19/15.
//
//
#include "MacroSlider.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
MacroSlider::MacroSlider()
{
}
MacroSlider::~MacroSlider()
{
for (auto mapping : mMappings)
delete mapping;
}
void MacroSlider::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mSlider = new FloatSlider(this, "input", 5, 4, 100, 15, &mValue, 0, 1);
}
void MacroSlider::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mSlider->Draw();
for (auto mapping : mMappings)
mapping->Draw();
}
void MacroSlider::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
for (auto mapping : mMappings)
{
if (mapping->GetCableSource() == cableSource)
mapping->UpdateControl();
}
}
void MacroSlider::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void MacroSlider::SaveLayout(ofxJSONElement& moduleInfo)
{
moduleInfo["num_mappings"] = (int)mMappings.size();
}
void MacroSlider::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadInt("num_mappings", moduleInfo, 3, 1, 100, K(isTextField));
SetUpFromSaveData();
}
void MacroSlider::SetUpFromSaveData()
{
int newNumMappings = mModuleSaveData.GetInt("num_mappings");
if (mMappings.size() > newNumMappings)
{
for (int i = newNumMappings; i < mMappings.size(); ++i)
delete mMappings[i];
}
mMappings.resize(newNumMappings);
for (int i = 0; i < mMappings.size(); ++i)
{
if (mMappings[i] == nullptr)
{
Mapping* mapping = new Mapping(this, i);
mapping->CreateUIControls();
mMappings[i] = mapping;
}
}
}
void MacroSlider::SetOutputTarget(int index, IUIControl* target)
{
mMappings[index]->GetCableSource()->SetTarget(target);
}
MacroSlider::Mapping::Mapping(MacroSlider* owner, int index)
: mOwner(owner)
, mIndex(index)
{
}
MacroSlider::Mapping::~Mapping()
{
mOwner->GetOwningContainer()->DeleteCablesForControl(mMinSlider);
mOwner->GetOwningContainer()->DeleteCablesForControl(mMaxSlider);
mOwner->RemoveUIControl(mMinSlider);
mOwner->RemoveUIControl(mMaxSlider);
mTargetCable->ClearPatchCables();
mOwner->RemovePatchCableSource(mTargetCable);
}
void MacroSlider::Mapping::CreateUIControls()
{
mMinSlider = new FloatSlider(mOwner, ("start" + ofToString(mIndex + 1)).c_str(), 5, 25 + mIndex * kMappingSpacing, 100, 15, &mDummyMin, 0, 1);
mMaxSlider = new FloatSlider(mOwner, ("end" + ofToString(mIndex + 1)).c_str(), 5, 39 + mIndex * kMappingSpacing, 100, 15, &mDummyMax, 0, 1);
mTargetCable = new PatchCableSource(mOwner, kConnectionType_Modulator);
mTargetCable->SetModulatorOwner(this);
mTargetCable->SetManualPosition(110, 39 + mIndex * kMappingSpacing);
mTargetCable->SetOverrideCableDir(ofVec2f(1, 0), PatchCableSource::Side::kRight);
mOwner->AddPatchCableSource(mTargetCable);
}
void MacroSlider::Mapping::UpdateControl()
{
OnModulatorRepatch();
}
float MacroSlider::Mapping::Value(int samplesIn)
{
mOwner->ComputeSliders(samplesIn);
return ofMap(mOwner->GetValue(), 0, 1, GetMin(), GetMax(), K(clamp));
}
void MacroSlider::Mapping::Draw()
{
mMinSlider->Draw();
mMaxSlider->Draw();
if (GetSliderTarget())
{
float x, y, w, h;
mMinSlider->GetPosition(x, y, K(local));
mMinSlider->GetDimensions(w, h);
int lineX = ofLerp(x, x + w, GetSliderTarget()->ValToPos(GetSliderTarget()->GetValue(), true));
int lineY1 = y;
int lineY2 = y + h * 2;
ofPushStyle();
ofSetColor(ofColor::green);
ofLine(lineX, lineY1, lineX, lineY2);
ofPopStyle();
}
}
``` | /content/code_sandbox/Source/MacroSlider.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,177 |
```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
**/
//
// ModwheelToVibrato.h
// Bespoke
//
// Created by Ryan Challinor on 1/4/16.
//
//
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "ModulationChain.h"
#include "DropdownList.h"
class ModwheelToVibrato : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public IDropdownListener
{
public:
ModwheelToVibrato();
virtual ~ModwheelToVibrato();
static IDrawableModule* Create() { return new ModwheelToVibrato(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 138;
height = 22;
}
NoteInterval mVibratoInterval{ NoteInterval::kInterval_16n };
DropdownList* mIntervalSelector{ nullptr };
float mVibratoAmount{ 1 };
FloatSlider* mVibratoSlider{ nullptr };
Modulations mModulation{ true };
};
``` | /content/code_sandbox/Source/ModwheelToVibrato.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
**/
//
// LabelDisplay.cpp
// Bespoke
//
// Created by Noxy Nixie on 03/19/2024.
//
//
#include "LabelDisplay.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "Slider.h"
#include "UIControlMacros.h"
LabelDisplay::LabelDisplay()
{
mFonts.emplace_back("Normal", gFont);
mFonts.emplace_back("Bold", gFontBold);
mFonts.emplace_back("Fixed width", gFontFixedWidth);
mColors.emplace_back("White", ofColor::white);
mColors.emplace_back("Black", ofColor::black);
mColors.emplace_back("Grey", ofColor::grey);
mColors.emplace_back("Red", ofColor::red);
mColors.emplace_back("Green", ofColor::green);
mColors.emplace_back("Yellow", ofColor::yellow);
mColors.emplace_back("Orange", ofColor::orange);
mColors.emplace_back("Blue", ofColor::blue);
mColors.emplace_back("Purple", ofColor::purple);
mColors.emplace_back("Lime", ofColor::lime);
mColors.emplace_back("Magenta", ofColor::magenta);
mColors.emplace_back("Cyan", ofColor::cyan);
}
LabelDisplay::~LabelDisplay()
{
}
void LabelDisplay::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
CHECKBOX(mShowControlsCheckbox, "showcontrols", &mShowControls);
mShowControlsCheckbox->SetDisplayText(false);
UIBLOCK_SHIFTRIGHT();
TEXTENTRY(mLabelEntry, "label", 12, mLabel);
UIBLOCK_SHIFTRIGHT();
INTSLIDER(mLabelSizeSlider, "size", &mLabelSize, 25, 500);
UIBLOCK_SHIFTRIGHT();
DROPDOWN(mLabelFontDropdown, "font", &mLabelFontIndex, 90);
UIBLOCK_SHIFTRIGHT();
DROPDOWN(mLabelColorDropdown, "color", &mLabelColorIndex, 72);
ENDUIBLOCK(mWidth, mHeight);
for (int i = 0; i < mFonts.size(); i++)
mLabelFontDropdown->AddLabel(mFonts[i].name, i);
for (int i = 0; i < mColors.size(); i++)
mLabelColorDropdown->AddLabel(mColors[i].name, i);
}
void LabelDisplay::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
if (mShowControls)
{
mShowControlsCheckbox->Draw();
mLabelEntry->Draw();
mLabelSizeSlider->Draw();
mLabelFontDropdown->Draw();
mLabelColorDropdown->Draw();
}
ofSetColor(mLabelColor);
mLabelFont.DrawString(mLabel, mLabelSize, 2, (mLabelFont.GetStringHeight(mLabel, mLabelSize) / 1.25) + (mShowControls ? mHeight : 0));
}
void LabelDisplay::GetModuleDimensions(float& w, float& h)
{
w = MAX((mShowControls ? mWidth : 0), mLabelFont.GetStringWidth(mLabel, mLabelSize) + 6);
h = (mShowControls ? mHeight : 0) + (3 + mLabelFont.GetStringHeight(mLabel, mLabelSize)) * 1.05;
}
void LabelDisplay::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void LabelDisplay::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mLabelFontDropdown && mLabelFontIndex >= 0 && mLabelFontIndex < mFonts.size())
mLabelFont = mFonts[mLabelFontIndex].font;
else if (list == mLabelColorDropdown && mLabelColorIndex >= 0 && mLabelColorIndex < mColors.size())
mLabelColor = mColors[mLabelColorIndex].color;
}
void LabelDisplay::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mShowControlsCheckbox)
{
mLabelEntry->SetNoHover(!mShowControls);
mLabelSizeSlider->SetNoHover(!mShowControls);
mLabelFontDropdown->SetNoHover(!mShowControls);
mLabelColorDropdown->SetNoHover(!mShowControls);
}
}
void LabelDisplay::TextEntryComplete(TextEntry* entry)
{
}
``` | /content/code_sandbox/Source/LabelDisplay.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,051 |
```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
**/
//
// SampleVoice.cpp
// modularSynth
//
// Created by Ryan Challinor on 2/5/14.
//
//
#include "SampleVoice.h"
#include "SynthGlobals.h"
#include "Scale.h"
#include "Profiler.h"
#include "ChannelBuffer.h"
SampleVoice::SampleVoice(IDrawableModule* owner)
: mOwner(owner)
{
}
SampleVoice::~SampleVoice()
{
}
bool SampleVoice::IsDone(double time)
{
return mAdsr.IsDone(time);
}
bool SampleVoice::Process(double time, ChannelBuffer* out, int oversampling)
{
PROFILER(SampleVoice);
if (IsDone(time) ||
mVoiceParams->mSampleData == nullptr ||
mVoiceParams->mSampleLength == 0)
return false;
float volSq = mVoiceParams->mVol * mVoiceParams->mVol;
for (int pos = 0; pos < out->BufferSize(); ++pos)
{
if (mOwner)
mOwner->ComputeSliders(pos);
if (mPos <= mVoiceParams->mSampleLength || mVoiceParams->mLoop)
{
float freq = TheScale->PitchToFreq(GetPitch(pos));
float speed;
if (mVoiceParams->mDetectedFreq != -1)
speed = freq / mVoiceParams->mDetectedFreq;
else
speed = freq / TheScale->PitchToFreq(TheScale->ScaleRoot() + 48);
float sample = GetInterpolatedSample(mPos, mVoiceParams->mSampleData, mVoiceParams->mSampleLength) * mAdsr.Value(time) * volSq;
if (out->NumActiveChannels() == 1)
{
out->GetChannel(0)[pos] += sample;
}
else
{
out->GetChannel(0)[pos] += sample * GetLeftPanGain(GetPan());
out->GetChannel(1)[pos] += sample * GetRightPanGain(GetPan());
}
mPos += speed;
}
time += gInvSampleRateMs;
}
return true;
}
void SampleVoice::Start(double time, float target)
{
mPos = 0;
mAdsr.Start(time, target, mVoiceParams->mAdsr);
}
void SampleVoice::Stop(double time)
{
mAdsr.Stop(time);
}
void SampleVoice::ClearVoice()
{
mAdsr.Clear();
}
void SampleVoice::SetVoiceParams(IVoiceParams* params)
{
mVoiceParams = dynamic_cast<SampleVoiceParams*>(params);
}
``` | /content/code_sandbox/Source/SampleVoice.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 649 |
```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
**/
//
// LFO.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/27/12.
//
//
#include "LFO.h"
#include "OpenFrameworksPort.h"
#include "Profiler.h"
//static
PerlinNoise LFO::sPerlinNoise;
LFO::LFO()
{
SetPeriod(kInterval_1n);
}
LFO::~LFO()
{
TheTransport->RemoveListener(this);
TheTransport->RemoveAudioPoller(this);
}
float LFO::CalculatePhase(int samplesIn /*= 0*/, bool doTransform /* = true*/) const
{
float ret;
if (mPeriod == kInterval_Free)
{
ret = mFreePhase + float(samplesIn) / gSampleRate * mFreeRate;
}
else
{
float period = TheTransport->GetDuration(mPeriod) / TheTransport->GetDuration(kInterval_1n);
float phase = TheTransport->GetMeasureTime(gTime + samplesIn * gInvSampleRateMs) / period + (1 - mPhaseOffset) + 1; //+1 so we can have negative samplesIn
phase -= int(phase) / 2 * 2; //using 2 allows for shuffle to work
ret = phase;
}
if (doTransform)
return TransformPhase(ret);
return ret;
}
float LFO::TransformPhase(float phase) const
{
if (mLength != 1)
phase = int(phase) + ofClamp((phase - int(phase)) / mLength, 0, 1);
return phase;
}
float LFO::Value(int samplesIn /*= 0*/, float forcePhase /*= -1*/) const
{
//PROFILER(LFO_Value);
if (mPeriod == kInterval_None) //no oscillator
return mMode == kLFOMode_Envelope ? 1 : 0;
float phase = CalculatePhase(samplesIn);
if (forcePhase != -1)
phase = forcePhase;
phase *= FTWO_PI;
float sample;
bool nonstandardOsc = false;
//use sample-and-hold value
if (mOsc.GetType() == kOsc_Random)
{
nonstandardOsc = true;
sample = pow(mRandom.Value(gTime + samplesIn * gInvSampleRateMs), powf((1 - mOsc.GetPulseWidth()) * 2, 2));
}
else if (mOsc.GetType() == kOsc_Drunk)
{
nonstandardOsc = true;
sample = mDrunk;
}
else if (mOsc.GetType() == kOsc_Perlin)
{
nonstandardOsc = true;
double perlinPos = gTime + gInvSampleRateMs * samplesIn;
if (forcePhase != -1)
perlinPos += forcePhase * 1000;
double perlinPhase = perlinPos * mFreeRate / 1000.0f;
sample = sPerlinNoise.noise(perlinPhase, mPerlinSeed, -perlinPhase);
}
else
{
sample = mOsc.Value(phase);
if (mMode == kLFOMode_Envelope) //rescale to 0 1
sample = sample * .5f + .5f;
}
if (nonstandardOsc)
{
if (mOsc.GetPulseWidth() != .5f)
sample = Bias(sample, mOsc.GetPulseWidth());
if (mMode == kLFOMode_Oscillator) //rescale to -1 1
sample = (sample - .5f * 2);
}
return sample;
}
void LFO::SetPeriod(NoteInterval interval)
{
if (interval == kInterval_Free)
mFreePhase = CalculatePhase();
mPeriod = interval;
if (mOsc.GetType() == kOsc_Random)
{
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
transportListenerInfo->mInterval = mPeriod;
}
if (mOsc.GetType() == kOsc_Drunk || mPeriod == kInterval_Free)
TheTransport->AddAudioPoller(this);
else
TheTransport->RemoveAudioPoller(this);
}
void LFO::SetType(OscillatorType type)
{
mOsc.SetType(type);
if (type == kOsc_Random)
TheTransport->AddListener(this, mPeriod, OffsetInfo(0, true), false);
else
TheTransport->RemoveListener(this);
if (type == kOsc_Perlin)
mPerlinSeed = gRandom() % 10000;
if (mOsc.GetType() == kOsc_Drunk || mOsc.GetType() == kOsc_Perlin || mPeriod == kInterval_Free)
TheTransport->AddAudioPoller(this);
else
TheTransport->RemoveAudioPoller(this);
}
void LFO::OnTimeEvent(double time)
{
if (mOsc.GetSoften() == 0)
mRandom.SetValue(ofRandom(1));
else
mRandom.Start(time, ofRandom(1), time + mOsc.GetSoften() * 30);
}
void LFO::OnTransportAdvanced(float amount)
{
if (mOsc.GetType() == kOsc_Drunk)
{
float distance = 0;
if (mPeriod == kInterval_Free)
{
distance = mFreeRate / 40;
}
else
{
distance = TheTransport->GetDuration(kInterval_64n) / TheTransport->GetDuration(mPeriod);
}
float drunk = ofRandom(-distance, distance);
if (mDrunk + drunk > 1 || mDrunk + drunk < 0)
drunk *= -1;
mDrunk = ofClamp(mDrunk + drunk, 0, 1);
}
if (mPeriod == kInterval_Free || mOsc.GetType() == kOsc_Perlin)
{
mFreePhase += mFreeRate * amount * TheTransport->MsPerBar() / 1000;
double wrap = mOsc.GetShuffle() > 0 ? 2 : 1;
if (mFreePhase > wrap || mFreePhase < 0)
{
mFreePhase = fmod(mFreePhase, wrap);
if (mOsc.GetType() == kOsc_Random)
OnTimeEvent(gTime);
}
}
}
``` | /content/code_sandbox/Source/LFO.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,524 |
```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
**/
//
// PreviousNote.h
// Bespoke
//
// Created by Ryan Challinor on 1/4/16.
//
//
#pragma once
#include "IDrawableModule.h"
#include "NoteEffectBase.h"
class PreviousNote : public NoteEffectBase, public IDrawableModule
{
public:
PreviousNote();
static IDrawableModule* Create() { return new PreviousNote(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) 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 = 22;
}
int mPitch{ -1 };
int mVelocity{ 0 };
};
``` | /content/code_sandbox/Source/PreviousNote.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 371 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
AudioToPulse.h
Created: 31 Mar 2021 10:18:53pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "IAudioProcessor.h"
#include "IPulseReceiver.h"
#include "Slider.h"
class PatchCableSource;
class AudioToPulse : public IDrawableModule, public IPulseSource, public IAudioProcessor, public IFloatSliderListener
{
public:
AudioToPulse();
virtual ~AudioToPulse();
static IDrawableModule* Create() { return new AudioToPulse(); }
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 Process(double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
float mWidth{ 200 };
float mHeight{ 20 };
FloatSlider* mThresholdSlider{ nullptr };
FloatSlider* mReleaseSlider{ nullptr };
float mPeak{ 0 };
float mEnvelope{ 0 };
float mThreshold{ 0.5 };
float mRelease{ 150 };
float mReleaseFactor{ 0.99 };
};
``` | /content/code_sandbox/Source/AudioToPulse.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 502 |
```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
**/
//
// FreeverbEffect.h
// Bespoke
//
// Created by Ryan Challinor on 12/19/14.
//
//
#pragma once
#include <iostream>
#include "IAudioEffect.h"
#include "Slider.h"
#include "Checkbox.h"
#include "freeverb/revmodel.hpp"
class FreeverbEffect : public IAudioEffect, public IFloatSliderListener
{
public:
FreeverbEffect();
~FreeverbEffect();
static IAudioEffect* Create() { return new FreeverbEffect(); }
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 "freeverb"; }
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
revmodel mFreeverb;
bool mNeedUpdate{ false };
bool mFreeze{ false };
float mRoomSize{ .5 };
float mDamp{ 50 };
float mWet{ .5 };
float mDry{ 1 };
float mVerbWidth{ 50 };
FloatSlider* mRoomSizeSlider{ nullptr };
FloatSlider* mDampSlider{ nullptr };
FloatSlider* mWetSlider{ nullptr };
FloatSlider* mDrySlider{ nullptr };
FloatSlider* mWidthSlider{ nullptr };
};
``` | /content/code_sandbox/Source/FreeverbEffect.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 469 |
```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
**/
//
// WhiteKeys.h
// modularSynth
//
// Created by Ryan Challinor on 3/7/13.
//
//
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
class WhiteKeys : public NoteEffectBase, public IDrawableModule
{
public:
WhiteKeys();
static IDrawableModule* Create() { return new WhiteKeys(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
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;
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 = 110;
height = 0;
}
};
``` | /content/code_sandbox/Source/WhiteKeys.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 377 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// BiquadFilter.cpp
// modularSynth
//
// Created by Ryan Challinor on 1/2/14.
//
//
#include "BiquadFilter.h"
#include "SynthGlobals.h"
BiquadFilter::BiquadFilter()
: mSampleRate(gSampleRate)
{
Clear();
UpdateFilterCoeff();
}
void BiquadFilter::Clear()
{
mZ1 = 0;
mZ2 = 0;
}
void BiquadFilter::SetFilterParams(double f, double q)
{
if (mF != f || mQ != q)
{
mF = f;
mQ = q;
UpdateFilterCoeff();
}
}
void BiquadFilter::UpdateFilterCoeff()
{
if (mF <= 0 || std::isnan(mF))
{
mA0 = 1;
mA1 = 0;
mA2 = 0;
mB1 = 0;
mB2 = 0;
return;
}
double norm;
double V = pow(10, fabs(mDbGain) / 20.0);
double K = tan(M_PI * (mF / mSampleRate));
switch (mType)
{
case kFilterType_Lowpass:
norm = 1 / (1 + K / mQ + K * K);
mA0 = K * K * norm;
mA1 = 2 * mA0;
mA2 = mA0;
mB1 = 2 * (K * K - 1) * norm;
mB2 = (1 - K / mQ + K * K) * norm;
break;
case kFilterType_Highpass:
norm = 1 / (1 + K / mQ + K * K);
mA0 = 1 * norm;
mA1 = -2 * mA0;
mA2 = mA0;
mB1 = 2 * (K * K - 1) * norm;
mB2 = (1 - K / mQ + K * K) * norm;
break;
case kFilterType_Bandpass:
norm = 1 / (1 + K / mQ + K * K);
mA0 = K / mQ * norm;
mA1 = 0;
mA2 = -mA0;
mB1 = 2 * (K * K - 1) * norm;
mB2 = (1 - K / mQ + K * K) * norm;
break;
case kFilterType_Notch:
norm = 1 / (1 + K / mQ + K * K);
mA0 = (1 + K * K) * norm;
mA1 = 2 * (K * K - 1) * norm;
mA2 = mA0;
mB1 = mA1;
mB2 = (1 - K / mQ + K * K) * norm;
break;
case kFilterType_Peak:
if (mDbGain >= 0)
{ // boost
norm = 1 / (1 + K / mQ + K * K);
mA0 = (1 + K / mQ * V + K * K) * norm;
mA1 = 2 * (K * K - 1) * norm;
mA2 = (1 - K / mQ * V + K * K) * norm;
mB1 = mA1;
mB2 = (1 - K / mQ + K * K) * norm;
}
else
{ // cut
norm = 1 / (1 + K / mQ * V + K * K);
mA0 = (1 + K / mQ + K * K) * norm;
mA1 = 2 * (K * K - 1) * norm;
mA2 = (1 - K / mQ + K * K) * norm;
mB1 = mA1;
mB2 = (1 - K / mQ * V + K * K) * norm;
}
break;
case kFilterType_LowShelf:
if (mDbGain >= 0)
{ // boost
norm = 1 / (1 + K / mQ + K * K);
mA0 = (1 + sqrt(V) * K / mQ + V * K * K) * norm;
mA1 = 2 * (V * K * K - 1) * norm;
mA2 = (1 - sqrt(V) * K / mQ + V * K * K) * norm;
mB1 = 2 * (K * K - 1) * norm;
mB2 = (1 - K / mQ + K * K) * norm;
}
else
{ // cut
norm = 1 / (1 + sqrt(V) * K / mQ + V * K * K);
mA0 = (1 + K / mQ + K * K) * norm;
mA1 = 2 * (K * K - 1) * norm;
mA2 = (1 - K / mQ + K * K) * norm;
mB1 = 2 * (V * K * K - 1) * norm;
mB2 = (1 - sqrt(V) * K / mQ + V * K * K) * norm;
}
break;
case kFilterType_HighShelf:
if (mDbGain >= 0)
{ // boost
norm = 1 / (1 + K / mQ + K * K);
mA0 = (V + sqrt(V) * K / mQ + K * K) * norm;
mA1 = 2 * (K * K - V) * norm;
mA2 = (V - sqrt(V) * K / mQ + K * K) * norm;
mB1 = 2 * (K * K - 1) * norm;
mB2 = (1 - K / mQ + K * K) * norm;
}
else
{ // cut
norm = 1 / (V + sqrt(V) * K / mQ + K * K);
mA0 = (1 + K / mQ + K * K) * norm;
mA1 = 2 * (K * K - 1) * norm;
mA2 = (1 - K / mQ + K * K) * norm;
mB1 = 2 * (K * K - V) * norm;
mB2 = (V - sqrt(V) * K / mQ + K * K) * norm;
}
break;
case kFilterType_LowShelfNoQ:
if (mDbGain >= 0)
{ // boost
norm = 1 / (1 + sqrt(2) * K + K * K);
mA0 = (1 + sqrt(2 * V) * K + V * K * K) * norm;
mA1 = 2 * (V * K * K - 1) * norm;
mA2 = (1 - sqrt(2 * V) * K + V * K * K) * norm;
mB1 = 2 * (K * K - 1) * norm;
mB2 = (1 - sqrt(2) * K + K * K) * norm;
}
else
{ // cut
norm = 1 / (1 + sqrt(2 * V) * K + V * K * K);
mA0 = (1 + sqrt(2) * K + K * K) * norm;
mA1 = 2 * (K * K - 1) * norm;
mA2 = (1 - sqrt(2) * K + K * K) * norm;
mB1 = 2 * (V * K * K - 1) * norm;
mB2 = (1 - sqrt(2 * V) * K + V * K * K) * norm;
}
break;
case kFilterType_HighShelfNoQ:
if (mDbGain >= 0)
{ // boost
norm = 1 / (1 + sqrt(2) * K + K * K);
mA0 = (V + sqrt(2 * V) * K + K * K) * norm;
mA1 = 2 * (K * K - V) * norm;
mA2 = (V - sqrt(2 * V) * K + K * K) * norm;
mB1 = 2 * (K * K - 1) * norm;
mB2 = (1 - sqrt(2) * K + K * K) * norm;
}
else
{ // cut
norm = 1 / (V + sqrt(2 * V) * K + K * K);
mA0 = (1 + sqrt(2) * K + K * K) * norm;
mA1 = 2 * (K * K - 1) * norm;
mA2 = (1 - sqrt(2) * K + K * K) * norm;
mB1 = 2 * (K * K - V) * norm;
mB2 = (V - sqrt(2 * V) * K + K * K) * norm;
}
break;
case kFilterType_Allpass:
norm = 1 / (1 + K / mQ + K * K);
mA0 = (1 - K / mQ + K * K) * norm;
mA1 = 2 * (K * K - 1) * norm;
mA2 = 1;
mB1 = mA1;
mB2 = mA0;
break;
case kFilterType_Off:
mA0 = 1;
mA1 = 0;
mA2 = 0;
mB1 = 0;
mB2 = 0;
break;
}
}
void BiquadFilter::Filter(float* buffer, int bufferSize)
{
for (int i = 0; i < bufferSize; ++i)
buffer[i] = Filter(buffer[i]);
}
void BiquadFilter::CopyCoeffFrom(BiquadFilter& other)
{
mA0 = other.mA0;
mA1 = other.mA1;
mA2 = other.mA2;
mB1 = other.mB1;
mB2 = other.mB2;
}
float BiquadFilter::GetMagnitudeResponseAt(float f)
{
auto const piw0 = (f / mSampleRate) * M_PI * 2;
auto const cosw = std::cos(piw0);
auto const sinw = std::sin(piw0);
auto square = [](auto z)
{
return z * z;
};
auto const numerator = sqrt(square(mA0 * square(cosw) - mA0 * square(sinw) + mA1 * cosw + mA2) + square(2 * mA0 * cosw * sinw + mA1 * (sinw)));
auto const denominator = sqrt(square(square(cosw) - square(sinw) + mB1 * cosw + mB2) + square(2 * cosw * sinw + mB1 * (sinw)));
return numerator / denominator;
}
``` | /content/code_sandbox/Source/BiquadFilter.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,598 |
```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
**/
//
// GridController.h
// Bespoke
//
// Created by Ryan Challinor on 2/9/15.
//
//
#pragma once
#include "IUIControl.h"
#include "MidiController.h"
#define MAX_GRIDCONTROLLER_ROWS 512
#define MAX_GRIDCONTROLLER_COLS 512
class IGridController;
class PatchCableSource;
enum GridColor
{
kGridColorOff,
kGridColor1Dim,
kGridColor1Bright,
kGridColor2Dim,
kGridColor2Bright,
kGridColor3Dim,
kGridColor3Bright
};
class IGridControllerListener
{
public:
virtual ~IGridControllerListener() {}
virtual void OnControllerPageSelected() = 0;
virtual void OnGridButton(int x, int y, float velocity, IGridController* grid) = 0;
};
class IGridController
{
public:
virtual ~IGridController() {}
virtual void SetGridControllerOwner(IGridControllerListener* owner) = 0;
virtual void SetLight(int x, int y, GridColor color, bool force = false) = 0;
virtual void SetLightDirect(int x, int y, int color, bool force = false) = 0;
virtual void ResetLights() = 0;
virtual int NumCols() = 0;
virtual int NumRows() = 0;
virtual bool HasInput() const = 0;
virtual bool IsMultisliderGrid() const { return false; }
virtual bool IsConnected() const = 0;
};
class GridControlTarget : public IUIControl
{
public:
GridControlTarget(IGridControllerListener* owner, const char* name, int x, int y);
virtual ~GridControlTarget() {}
void Render() override;
static void DrawGridIcon(float x, float y);
void SetGridController(IGridController* gridController)
{
mGridController = gridController;
gridController->SetGridControllerOwner(mOwner);
}
IGridController* GetGridController() { return mGridController; }
//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;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, bool shouldSetValue = true) override;
bool IsSliderControl() override { return false; }
bool IsButtonControl() override { return false; }
bool GetNoHover() const override { return true; }
private:
void GetDimensions(float& width, float& height) override
{
width = 30;
height = 15;
}
bool MouseMoved(float x, float y) override;
IGridControllerListener* mOwner{ nullptr };
IGridController* mGridController{ nullptr };
};
class GridControllerMidi : public IGridController
{
public:
GridControllerMidi();
virtual ~GridControllerMidi() {}
void SetUp(GridLayout* layout, int page, MidiController* controller);
void UnhookController();
//IGridController
void SetGridControllerOwner(IGridControllerListener* owner) override { mOwner = owner; }
void SetLight(int x, int y, GridColor color, bool force = false) override;
void SetLightDirect(int x, int y, int color, bool force = false) override;
void ResetLights() override;
int NumCols() override { return mCols; }
int NumRows() override { return mRows; }
bool HasInput() const override;
//bool IsMultisliderGrid() const override { return mColors.empty(); } //commented out... don't remember what types of grids this is supposed to be for
bool IsConnected() const override { return mMidiController != nullptr; }
void OnControllerPageSelected();
void OnInput(int control, float velocity);
private:
unsigned int mRows{ 8 };
unsigned int mCols{ 8 };
int mControls[MAX_GRIDCONTROLLER_COLS][MAX_GRIDCONTROLLER_ROWS]{};
float mInput[MAX_GRIDCONTROLLER_COLS][MAX_GRIDCONTROLLER_ROWS]{};
int mLights[MAX_GRIDCONTROLLER_COLS][MAX_GRIDCONTROLLER_ROWS]{};
std::vector<int> mColors;
MidiMessageType mMessageType{ MidiMessageType::kMidiMessage_Note };
MidiController* mMidiController{ nullptr };
int mControllerPage{ 0 };
IGridControllerListener* mOwner{ nullptr };
};
``` | /content/code_sandbox/Source/GridController.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,099 |
```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
**/
//
// RadioButton.h
// modularSynth
//
// Created by Ryan Challinor on 12/5/12.
//
//
#pragma once
#include "IUIControl.h"
struct RadioButtonElement
{
std::string mLabel;
int mValue{ 0 };
};
enum RadioDirection
{
kRadioVertical,
kRadioHorizontal
};
class RadioButton;
class DropdownList;
class IRadioButtonListener
{
public:
virtual ~IRadioButtonListener() {}
virtual void RadioButtonUpdated(RadioButton* radio, int oldVal, double time) = 0;
};
class RadioButton : public IUIControl
{
public:
RadioButton(IRadioButtonListener* owner, const char* name, int x, int y, int* var, RadioDirection direction = kRadioVertical);
RadioButton(IRadioButtonListener* owner, const char* name, IUIControl* anchor, AnchorDirection anchorDirection, int* var, RadioDirection direction = kRadioVertical);
void AddLabel(const char* label, int value);
void SetLabel(const char* label, int value);
void RemoveLabel(int value);
void Render() override;
void SetMultiSelect(bool on) { mMultiSelect = on; }
void Clear();
EnumMap GetEnumMap();
void SetForcedWidth(int width) { mForcedWidth = width; }
void CopyContentsTo(DropdownList* list) const;
bool MouseMoved(float x, float y) override;
static int GetSpacing();
//IUIControl
void SetFromMidiCC(float slider, double time, bool setViaModulator) override;
float GetValueForMidiCC(float slider) const override;
void SetValue(float value, double time, bool forceUpdate = false) override;
void SetValueDirect(float value, double time) override;
float GetValue() const override;
float GetMidiValue() const override;
int GetNumValues() override { return (int)mElements.size(); }
std::string GetDisplayValue(float val) const override;
bool IsBitmask() override { return mMultiSelect; }
bool InvertScrollDirection() override { return mDirection == kRadioVertical; }
void Increment(float amount) override;
void Poll() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, bool shouldSetValue = true) override;
void GetDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
ofVec2f GetOptionPosition(int optionIndex);
protected:
~RadioButton(); //protected so that it can't be created on the stack
private:
void SetIndex(int i, double time);
void CalcSliderVal();
void UpdateDimensions();
void SetValueDirect(float value, double time, bool forceUpdate);
void OnClicked(float x, float y, bool right) override;
int mWidth{ 15 };
int mHeight{ 15 };
float mElementWidth{ 8 };
std::vector<RadioButtonElement> mElements;
int* mVar;
IRadioButtonListener* mOwner;
bool mMultiSelect{ false }; //makes this... not a radio button. mVar becomes a bitmask
RadioDirection mDirection;
float mSliderVal{ 0 };
int mLastSetValue{ 0 };
int mForcedWidth{ -1 };
};
``` | /content/code_sandbox/Source/RadioButton.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 820 |
```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
**/
//
// Amplifier.cpp
// modularSynth
//
// Created by Ryan Challinor on 7/13/13.
//
//
#include "Amplifier.h"
#include "ModularSynth.h"
#include "Profiler.h"
Amplifier::Amplifier()
: IAudioProcessor(gBufferSize)
{
}
void Amplifier::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mGainSlider = new FloatSlider(this, "gain", 5, 2, 110, 15, &mGain, 0, 4);
}
Amplifier::~Amplifier()
{
}
void Amplifier::Process(double time)
{
PROFILER(Amplifier);
IAudioReceiver* target = GetTarget();
if (target == nullptr)
return;
SyncBuffers();
int bufferSize = GetBuffer()->BufferSize();
ChannelBuffer* out = target->GetBuffer();
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
{
auto getBufferChannelCh = GetBuffer()->GetChannel(ch);
if (mEnabled)
{
for (int i = 0; i < bufferSize; ++i)
{
ComputeSliders(i);
gWorkBuffer[i] = getBufferChannelCh[i] * mGain;
}
Add(out->GetChannel(ch), gWorkBuffer, GetBuffer()->BufferSize());
GetVizBuffer()->WriteChunk(gWorkBuffer, GetBuffer()->BufferSize(), ch);
}
else
{
Add(out->GetChannel(ch), getBufferChannelCh, GetBuffer()->BufferSize());
GetVizBuffer()->WriteChunk(getBufferChannelCh, GetBuffer()->BufferSize(), ch);
}
}
GetBuffer()->Reset();
}
void Amplifier::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mGainSlider->Draw();
}
void Amplifier::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void Amplifier::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
``` | /content/code_sandbox/Source/Amplifier.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 564 |
```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
**/
//
// BufferShuffler.h
//
// Created by Ryan Challinor on 6/23/23.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "Checkbox.h"
#include "INoteReceiver.h"
#include "SwitchAndRamp.h"
#include "Push2Control.h"
#include "GridController.h"
class BufferShuffler : public IAudioProcessor, public IDrawableModule, public INoteReceiver, public IFloatSliderListener, public IIntSliderListener, public IDropdownListener, public IPush2GridController, public IGridControllerListener
{
public:
BufferShuffler();
virtual ~BufferShuffler();
static IDrawableModule* Create() { return new BufferShuffler(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void Poll() override;
void CreateUIControls() override;
bool IsResizable() const override { return true; }
void Resize(float w, float h) override
{
mWidth = MAX(w, 245);
mHeight = MAX(h, 85);
}
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//IAudioSource
void Process(double time) override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendCC(int control, int value, int voiceIdx = -1) override {}
//IPush2GridController
bool OnPush2Control(Push2Control* push2, MidiMessageType type, int controlIndex, float midiValue) override;
void UpdatePush2Leds(Push2Control* push2) override;
//IGridControllerListener
void OnControllerPageSelected() override;
void OnGridButton(int x, int y, float velocity, IGridController* grid) override;
void UpdateGridControllerLights(bool force);
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 DropdownUpdated(DropdownList* dropdown, int 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; }
bool HasDebugDraw() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void DrawModuleUnclipped() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void OnClicked(float x, float y, bool right) override;
bool DrawToPush2Screen() override;
float GetFourTetPosition(double time);
enum class PlaybackStyle
{
Normal,
Double,
Half,
Reverse,
DoubleReverse,
HalfReverse,
None
};
int GetWritePositionInSamples(double time);
int GetLengthInSamples();
void DrawBuffer(float x, float y, float w, float h);
void PlayOneShot(int slice);
int GetNumSlices();
float GetSlicePlaybackRate() const;
PlaybackStyle VelocityToPlaybackStyle(int velocity) const;
ChannelBuffer mInputBuffer;
float mWidth{ 245 };
float mHeight{ 85 };
int mNumBars{ 1 };
IntSlider* mNumBarsSlider{ nullptr };
NoteInterval mInterval{ kInterval_8n };
DropdownList* mIntervalSelector{ nullptr };
bool mFreezeInput{ false };
Checkbox* mFreezeInputCheckbox{ nullptr };
PlaybackStyle mPlaybackStyle{ PlaybackStyle::Normal };
DropdownList* mPlaybackStyleDropdown{ nullptr };
float mFourTet{ 0 };
FloatSlider* mFourTetSlider{ nullptr };
int mFourTetSlices{ 4 };
DropdownList* mFourTetSlicesDropdown{ nullptr };
int mQueuedSlice{ -1 };
PlaybackStyle mQueuedPlaybackStyle{ PlaybackStyle::None };
float mPlaybackSampleIndex{ -1 };
double mPlaybackSampleStartTime{ -1 };
double mPlaybackSampleStopTime{ -1 };
GridControlTarget* mGridControlTarget{ nullptr };
bool mUseVelocitySpeedControl{ false };
bool mOnlyPlayWhenTriggered{ false };
float mFourTetSampleIndex{ 0 };
SwitchAndRamp mSwitchAndRamp;
};
``` | /content/code_sandbox/Source/BufferShuffler.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,181 |
```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
**/
/*
==============================================================================
NoteExpressionRouter.h
Created: 19 Dec 2019 10:40:58pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <array>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "INoteSource.h"
#include "TextEntry.h"
#include "exprtk/exprtk.hpp"
class NoteExpressionRouter : public INoteReceiver, public INoteSource, public IDrawableModule, public ITextEntryListener
{
public:
NoteExpressionRouter();
static IDrawableModule* Create() { return new NoteExpressionRouter(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation) override;
void SendCC(int control, int value, int voiceIdx = -1) override;
void TextEntryComplete(TextEntry* entry) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
virtual void SaveLayout(ofxJSONElement& moduleInfo) override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
static const int kMaxDestinations = 5;
AdditionalNoteCable* mDestinationCables[kMaxDestinations]{ nullptr };
float mWidth{ 200 };
float mHeight{ 20 };
private:
exprtk::symbol_table<float> mSymbolTable;
float mSTNote{ 0 }, mSTVelocity{ 0 }; // bound to the symbol table
std::array<exprtk::expression<float>, kMaxDestinations> mExpressions;
TextEntry* mExpressionWidget[kMaxDestinations]{ nullptr };
char mExpressionText[kMaxDestinations][MAX_TEXTENTRY_LENGTH]{};
};
``` | /content/code_sandbox/Source/NoteExpressionRouter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 563 |
```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
**/
/*
==============================================================================
SpaceMouseControl.h
Created: 25 Jan 2021 9:12:45pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <memory>
class ModularSynth;
//==============================================================================
class SpaceMouseMessageWindow
{
public:
explicit SpaceMouseMessageWindow(ModularSynth& theSynth);
~SpaceMouseMessageWindow();
void Poll();
#if BESPOKE_SPACEMOUSE_SUPPORT
private:
struct Impl;
const std::unique_ptr<Impl> d;
#endif
};
#if !BESPOKE_SPACEMOUSE_SUPPORT
inline void SpaceMouseMessageWindow::Poll()
{
}
#endif
``` | /content/code_sandbox/Source/SpaceMouseControl.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 239 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// FMSynth.cpp
// modularSynth
//
// Created by Ryan Challinor on 1/6/13.
//
//
#include "FMSynth.h"
#include "OpenFrameworksPort.h"
#include "SynthGlobals.h"
#include "IAudioReceiver.h"
#include "ModularSynth.h"
#include "Profiler.h"
FMSynth::FMSynth()
: mPolyMgr(this)
, mNoteInputBuffer(this)
, mWriteBuffer(gBufferSize)
{
mVoiceParams.mOscADSRParams.GetA() = 10;
mVoiceParams.mOscADSRParams.GetD() = 0;
mVoiceParams.mOscADSRParams.GetS() = 1;
mVoiceParams.mOscADSRParams.GetR() = 10;
mVoiceParams.mHarmRatioADSRParams.GetA() = 1;
mVoiceParams.mHarmRatioADSRParams.GetD() = 0;
mVoiceParams.mHarmRatioADSRParams.GetS() = 1;
mVoiceParams.mHarmRatioADSRParams.GetR() = 1;
mVoiceParams.mModIdxADSRParams.GetA() = 1;
mVoiceParams.mModIdxADSRParams.GetD() = 0;
mVoiceParams.mModIdxADSRParams.GetS() = 1;
mVoiceParams.mModIdxADSRParams.GetR() = 1;
mVoiceParams.mPhaseOffset0 = 0;
mVoiceParams.mHarmRatio = 1;
mVoiceParams.mModIdx = 0;
mVoiceParams.mPhaseOffset1 = 0;
mVoiceParams.mHarmRatioADSRParams2.GetA() = 1;
mVoiceParams.mHarmRatioADSRParams2.GetD() = 0;
mVoiceParams.mHarmRatioADSRParams2.GetS() = 1;
mVoiceParams.mHarmRatioADSRParams2.GetR() = 1;
mVoiceParams.mModIdxADSRParams2.GetA() = 1;
mVoiceParams.mModIdxADSRParams2.GetD() = 0;
mVoiceParams.mModIdxADSRParams2.GetS() = 1;
mVoiceParams.mModIdxADSRParams2.GetR() = 1;
mVoiceParams.mHarmRatio2 = 1;
mVoiceParams.mModIdx2 = 0;
mVoiceParams.mPhaseOffset2 = 0;
mVoiceParams.mVol = 1.f;
mPolyMgr.Init(kVoiceType_FM, &mVoiceParams);
}
void FMSynth::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mVolSlider = new FloatSlider(this, "vol", 94, 4, 80, 15, &mVoiceParams.mVol, 0, 2);
mAdsrDisplayVol = new ADSRDisplay(this, "adsrosc", 4, 4, 80, 40, &mVoiceParams.mOscADSRParams);
mAdsrDisplayHarm = new ADSRDisplay(this, "adsrharm", 4, 50, 80, 40, &mVoiceParams.mHarmRatioADSRParams);
mAdsrDisplayMod = new ADSRDisplay(this, "adsrmod", 94, 50, 80, 40, &mVoiceParams.mModIdxADSRParams);
mAdsrDisplayHarm2 = new ADSRDisplay(this, "adsrharm2", 4, 127, 80, 40, &mVoiceParams.mHarmRatioADSRParams2);
mAdsrDisplayMod2 = new ADSRDisplay(this, "adsrmod2", 94, 127, 80, 40, &mVoiceParams.mModIdxADSRParams2);
mHarmRatioBaseDropdown = new DropdownList(this, "harmratio", mAdsrDisplayHarm, kAnchor_Below, &mHarmRatioBase);
mHarmRatioBaseDropdown2 = new DropdownList(this, "harmratio2", mAdsrDisplayHarm2, kAnchor_Below, &mHarmRatioBase2);
mHarmSlider = new FloatSlider(this, "tweak", mHarmRatioBaseDropdown, kAnchor_Below, 80, 15, &mHarmRatioTweak, .5f, 2, 3);
mModSlider = new FloatSlider(this, "mod", mAdsrDisplayMod, kAnchor_Below, 80, 15, &mVoiceParams.mModIdx, 0, 20);
mHarmSlider2 = new FloatSlider(this, "tweak2", mHarmRatioBaseDropdown2, kAnchor_Below, 80, 15, &mHarmRatioTweak2, .5f, 2, 3);
mModSlider2 = new FloatSlider(this, "mod2", mAdsrDisplayMod2, kAnchor_Below, 80, 15, &mVoiceParams.mModIdx2, 0, 20);
mPhaseOffsetSlider0 = new FloatSlider(this, "phase0", mVolSlider, kAnchor_Below, 80, 15, &mVoiceParams.mPhaseOffset0, 0, FTWO_PI);
mPhaseOffsetSlider1 = new FloatSlider(this, "phase1", mModSlider, kAnchor_Below, 80, 15, &mVoiceParams.mPhaseOffset1, 0, FTWO_PI);
mPhaseOffsetSlider2 = new FloatSlider(this, "phase2", mModSlider2, kAnchor_Below, 80, 15, &mVoiceParams.mPhaseOffset2, 0, FTWO_PI);
mHarmRatioBaseDropdown->AddLabel(".125", -8);
mHarmRatioBaseDropdown->AddLabel(".2", -5);
mHarmRatioBaseDropdown->AddLabel(".25", -4);
mHarmRatioBaseDropdown->AddLabel(".333", -3);
mHarmRatioBaseDropdown->AddLabel(".5", -2);
mHarmRatioBaseDropdown->AddLabel("1", 1);
mHarmRatioBaseDropdown->AddLabel("2", 2);
mHarmRatioBaseDropdown->AddLabel("3", 3);
mHarmRatioBaseDropdown->AddLabel("4", 4);
mHarmRatioBaseDropdown->AddLabel("8", 8);
mHarmRatioBaseDropdown->AddLabel("16", 16);
mHarmRatioBaseDropdown2->AddLabel(".125", -8);
mHarmRatioBaseDropdown2->AddLabel(".2", -5);
mHarmRatioBaseDropdown2->AddLabel(".25", -4);
mHarmRatioBaseDropdown2->AddLabel(".333", -3);
mHarmRatioBaseDropdown2->AddLabel(".5", -2);
mHarmRatioBaseDropdown2->AddLabel("1", 1);
mHarmRatioBaseDropdown2->AddLabel("2", 2);
mHarmRatioBaseDropdown2->AddLabel("3", 3);
mHarmRatioBaseDropdown2->AddLabel("4", 4);
mHarmRatioBaseDropdown2->AddLabel("8", 8);
mHarmRatioBaseDropdown2->AddLabel("16", 16);
mModSlider->SetMode(FloatSlider::kSquare);
mModSlider2->SetMode(FloatSlider::kSquare);
}
FMSynth::~FMSynth()
{
}
void FMSynth::Process(double time)
{
PROFILER(FMSynth);
IAudioReceiver* target = GetTarget();
if (!mEnabled || target == nullptr)
return;
mNoteInputBuffer.Process(time);
ComputeSliders(0);
int bufferSize = target->GetBuffer()->BufferSize();
assert(bufferSize == gBufferSize);
mWriteBuffer.Clear();
mPolyMgr.Process(time, &mWriteBuffer, bufferSize);
SyncOutputBuffer(mWriteBuffer.NumActiveChannels());
for (int ch = 0; ch < mWriteBuffer.NumActiveChannels(); ++ch)
{
GetVizBuffer()->WriteChunk(mWriteBuffer.GetChannel(ch), mWriteBuffer.BufferSize(), ch);
Add(target->GetBuffer()->GetChannel(ch), mWriteBuffer.GetChannel(ch), gBufferSize);
}
}
void FMSynth::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (!mEnabled)
return;
if (!NoteInputBuffer::IsTimeWithinFrame(time) && GetTarget())
{
mNoteInputBuffer.QueueNote(time, pitch, velocity, voiceIdx, modulation);
return;
}
if (velocity > 0)
{
mPolyMgr.Start(time, pitch, velocity / 127.0f, voiceIdx, modulation);
mVoiceParams.mOscADSRParams.Start(time, 1); //for visualization
}
else
{
mPolyMgr.Stop(time, pitch, voiceIdx);
mVoiceParams.mOscADSRParams.Stop(time); //for visualization
}
if (mDrawDebug)
AddDebugLine("PlayNote(" + ofToString(time / 1000) + ", " + ofToString(pitch) + ", " + ofToString(velocity) + ", " + ofToString(voiceIdx) + ")", 10);
}
void FMSynth::SetEnabled(bool enabled)
{
mEnabled = enabled;
}
void FMSynth::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mAdsrDisplayVol->Draw();
mAdsrDisplayHarm->Draw();
mAdsrDisplayMod->Draw();
mHarmSlider->Draw();
mModSlider->Draw();
mVolSlider->Draw();
mPhaseOffsetSlider0->Draw();
mHarmRatioBaseDropdown->Draw();
mPhaseOffsetSlider1->Draw();
mAdsrDisplayHarm2->Draw();
mAdsrDisplayMod2->Draw();
mHarmSlider2->Draw();
mModSlider2->Draw();
mHarmRatioBaseDropdown2->Draw();
mPhaseOffsetSlider2->Draw();
DrawTextNormal("env", mAdsrDisplayVol->GetPosition(true).x, mAdsrDisplayVol->GetPosition(true).y + 10);
DrawTextNormal("harm", mAdsrDisplayHarm->GetPosition(true).x, mAdsrDisplayHarm->GetPosition(true).y + 10);
DrawTextNormal("mod", mAdsrDisplayMod->GetPosition(true).x, mAdsrDisplayMod->GetPosition(true).y + 10);
DrawTextNormal("harm2", mAdsrDisplayHarm2->GetPosition(true).x, mAdsrDisplayHarm2->GetPosition(true).y + 10);
DrawTextNormal("mod2", mAdsrDisplayMod2->GetPosition(true).x, mAdsrDisplayMod2->GetPosition(true).y + 10);
}
void FMSynth::DrawModuleUnclipped()
{
if (mDrawDebug)
{
float width, height;
GetModuleDimensions(width, height);
mPolyMgr.DrawDebug(width + 3, 0);
DrawTextNormal(mDebugDisplayText, 0, height + 15);
}
}
void FMSynth::UpdateHarmonicRatio()
{
if (mHarmRatioBase < 0)
mVoiceParams.mHarmRatio = 1.0f / (-mHarmRatioBase);
else
mVoiceParams.mHarmRatio = mHarmRatioBase;
mVoiceParams.mHarmRatio *= mHarmRatioTweak;
if (mHarmRatioBase2 < 0)
mVoiceParams.mHarmRatio2 = 1.0f / (-mHarmRatioBase2);
else
mVoiceParams.mHarmRatio2 = mHarmRatioBase2;
mVoiceParams.mHarmRatio2 *= mHarmRatioTweak2;
}
void FMSynth::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mHarmRatioBaseDropdown || list == mHarmRatioBaseDropdown2)
UpdateHarmonicRatio();
}
void FMSynth::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mHarmSlider || slider == mHarmSlider2)
UpdateHarmonicRatio();
}
void FMSynth::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
mPolyMgr.KillAll();
}
void FMSynth::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadInt("voicelimit", moduleInfo, -1, -1, kNumVoices);
EnumMap oversamplingMap;
oversamplingMap["1"] = 1;
oversamplingMap["2"] = 2;
oversamplingMap["4"] = 4;
oversamplingMap["8"] = 8;
mModuleSaveData.LoadEnum<int>("oversampling", moduleInfo, 1, nullptr, &oversamplingMap);
mModuleSaveData.LoadBool("mono", moduleInfo, false);
SetUpFromSaveData();
}
void FMSynth::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
int voiceLimit = mModuleSaveData.GetInt("voicelimit");
if (voiceLimit > 0)
mPolyMgr.SetVoiceLimit(voiceLimit);
else
mPolyMgr.SetVoiceLimit(kNumVoices);
bool mono = mModuleSaveData.GetBool("mono");
mWriteBuffer.SetNumActiveChannels(mono ? 1 : 2);
int oversampling = mModuleSaveData.GetEnum<int>("oversampling");
mPolyMgr.SetOversampling(oversampling);
}
``` | /content/code_sandbox/Source/FMSynth.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 3,157 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.