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
**/
//
// ADSRDisplay.cpp
// modularSynth
//
// Created by Ryan Challinor on 4/28/13.
//
//
#include "ADSRDisplay.h"
#include "SynthGlobals.h"
#include "IDrawableModule.h"
#include "ModularSynth.h"
#include "EnvelopeEditor.h"
#include "PatchCable.h"
#include "IModulator.h"
ADSRDisplay::DisplayMode ADSRDisplay::sDisplayMode = ADSRDisplay::kDisplayEnvelope;
ADSRDisplay::ADSRDisplay(IDrawableModule* owner, const char* name, int x, int y, int w, int h, ::ADSR* adsr)
: mWidth(w)
, mHeight(h)
, mAdsr(adsr)
{
assert(owner);
SetName(name);
SetPosition(x, y);
owner->AddUIControl(this);
SetParent(owner);
IFloatSliderListener* floatListener = dynamic_cast<IFloatSliderListener*>(owner);
assert(floatListener); //make anything that uses an ADSRDisplay a FloatSliderListener for these sliders
if (floatListener)
{
int sliderHeight = h / 4;
mASlider = new FloatSlider(floatListener, (std::string(name) + "A").c_str(), x, y, w, sliderHeight, &(mAdsr->GetA()), 0.001f, 1000);
mDSlider = new FloatSlider(floatListener, (std::string(name) + "D").c_str(), x, y + sliderHeight, w, sliderHeight, &(mAdsr->GetD()), 0.001f, 1000);
mSSlider = new FloatSlider(floatListener, (std::string(name) + "S").c_str(), x, y + sliderHeight * 2, w, sliderHeight, &(mAdsr->GetS()), 0, 1);
mRSlider = new FloatSlider(floatListener, (std::string(name) + "R").c_str(), x, y + sliderHeight * 3, w, sliderHeight, &(mAdsr->GetR()), 0.001f, 1000);
mASlider->SetMode(FloatSlider::kSquare);
mDSlider->SetMode(FloatSlider::kSquare);
mRSlider->SetMode(FloatSlider::kSquare);
mASlider->SetShowName(false);
mDSlider->SetShowName(false);
mSSlider->SetShowName(false);
mRSlider->SetShowName(false);
UpdateSliderVisibility();
}
}
ADSRDisplay::~ADSRDisplay()
{
}
void ADSRDisplay::Render()
{
static bool sSkipDraw = false;
if (sSkipDraw)
return;
UpdateSliderVisibility();
ofPushStyle();
ofPushMatrix();
ofTranslate(mX, mY);
ofSetColor(100, 100, 100, .8f * gModuleDrawAlpha);
ofSetLineWidth(.5f);
ofRect(0, 0, mWidth, mHeight, 0);
if (mAdsr && sDisplayMode == kDisplayEnvelope)
{
ofSetColor(245, 58, 0, gModuleDrawAlpha);
ofSetLineWidth(1);
float timeBeforeSustain = mMaxTime;
float releaseTime = mMaxTime;
if (mAdsr->GetMaxSustain() == -1 && mAdsr->GetHasSustainStage())
{
timeBeforeSustain = 0;
for (int i = 0; i < mAdsr->GetNumStages(); ++i)
{
timeBeforeSustain += mAdsr->GetStageData(i).time;
if (i == mAdsr->GetSustainStage())
break;
}
releaseTime = timeBeforeSustain + mMaxTime * .2f;
}
ADSR::EventInfo adsrEvent(0, releaseTime);
ofBeginShape();
ofVertex(0, mHeight);
for (float i = 0; i < mWidth; i += (.25f / gDrawScale))
{
float time = i / mWidth * mMaxTime;
ofVertex(GetDrawPoint(time, adsrEvent));
}
ofEndShape(false);
if (mAdjustMode == kAdjustAttack ||
mAdjustMode == kAdjustAttackAR ||
mAdjustMode == kAdjustDecaySustain ||
mAdjustMode == kAdjustRelease ||
mAdjustMode == kAdjustReleaseAR)
{
float startTime = 0;
float endTime = 999;
if (mAdjustMode == kAdjustAttack || mAdjustMode == kAdjustAttackAR)
{
startTime = 0;
endTime = mAdsr->GetA();
}
if (mAdjustMode == kAdjustDecaySustain)
{
startTime = mAdsr->GetA();
endTime = releaseTime;
}
if (mAdjustMode == kAdjustRelease)
{
startTime = releaseTime;
endTime = releaseTime + mAdsr->GetR();
}
if (mAdjustMode == kAdjustReleaseAR)
{
startTime = mAdsr->GetA();
endTime = mAdsr->GetA() + mAdsr->GetD();
}
ofSetColor(0, 255, 255);
ofBeginShape();
ofVertex(GetDrawPoint(startTime, adsrEvent));
for (float i = 0; i < mWidth; i += (.25f / gDrawScale))
{
float time = i / mWidth * mMaxTime;
if (time >= startTime && time <= endTime)
ofVertex(GetDrawPoint(time, adsrEvent));
}
ofVertex(GetDrawPoint(MIN(endTime, mMaxTime), adsrEvent));
ofEndShape(false);
}
float drawTime = 0;
if (mOverrideDrawTime != -1)
{
drawTime = mOverrideDrawTime;
}
else
{
if (mAdsr->GetStartTime(gTime) > 0 && mAdsr->GetStartTime(gTime) >= mAdsr->GetStopTime(gTime))
drawTime = ofClamp(gTime - mAdsr->GetStartTime(gTime), 0, releaseTime * mAdsr->GetTimeScale()) / mAdsr->GetTimeScale();
if (mAdsr->GetStopTime(gTime) > mAdsr->GetStartTime(gTime))
drawTime = releaseTime + (gTime - mAdsr->GetStopTime(gTime));
}
ofPushStyle();
ofSetColor(0, 255, 0, gModuleDrawAlpha * .5f);
float x = drawTime / mMaxTime * mWidth;
float y = (1 - mAdsr->Value(drawTime, &adsrEvent) * mVol) * mHeight;
if (drawTime >= timeBeforeSustain && drawTime <= releaseTime)
{
ofSetLineWidth(1.5f);
ofLine(drawTime / mMaxTime * mWidth, y, releaseTime / mMaxTime * mWidth, y);
}
if (drawTime > 0 && drawTime < mMaxTime)
{
ofPushMatrix();
ofClipWindow(0, 0, mWidth, mHeight, true);
ofCircle(x, y, 1);
ofLine(x, y, x, mHeight);
ofPopMatrix();
}
mDrawTimeHistory[mDrawTimeHistoryIndex] = drawTime;
for (size_t i = 0; i < mDrawTimeHistory.size() - 1; ++i)
{
ofFill();
ofSetColor(0, 255, 0, gModuleDrawAlpha * ofLerp(.3f, 0, float(i) / mDrawTimeHistory.size()));
int indexLeading = (mDrawTimeHistoryIndex - i + (int)mDrawTimeHistory.size()) % (int)mDrawTimeHistory.size();
//int indexPast = (indexLeading - 1 + (int)mDrawTimeHistory.size()) % (int)mDrawTimeHistory.size();
double timeLeading = mDrawTimeHistory[indexLeading];
//double timePast = mDrawTimeHistory[indexPast];
float xLeading = timeLeading / mMaxTime * mWidth;
float yLeading = (1 - mAdsr->Value(timeLeading, &adsrEvent) * mVol) * mHeight;
//float xPast = timePast / mMaxTime * mWidth;
//float yPast = (1 - mAdsr->Value(timePast, &adsrEvent) * mVol) * mHeight;
if (xLeading <= mWidth)
ofLine(xLeading, yLeading, xLeading, mHeight);
/*bool discontinuity = false;
if (timeLeading < timePast)
discontinuity = true;
if (timeLeading >= releaseTime - gBufferSizeMs && timePast <= releaseTime)
discontinuity = true;
if (!discontinuity)
{
ofBeginShape();
ofVertex(xLeading, yLeading);
ofVertex(xLeading, mHeight);
ofVertex(xPast, mHeight);
ofVertex(xPast, yPast);
ofEndShape();
}*/
}
mDrawTimeHistoryIndex = (mDrawTimeHistoryIndex + 1) % mDrawTimeHistory.size();
ofPopStyle();
}
ofFill();
if (mHighlighted)
{
ofSetColor(255, 255, 0, .2f * gModuleDrawAlpha);
ofRect(0, 0, mWidth, mHeight, 0);
}
ofSetColor(245, 58, 0, gModuleDrawAlpha);
ofCircle(mWidth - 5, 5, 2);
if (sDisplayMode == kDisplayEnvelope)
{
ofSetColor(0, 255, 255, .2f * gModuleDrawAlpha);
switch (mAdjustMode)
{
case kAdjustAttack:
ofRect(0, 0, 20, mHeight);
break;
case kAdjustDecaySustain:
ofRect(20, 0, mWidth - 40, mHeight);
break;
case kAdjustRelease:
ofRect(mWidth - 20, 0, 20, mHeight);
break;
case kAdjustEnvelopeEditor:
ofSetColor(255, 255, 255, .2f * gModuleDrawAlpha);
ofRect(mWidth - 10, 0, 10, 10);
break;
case kAdjustViewLength:
ofSetColor(255, 255, 255, .2f * gModuleDrawAlpha);
ofRect(0, 0, mWidth, 10);
ofRect(ofMap(mMaxTime, 10, 10000, 0, mWidth - 3, K(clamp)), 0, 3, 10);
ofSetColor(255, 255, 255, .8f * gModuleDrawAlpha);
DrawTextNormal(ofToString(mMaxTime, 0) + " ms", 3, 8, 8);
break;
case kAdjustAttackAR:
ofRect(0, 0, mWidth * .5f, mHeight);
break;
case kAdjustReleaseAR:
ofRect(mWidth * .5f, 0, mWidth * .5f, mHeight);
break;
default:
break;
}
}
ofPopMatrix();
ofPopStyle();
if (mASlider)
{
int sliderHeight = mHeight / 4;
mASlider->SetPosition(mX, mY);
mDSlider->SetPosition(mX, mY + sliderHeight);
mSSlider->SetPosition(mX, mY + sliderHeight * 2);
mRSlider->SetPosition(mX, mY + sliderHeight * 3);
mASlider->Draw();
mDSlider->Draw();
mSSlider->Draw();
mRSlider->Draw();
}
}
ofVec2f ADSRDisplay::GetDrawPoint(float time, const ADSR::EventInfo& adsrEvent)
{
float value = mAdsr->Value(time, &adsrEvent) * mVol;
float x = time / mMaxTime * mWidth;
float y = mHeight * (1 - value);
return ofVec2f(x, y);
}
void ADSRDisplay::SetMaxTime(float maxTime)
{
mMaxTime = maxTime;
if (mASlider)
{
mASlider->SetExtents(mASlider->GetMin(), maxTime);
mDSlider->SetExtents(mDSlider->GetMin(), maxTime);
mRSlider->SetExtents(mRSlider->GetMin(), maxTime);
}
}
void ADSRDisplay::SetADSR(::ADSR* adsr)
{
mAdsr = adsr;
if (mASlider)
{
mASlider->SetVar(&(mAdsr->GetA()));
mDSlider->SetVar(&(mAdsr->GetD()));
mSSlider->SetVar(&(mAdsr->GetS()));
mRSlider->SetVar(&(mAdsr->GetR()));
}
}
void ADSRDisplay::UpdateSliderVisibility()
{
bool slidersActive = false;
if (mAdsr != nullptr && IsShowing())
{
if (sDisplayMode == kDisplaySliders)
slidersActive = true;
if (PatchCable::sActivePatchCable != nullptr &&
(PatchCable::sActivePatchCable->GetConnectionType() == kConnectionType_Modulator || PatchCable::sActivePatchCable->GetConnectionType() == kConnectionType_ValueSetter || PatchCable::sActivePatchCable->GetConnectionType() == kConnectionType_UIControl))
slidersActive = true;
}
if (mASlider && mASlider->GetModulator() != nullptr && mASlider->GetModulator()->Active())
slidersActive = true;
if (mDSlider && mDSlider->GetModulator() != nullptr && mDSlider->GetModulator()->Active())
slidersActive = true;
if (mSSlider && mSSlider->GetModulator() != nullptr && mSSlider->GetModulator()->Active())
slidersActive = true;
if (mRSlider && mRSlider->GetModulator() != nullptr && mRSlider->GetModulator()->Active())
slidersActive = true;
if (mAdsr != nullptr && mASlider)
{
if (mAdsr->IsStandardADSR())
{
mASlider->SetShowing(slidersActive);
mDSlider->SetShowing(slidersActive);
mSSlider->SetShowing(slidersActive);
mRSlider->SetShowing(slidersActive);
}
if (mAdsr->GetNumStages() == 3 && !mAdsr->GetHasSustainStage())
{
mASlider->SetShowing(slidersActive);
mDSlider->SetShowing(slidersActive);
mSSlider->SetShowing(false);
mRSlider->SetShowing(slidersActive);
}
if (mAdsr->GetNumStages() == 2 && !mAdsr->GetHasSustainStage())
{
mASlider->SetShowing(slidersActive);
mDSlider->SetShowing(slidersActive);
mSSlider->SetShowing(false);
mRSlider->SetShowing(false);
}
}
}
//static
void ADSRDisplay::ToggleDisplayMode()
{
sDisplayMode = (sDisplayMode == kDisplayEnvelope) ? kDisplaySliders : kDisplayEnvelope;
}
void ADSRDisplay::SpawnEnvelopeEditor()
{
if (mEditor == nullptr)
{
ModuleFactory::Spawnable spawnable;
spawnable.mLabel = "envelopeeditor";
mEditor = dynamic_cast<EnvelopeEditor*>(TheSynth->SpawnModuleOnTheFly(spawnable, -1, -1, false, "envelopepopup"));
mEditor->SetADSRDisplay(this);
}
if (!mEditor->IsPinned())
{
mEditor->SetPosition(GetPosition().x + mWidth, GetPosition().y);
mEditor->SetOwningContainer(GetModuleParent()->GetOwningContainer());
TheSynth->PushModalFocusItem(mEditor);
}
}
void ADSRDisplay::OnClicked(float x, float y, bool right)
{
if (mASlider != nullptr && mASlider->IsShowing())
{
if (gHoveredUIControl == mASlider)
mASlider->TestClick(x + mX, y + mY, right, false);
if (gHoveredUIControl == mDSlider)
mDSlider->TestClick(x + mX, y + mY, right, false);
if (gHoveredUIControl == mSSlider)
mSSlider->TestClick(x + mX, y + mY, right, false);
if (gHoveredUIControl == mRSlider)
mRSlider->TestClick(x + mX, y + mY, right, false);
return;
}
if (!mShowing)
return;
if (right)
{
//randomize
for (int i = 0; i < mAdsr->GetNumStages(); ++i)
{
if (i == 0)
mAdsr->GetStageData(i).target = 1;
else if (i == mAdsr->GetNumStages() - 1)
mAdsr->GetStageData(i).target = 0;
else
mAdsr->GetStageData(i).target = ofRandom(0, 1);
mAdsr->GetStageData(i).time = ofMap(pow(ofRandom(1), 2), 0, 1, 1, 200);
}
return;
}
if (mAdjustMode == kAdjustEnvelopeEditor)
{
TheSynth->ScheduleEnvelopeEditorSpawn(this);
}
else if (mAdsr->IsStandardADSR() || mAdsr->GetNumStages() == 2)
{
mClick = true;
mClickStart.set(x, y);
mClickAdsr.Set(*mAdsr);
mClickLength = mMaxTime;
}
}
void ADSRDisplay::MouseReleased()
{
mClick = false;
}
bool ADSRDisplay::MouseMoved(float x, float y)
{
if (!mClick)
{
if (x < 0 || y < 0 || x > mWidth || y > mHeight)
{
mAdjustMode = kAdjustNone;
}
else if (GetKeyModifiers() == kModifier_Shift)
{
mAdjustMode = kAdjustViewLength;
}
else if (x >= mWidth - 10 && x <= mWidth && y >= 0 && y <= 10)
{
mAdjustMode = kAdjustEnvelopeEditor;
}
else if (mAdsr->GetNumStages() == 2) //2-stage AR envelope
{
if (x < mWidth / 2)
{
mAdjustMode = kAdjustAttackAR;
}
else
{
mAdjustMode = kAdjustReleaseAR;
}
}
else if (!mAdsr->IsStandardADSR())
{
mAdjustMode = kAdjustNone;
}
else if (x < 20)
{
mAdjustMode = kAdjustAttack;
}
else if (x > mWidth - 20)
{
mAdjustMode = kAdjustRelease;
}
else
{
mAdjustMode = kAdjustDecaySustain;
}
}
if (mClick)
{
if (mAdsr == nullptr)
return false;
float mousePosSq = (x - mClickStart.x) / mWidth;
if (mousePosSq > 0)
mousePosSq *= mousePosSq;
switch (mAdjustMode)
{
case kAdjustViewLength:
{
mMaxTime = std::clamp(mClickLength + mousePosSq * 500, 10.0f, 10000.0f);
break;
}
case kAdjustAttack:
case kAdjustAttackAR:
{
float a = ofClamp(mClickAdsr.GetA() + mousePosSq * mMaxTime * .1f, 1, mMaxTime);
mAdsr->GetA() = a;
break;
}
case kAdjustDecaySustain:
{
float d = ofClamp(mClickAdsr.GetD() + mousePosSq * mMaxTime, 1, mMaxTime);
mAdsr->GetD() = d;
float s = ofClamp(mClickAdsr.GetS() + (mClickStart.y - y) / mHeight, 0, 1);
mAdsr->GetS() = s;
break;
}
case kAdjustRelease:
{
float r = ofClamp(mClickAdsr.GetR() + mousePosSq * mMaxTime, 1, mMaxTime);
mAdsr->GetR() = r;
break;
}
case kAdjustReleaseAR:
{
float r = ofClamp(mClickAdsr.GetD() + mousePosSq * mMaxTime, 1, mMaxTime);
mAdsr->GetD() = r;
break;
}
default:
break;
}
}
return false;
}
namespace
{
const int kSaveStateRev = 1;
}
void ADSRDisplay::SaveState(FileStreamOut& out)
{
out << kSaveStateRev;
mAdsr->SaveState(out);
}
void ADSRDisplay::LoadState(FileStreamIn& in, bool shouldSetValue)
{
int rev;
in >> rev;
LoadStateValidate(rev <= kSaveStateRev);
mAdsr->LoadState(in);
}
``` | /content/code_sandbox/Source/ADSRDisplay.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 4,917 |
```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
**/
//
// Pressure.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 Pressure : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public IAudioPoller
{
public:
Pressure();
virtual ~Pressure();
static IDrawableModule* Create() { return new Pressure(); }
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 mPressure{ 0 };
FloatSlider* mPressureSlider{ nullptr };
Modulations mModulation{ true };
};
``` | /content/code_sandbox/Source/Pressure.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 477 |
```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
**/
/*
==============================================================================
SignalClamp.h
Created: 1 Dec 2019 3:24:55pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "Slider.h"
class SignalClamp : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener
{
public:
SignalClamp();
virtual ~SignalClamp();
static IDrawableModule* Create() { return new SignalClamp(); }
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 = 40;
}
float mMin{ -1 };
FloatSlider* mMinSlider{ nullptr };
float mMax{ 1 };
FloatSlider* mMaxSlider{ nullptr };
};
``` | /content/code_sandbox/Source/SignalClamp.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 435 |
```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
**/
//
// KompleteKontrol.h
// Bespoke
//
// Created by Ryan Challinor on 3/11/15.
//
//
#ifndef __Bespoke__KompleteKontrol__
#define __Bespoke__KompleteKontrol__
#include <iostream>
#include "IDrawableModule.h"
#include "OpenFrameworksPort.h"
#include "Checkbox.h"
#include "Stutter.h"
#include "CFMessaging/KontrolKommunicator.h"
#include "NoteEffectBase.h"
#include "Scale.h"
class MidiController;
#define NUM_SLIDER_SEGMENTS 72
class KompleteKontrol : public IDrawableModule, public NoteEffectBase, public IScaleListener, public IKontrolListener
{
public:
KompleteKontrol();
~KompleteKontrol();
static IDrawableModule* Create() { return new KompleteKontrol(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Poll() override;
void Exit() override;
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
//IScaleListener
void OnScaleChanged() override;
//IKontrolListener
void OnKontrolButton(int control, bool on) override;
void OnKontrolEncoder(int control, float change) override;
void OnKontrolOctave(int octave) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
const int kNumKeys = 61;
bool IsEnabled() const override { return true; }
private:
struct TextBox
{
TextBox()
: slider(false)
, amount(0)
{}
bool slider;
float amount;
std::string line1;
std::string line2;
};
void UpdateKeys();
void UpdateText();
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 100;
height = 18;
}
KontrolKommunicator mKontrol;
bool mInitialized;
int mKeyOffset;
bool mNeedKeysUpdate;
std::string mCurrentText;
uint16_t mCurrentSliders[NUM_SLIDER_SEGMENTS];
TextBox mTextBoxes[9];
MidiController* mController;
PatchCableSource* mMidiControllerCable;
};
#endif /* defined(__Bespoke__KompleteKontrol__) */
``` | /content/code_sandbox/Source/KompleteKontrol.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 692 |
```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
**/
//
// OutputChannel.h
// modularSynth
//
// Created by Ryan Challinor on 12/17/12.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "DropdownList.h"
#include "PeakTracker.h"
class OutputChannel : public IAudioProcessor, public IDrawableModule, public IDropdownListener
{
public:
OutputChannel();
virtual ~OutputChannel();
static IDrawableModule* Create() { return new OutputChannel(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IAudioReceiver
InputMode GetInputMode() override { return mChannelSelectionIndex < mStereoSelectionOffset ? kInputMode_Mono : kInputMode_Multichannel; }
//IAudioSource
void Process(double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override {}
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
int GetNumChannels() const { return mChannelSelectionIndex < mStereoSelectionOffset ? 1 : 2; }
float mWidth{ 64 };
float mHeight{ 40 };
DropdownList* mChannelSelector{ nullptr };
int mChannelSelectionIndex{ 0 };
int mStereoSelectionOffset{ 0 };
float mLimit{ 1 };
struct LevelMeter
{
PeakTracker mPeakTracker;
PeakTracker mPeakTrackerSlow;
};
std::array<LevelMeter, 2> mLevelMeters;
};
``` | /content/code_sandbox/Source/OutputChannel.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 537 |
```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
**/
//
// DistortionEffect.h
// modularSynth
//
// Created by Ryan Challinor on 12/2/12.
//
//
#pragma once
#include <iostream>
#include "IAudioEffect.h"
#include "Checkbox.h"
#include "Slider.h"
#include "DropdownList.h"
#include "BiquadFilter.h"
#include "PeakTracker.h"
class DistortionEffect : public IAudioEffect, public IFloatSliderListener, public IDropdownListener
{
public:
DistortionEffect();
static IAudioEffect* Create() { return new DistortionEffect(); }
void CreateUIControls() override;
void SetClip(float amount);
//IAudioEffect
void ProcessAudio(double time, ChannelBuffer* buffer) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
float GetEffectAmount() override;
std::string GetType() override { return "distortion"; }
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override {}
bool IsEnabled() const override { return mEnabled; }
private:
enum DistortionType
{
kClean,
kWarm,
kDirty,
kSoft,
kAsymmetric,
kFold,
kGrungy
};
//IDrawableModule
void GetModuleDimensions(float& width, float& height) override;
void DrawModule() override;
float mWidth{ 200 };
float mHeight{ 20 };
DistortionType mType{ DistortionType::kClean };
float mClip{ 1 };
float mGain{ 1 };
float mPreamp{ 1 };
float mFuzzAmount{ 0 };
bool mRemoveInputDC{ true };
DropdownList* mTypeDropdown{ nullptr };
FloatSlider* mClipSlider{ nullptr };
FloatSlider* mPreampSlider{ nullptr };
Checkbox* mRemoveInputDCCheckbox{ nullptr };
FloatSlider* mFuzzAmountSlider{ nullptr };
BiquadFilter mDCRemover[ChannelBuffer::kMaxNumChannels]{};
PeakTracker mPeakTracker[ChannelBuffer::kMaxNumChannels]{};
};
``` | /content/code_sandbox/Source/DistortionEffect.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 592 |
```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
**/
//
// Created by block on 8/6/2022.
//
#pragma once
#include <iostream>
#include "IAudioReceiver.h"
#include "INoteSource.h"
#include "Slider.h"
#include "IDrawableModule.h"
#include "RadioButton.h"
#include "BiquadFilter.h"
#include "Scale.h"
#include "IAudioSource.h"
#include "IPulseReceiver.h"
#include "IAudioPoller.h"
class BoundsToPulse : public IDrawableModule, public IFloatSliderListener, public IPulseSource, public IAudioPoller
{
public:
BoundsToPulse();
virtual ~BoundsToPulse();
static IDrawableModule* Create() { return new BoundsToPulse(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void Init() override;
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void OnTransportAdvanced(float amount) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
float GetValue() const { return mValue; }
FloatSlider* GetSlider() { return mSlider; }
private:
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 110;
height = 40;
}
FloatSlider* mSlider;
float mValue;
PatchCableSource* mMinCable{};
PatchCableSource* mMaxCable{};
};
``` | /content/code_sandbox/Source/BoundsToPulse.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 441 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// PitchDive.cpp
// Bespoke
//
// Created by Ryan Challinor on 12/27/15.
//
//
#include "PitchDive.h"
#include "OpenFrameworksPort.h"
#include "ModularSynth.h"
PitchDive::PitchDive()
: mStart(0)
, mStartSlider(nullptr)
, mTime(0)
, mTimeSlider(nullptr)
, mModulation(false)
{
}
PitchDive::~PitchDive()
{
}
void PitchDive::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mStartSlider = new FloatSlider(this, "start", 5, 2, 110, 15, &mStart, -3, 3);
mTimeSlider = new FloatSlider(this, "time", 5, 20, 110, 15, &mTime, 0, 1000);
mTimeSlider->SetMode(FloatSlider::kSquare);
}
void PitchDive::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mStartSlider->Draw();
mTimeSlider->Draw();
}
void PitchDive::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mEnabled && velocity > 0 && mStart != 0 && mTime != 0)
{
ComputeSliders(0);
auto* pitchBend = mModulation.GetPitchBend(voiceIdx);
pitchBend->RampValue(time, mStart, 0, mTime);
pitchBend->AppendTo(modulation.pitchBend);
modulation.pitchBend = pitchBend;
}
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
void PitchDive::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void PitchDive::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void PitchDive::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void PitchDive::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/PitchDive.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 581 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// PolyphonyMgr.cpp
// additiveSynth
//
// Created by Ryan Challinor on 11/20/12.
//
//
#include "PolyphonyMgr.h"
#include "IMidiVoice.h"
#include "FMVoice.h"
#include "KarplusStrongVoice.h"
#include "SingleOscillatorVoice.h"
#include "SampleVoice.h"
#include "SynthGlobals.h"
#include "Profiler.h"
ChannelBuffer gMidiVoiceWorkChannelBuffer(kWorkBufferSize);
PolyphonyMgr::PolyphonyMgr(IDrawableModule* owner)
: mOwner(owner)
{
}
PolyphonyMgr::~PolyphonyMgr()
{
for (int i = 0; i < kNumVoices; ++i)
delete mVoices[i].mVoice;
}
void PolyphonyMgr::Init(VoiceType type, IVoiceParams* params)
{
if (type == kVoiceType_FM)
{
for (int i = 0; i < kNumVoices; ++i)
{
mVoices[i].mVoice = new FMVoice(mOwner);
mVoices[i].mVoice->SetVoiceParams(params);
}
}
else if (type == kVoiceType_Karplus)
{
for (int i = 0; i < kNumVoices; ++i)
{
mVoices[i].mVoice = new KarplusStrongVoice(mOwner);
mVoices[i].mVoice->SetVoiceParams(params);
}
}
else if (type == kVoiceType_SingleOscillator)
{
for (int i = 0; i < kNumVoices; ++i)
{
mVoices[i].mVoice = new SingleOscillatorVoice(mOwner);
mVoices[i].mVoice->SetVoiceParams(params);
}
}
else if (type == kVoiceType_Sampler)
{
for (int i = 0; i < kNumVoices; ++i)
{
mVoices[i].mVoice = new SampleVoice(mOwner);
mVoices[i].mVoice->SetVoiceParams(params);
}
}
else
{
assert(false); //unsupported voice type
}
}
void PolyphonyMgr::Start(double time, int pitch, float amount, int voiceIdx, ModulationParameters modulation)
{
assert(voiceIdx < kNumVoices);
bool preserveVoice = voiceIdx != -1 && //we specified a voice
mVoices[voiceIdx].mPitch != -1; //there is a note playing from that voice
if (voiceIdx == -1) //need a new voice
{
for (int i = 0; i < mVoiceLimit; ++i)
{
int check = (i + mLastVoice + 1) % mVoiceLimit; //try to keep incrementing through list to allow old voices to finish
if (mVoices[check].mPitch == -1)
{
voiceIdx = check;
break;
}
}
}
if (voiceIdx == -1) //all used
{
if (mAllowStealing)
{
double oldest = mVoices[0].mTime;
int oldestIndex = 0;
for (int i = 1; i < mVoiceLimit; ++i)
{
if (mVoices[i].mTime < oldest)
{
oldest = mVoices[i].mTime;
oldestIndex = i;
}
}
voiceIdx = oldestIndex;
}
else
{
return;
}
}
IMidiVoice* voice = mVoices[voiceIdx].mVoice;
assert(voice);
if (!voice->IsDone(time) && (!preserveVoice || modulation.pan != voice->GetPan()))
{
//ofLog() << "fading stolen voice " << voiceIdx << " at " << time;
mFadeOutWorkBuffer.Clear();
voice->Process(time, &mFadeOutWorkBuffer, mOversampling);
for (int i = 0; i < kVoiceFadeSamples; ++i)
{
float fade = 1 - (float(i) / kVoiceFadeSamples);
for (int ch = 0; ch < mFadeOutBuffer.NumActiveChannels(); ++ch)
mFadeOutBuffer.GetChannel(ch)[(i + mFadeOutBufferPos) % kVoiceFadeSamples] += mFadeOutWorkBuffer.GetChannel(ch)[i] * fade;
}
}
if (!preserveVoice)
voice->ClearVoice();
voice->SetPitch(pitch);
voice->SetModulators(modulation);
voice->Start(time, amount);
voice->SetPan(modulation.pan);
mLastVoice = voiceIdx;
mVoices[voiceIdx].mPitch = pitch;
mVoices[voiceIdx].mTime = time;
mVoices[voiceIdx].mNoteOn = true;
}
void PolyphonyMgr::Stop(double time, int pitch, int voiceIdx)
{
if (voiceIdx == -1)
{
double oldest = std::numeric_limits<double>::max();
for (int i = 0; i < mVoiceLimit; ++i)
{
if (mVoices[i].mPitch == pitch && mVoices[i].mNoteOn && mVoices[i].mTime < oldest)
{
oldest = mVoices[i].mTime;
voiceIdx = i;
}
}
}
if (voiceIdx > -1 && mVoices[voiceIdx].mPitch == pitch && mVoices[voiceIdx].mNoteOn)
{
mVoices[voiceIdx].mVoice->Stop(time);
mVoices[voiceIdx].mNoteOn = false;
}
}
void PolyphonyMgr::KillAll()
{
for (int i = 0; i < kNumVoices; ++i)
{
mVoices[i].mVoice->ClearVoice();
mVoices[i].mNoteOn = false;
}
}
void PolyphonyMgr::Process(double time, ChannelBuffer* out, int bufferSize)
{
PROFILER(PolyphonyMgr);
mFadeOutBuffer.SetNumActiveChannels(out->NumActiveChannels());
mFadeOutWorkBuffer.SetNumActiveChannels(out->NumActiveChannels());
float debugRef = 0;
for (int i = 0; i < mVoiceLimit; ++i)
{
if (mVoices[i].mPitch != -1)
{
mVoices[i].mVoice->Process(time, out, mOversampling);
float testSample = out->GetChannel(0)[0];
mVoices[i].mActivity = testSample - debugRef;
if (!mVoices[i].mNoteOn && mVoices[i].mVoice->IsDone(time))
mVoices[i].mPitch = -1;
debugRef = testSample;
}
}
for (int ch = 0; ch < out->NumActiveChannels(); ++ch)
{
for (int i = 0; i < bufferSize; ++i)
{
int fadeOutIdx = (i + mFadeOutBufferPos) % kVoiceFadeSamples;
out->GetChannel(ch)[i] += mFadeOutBuffer.GetChannel(ch)[fadeOutIdx];
mFadeOutBuffer.GetChannel(ch)[fadeOutIdx] = 0;
}
}
mFadeOutBufferPos += bufferSize;
}
void PolyphonyMgr::DrawDebug(float x, float y)
{
ofPushMatrix();
ofPushStyle();
ofTranslate(x, y);
for (int i = 0; i < kNumVoices; ++i)
{
if (mVoices[i].mPitch == -1)
ofSetColor(100, 100, 100);
else if (mVoices[i].mNoteOn)
ofSetColor(0, 255, 0);
else
ofSetColor(255, 0, 0);
std::string outputLine = "voice " + ofToString(i);
if (mVoices[i].mPitch == -1)
outputLine += " unused";
else
outputLine += " used: " + ofToString(mVoices[i].mPitch) + (mVoices[i].mNoteOn ? " (note on)" : " (note off)");
outputLine += " " + ofToString(mVoices[i].mActivity, 3);
DrawTextNormal(outputLine, 0, i * 18);
}
ofPopStyle();
ofPopMatrix();
}
``` | /content/code_sandbox/Source/PolyphonyMgr.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,956 |
```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
**/
/*
==============================================================================
ModulatorCurve.h
Created: 29 Nov 2017 8:56:47pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "Slider.h"
#include "IModulator.h"
#include "EnvelopeEditor.h"
class PatchCableSource;
class ModulatorCurve : public IDrawableModule, public IFloatSliderListener, public IModulator
{
public:
ModulatorCurve();
virtual ~ModulatorCurve();
static IDrawableModule* Create() { return new ModulatorCurve(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
//IModulator
float Value(int samplesIn = 0) override;
bool Active() const override { return mEnabled; }
FloatSlider* GetTarget() { return GetSliderTarget(); }
void MouseReleased() override;
bool MouseMoved(float x, float y) override;
//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 = 121;
}
void OnClicked(float x, float y, bool right) override;
float mInput{ 0 };
EnvelopeControl mEnvelopeControl{ ofVec2f(3, 19), ofVec2f(100, 100) };
::ADSR mAdsr;
FloatSlider* mInputSlider{ nullptr };
};
``` | /content/code_sandbox/Source/ModulatorCurve.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 606 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
ModulatorAdd.cpp
Created: 19 Nov 2017 2:04:24pm
Author: Ryan Challinor
==============================================================================
*/
#include "ModulatorAdd.h"
#include "Profiler.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
ModulatorAdd::ModulatorAdd()
{
}
void ModulatorAdd::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mValue1Slider = new FloatSlider(this, "value 1", 3, 2, 100, 15, &mValue1, 0, 1);
mValue2Slider = new FloatSlider(this, "value 2", mValue1Slider, kAnchor_Below, 100, 15, &mValue2, 0, 1);
mTargetCable = new PatchCableSource(this, kConnectionType_Modulator);
mTargetCable->SetModulatorOwner(this);
AddPatchCableSource(mTargetCable);
}
ModulatorAdd::~ModulatorAdd()
{
}
void ModulatorAdd::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mValue1Slider->Draw();
mValue2Slider->Draw();
}
void ModulatorAdd::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
OnModulatorRepatch();
if (GetSliderTarget() && fromUserClick)
{
mValue1 = GetSliderTarget()->GetValue();
mValue2 = 0;
mValue1Slider->SetExtents(GetSliderTarget()->GetMin(), GetSliderTarget()->GetMax());
mValue1Slider->SetMode(GetSliderTarget()->GetMode());
}
}
float ModulatorAdd::Value(int samplesIn)
{
ComputeSliders(samplesIn);
if (GetSliderTarget())
return ofClamp(mValue1 + mValue2, GetSliderTarget()->GetMin(), GetSliderTarget()->GetMax());
else
return mValue1 + mValue2;
}
void ModulatorAdd::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void ModulatorAdd::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void ModulatorAdd::SetUpFromSaveData()
{
}
``` | /content/code_sandbox/Source/ModulatorAdd.cpp | 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
**/
//
// IClickable.h
// modularSynth
//
// Created by Ryan Challinor on 12/3/12.
//
//
#pragma once
#include "SynthGlobals.h"
//TODO(Ryan) factor Transformable stuff out of here
class IDrawableModule;
class IClickable
{
public:
IClickable();
virtual ~IClickable() {}
void Draw();
virtual void Render() {}
void SetPosition(float x, float y)
{
mX = x;
mY = y;
}
void GetPosition(float& x, float& y, bool local = false) const;
ofVec2f GetPosition(bool local = false) const;
virtual void Move(float moveX, float moveY)
{
mX += moveX;
mY += moveY;
}
virtual bool TestClick(float x, float y, bool right, bool testOnly = false);
IClickable* GetParent() const { return mParent; }
void SetParent(IClickable* parent) { mParent = parent; }
bool NotifyMouseMoved(float x, float y);
bool NotifyMouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll);
virtual void MouseReleased() {}
virtual void GetDimensions(float& width, float& height)
{
width = 10;
height = 10;
}
ofVec2f GetDimensions();
ofRectangle GetRect(bool local = false);
void SetName(const char* name)
{
if (mName != name)
StringCopy(mName, name, MAX_TEXTENTRY_LENGTH);
}
const char* Name() const { return mName; }
char* NameMutable() { return mName; }
std::string Path(bool ignoreContext = false, bool useDisplayName = false);
virtual bool CheckNeedsDraw();
virtual void SetShowing(bool showing) { mShowing = showing; }
bool IsShowing() const { return mShowing; }
virtual void StartBeacon() { mBeaconTime = gTime; }
float GetBeaconAmount() const;
void DrawBeacon(int x, int y);
IClickable* GetRootParent();
IDrawableModule* GetModuleParent();
void SetOverrideDisplayName(std::string name)
{
mHasOverrideDisplayName = true;
mOverrideDisplayName = name;
}
std::string GetDisplayName()
{
return mHasOverrideDisplayName ? mOverrideDisplayName : mName;
}
static void SetLoadContext(IClickable* context) { sPathLoadContext = context->Path() + "~"; }
static void ClearLoadContext() { sPathLoadContext = ""; }
static void SetSaveContext(IClickable* context) { sPathSaveContext = context->Path() + "~"; }
static void ClearSaveContext() { sPathSaveContext = ""; }
static std::string sPathLoadContext;
static std::string sPathSaveContext;
protected:
virtual void OnClicked(float x, float y, bool right) {}
virtual bool MouseMoved(float x, float y) { return false; }
virtual bool MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) { return false; }
float mX{ 0 };
float mY{ 0 };
IClickable* mParent{ nullptr };
bool mShowing{ true };
private:
char mName[MAX_TEXTENTRY_LENGTH]{};
double mBeaconTime{ -999 };
bool mHasOverrideDisplayName{ false };
std::string mOverrideDisplayName{ "" };
};
class IKeyboardFocusListener
{
public:
virtual ~IKeyboardFocusListener() {}
static void SetActiveKeyboardFocus(IKeyboardFocusListener* focus) { sCurrentKeyboardFocus = focus; }
static IKeyboardFocusListener* GetActiveKeyboardFocus() { return sCurrentKeyboardFocus; }
static void ClearActiveKeyboardFocus(bool notifyListeners);
virtual void OnKeyPressed(int key, bool isRepeat) = 0;
virtual bool ShouldConsumeKey(int key) { return true; }
virtual bool CanTakeFocus() { return true; }
static IKeyboardFocusListener* sKeyboardFocusBeforeClick;
private:
virtual void AcceptEntry(bool pressedEnter) {}
virtual void CancelEntry() {}
static IKeyboardFocusListener* sCurrentKeyboardFocus;
};
``` | /content/code_sandbox/Source/IClickable.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,038 |
```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
**/
//
// Chord.h
// modularSynth
//
// Created by Ryan Challinor on 12/16/13.
//
//
#pragma once
#include "OpenFrameworksPort.h"
struct ScalePitches;
enum ChordType
{
kChord_Maj = 0x1,
kChord_Min = 0x2,
kChord_Aug = 0x4,
kChord_Dim = 0x8,
kChord_Unknown = 0xff
};
struct Chord
{
Chord() {}
Chord(std::string name);
Chord(int pitch, ChordType type, int inversion = 0)
: mRootPitch(pitch)
, mType(type)
, mInversion(inversion)
{}
int mRootPitch{ 0 };
ChordType mType{ kChord_Unknown };
int mInversion{ 0 };
std::string Name(bool withDegree, bool withAccidentals, ScalePitches* scale = nullptr);
void SetFromDegreeAndScale(int degree, const ScalePitches& scale, int inversion = 0);
};
``` | /content/code_sandbox/Source/Chord.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 343 |
```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
**/
//
// RhythmSequencer.h
// Bespoke
//
// Created by Ryan Challinor on 12/5/23.
//
//
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Transport.h"
#include "Checkbox.h"
#include "DropdownList.h"
#include "ClickButton.h"
#include "Slider.h"
#include "INoteReceiver.h"
#include "IPulseReceiver.h"
#include "IDrivableSequencer.h"
class RhythmSequencer : public IDrawableModule, public ITimeListener, public NoteEffectBase, public IPulseReceiver, public IDrivableSequencer, public IButtonListener, public IDropdownListener, public IIntSliderListener, public IFloatSliderListener
{
public:
RhythmSequencer();
~RhythmSequencer();
static IDrawableModule* Create() { return new RhythmSequencer(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return true; }
void CreateUIControls() override;
void Init() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
//ITimeListener
void OnTimeEvent(double time) override;
//IPulseReceiver
void OnPulse(double time, float velocity, int flags) override;
//IDrivableSequencer
bool HasExternalPulseSource() const override { return mHasExternalPulseSource; }
void ResetExternalPulseSource() override { mHasExternalPulseSource = false; }
//IButtonListener
void ButtonClicked(ClickButton* button, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 0; }
bool IsEnabled() const override { return mEnabled; }
private:
void Step(double time, float velocity, int pulseFlags);
int GetArpIndex(double time, int current, int length, int pulseFlags);
bool DoesStepHold(int index, int depth) const;
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
float mWidth{ 160 };
float mHeight{ 160 };
bool mHasExternalPulseSource{ false };
static constexpr int kMaxSteps = 8;
enum class StepAction
{
On,
Hold,
Off
};
struct StepData
{
StepAction mAction{ StepAction::On };
DropdownList* mActionSelector{ nullptr };
float mVel{ 1.0f };
FloatSlider* mVelSlider{ nullptr };
int mOctave{ 0 };
IntSlider* mOctaveSlider{ nullptr };
int mDegree{ 0 };
DropdownList* mDegreeSelector{ nullptr };
};
std::array<StepData, kMaxSteps> mStepData{};
NoteInterval mInterval{ NoteInterval::kInterval_16n };
int mArpIndex{ -1 };
int mArpIndexAction{ -1 };
int mArpIndexVel{ -1 };
int mArpIndexOctave{ -1 };
int mArpIndexDegree{ -1 };
DropdownList* mIntervalSelector{ nullptr };
int mLength{ kMaxSteps };
int mLengthAction{ kMaxSteps };
int mLengthVel{ kMaxSteps };
int mLengthOctave{ kMaxSteps };
int mLengthDegree{ kMaxSteps };
IntSlider* mLengthSlider{ nullptr };
IntSlider* mLengthActionSlider{ nullptr };
IntSlider* mLengthVelSlider{ nullptr };
IntSlider* mLengthOctaveSlider{ nullptr };
IntSlider* mLengthDegreeSlider{ nullptr };
bool mLinkLengths{ true };
Checkbox* mLinkLengthsCheckbox{ nullptr };
TransportListenerInfo* mTransportListenerInfo{ nullptr };
std::array<bool, 128> mInputPitches{};
};
``` | /content/code_sandbox/Source/RhythmSequencer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,148 |
```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
**/
//
// Profiler.h
// modularSynth
//
// Created by Ryan Challinor on 2/28/14.
//
//
#pragma once
#include "OpenFrameworksPort.h"
#define PROFILER_HISTORY_LENGTH 500
#define PROFILER_MAX_TRACK 100
#define PROFILER(profile_id) \
static uint32_t profile_id##_hash = JenkinsHash(#profile_id); \
Profiler profilerScopeHolder(#profile_id, profile_id##_hash)
class Profiler
{
public:
Profiler(const char* name, uint32_t hash);
~Profiler();
static void PrintCounters();
static void Draw();
static void ToggleProfiler();
private:
static long GetSafeFrameLengthNanoseconds();
struct Cost
{
void EndFrame();
unsigned long long MaxCost() const;
std::string mName;
uint32_t mHash{ 0 };
unsigned long long mFrameCost{ 0 };
unsigned long long mHistory[PROFILER_HISTORY_LENGTH]{};
int mHistoryIdx{ 0 };
};
unsigned long long mTimerStart{ 0 };
int mIndex{ -1 };
static Cost sCosts[PROFILER_MAX_TRACK];
static bool sEnableProfiler;
};
``` | /content/code_sandbox/Source/Profiler.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 359 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// IClickable.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/3/12.
//
//
#include "IClickable.h"
#include "SynthGlobals.h"
#include "IDrawableModule.h"
#include "Prefab.h"
#include <cstring>
std::string IClickable::sPathLoadContext = "";
std::string IClickable::sPathSaveContext = "";
IClickable::IClickable()
{
}
void IClickable::Draw()
{
if (!mShowing)
return;
Render();
}
bool IClickable::TestClick(float x, float y, bool right, bool testOnly /* = false */)
{
if (!mShowing)
return false;
float w, h;
GetDimensions(w, h);
float titleBarHeight = 0;
IDrawableModule* module = dynamic_cast<IDrawableModule*>(this);
if (module && module->HasTitleBar())
titleBarHeight = IDrawableModule::TitleBarHeight();
if (x >= mX && y >= mY - titleBarHeight && x <= mX + w && y <= mY + h)
{
if (!testOnly)
OnClicked(x - mX, y - mY, right);
return true;
}
return false;
}
bool IClickable::NotifyMouseMoved(float x, float y)
{
if (!mShowing)
return false;
return MouseMoved(x - mX, y - mY);
}
bool IClickable::NotifyMouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll)
{
if (!mShowing)
return false;
return MouseScrolled(x - mX, y - mY, scrollX, scrollY, isSmoothScroll, isInvertedScroll);
}
void IClickable::GetPosition(float& x, float& y, bool local /*= false*/) const
{
if (mParent && !local)
{
mParent->GetPosition(x, y, false);
x += mX;
y += mY;
}
else
{
x = mX;
y = mY;
}
}
ofVec2f IClickable::GetPosition(bool local /*= false*/) const
{
float x, y;
GetPosition(x, y, local);
return ofVec2f(x, y);
}
ofVec2f IClickable::GetDimensions()
{
float w, h;
GetDimensions(w, h);
return ofVec2f(w, h);
}
ofRectangle IClickable::GetRect(bool local /*=false*/)
{
float x, y, w, h;
GetPosition(x, y, local);
GetDimensions(w, h);
return ofRectangle(x, y, w, h);
}
IClickable* IClickable::GetRootParent()
{
IClickable* parent = this;
while (parent->GetParent()) //keep going up until there are no parents
parent = parent->GetParent();
return parent;
}
IDrawableModule* IClickable::GetModuleParent()
{
IClickable* parent = this;
while (parent->GetParent()) //keep going up until there are no parents
{
IDrawableModule* module = dynamic_cast<IDrawableModule*>(parent);
if (module && module->CanMinimize()) //"minimizable" modules doesn't include effects in effectchains, which we want to avoid
return module;
parent = parent->GetParent();
}
return dynamic_cast<IDrawableModule*>(parent);
}
std::string IClickable::Path(bool ignoreContext, bool useDisplayName)
{
if (mName[0] == 0) //must have a name
return "";
std::string name = useDisplayName ? GetDisplayName() : mName;
std::string path = name;
if (mParent != nullptr)
path = mParent->Path(true) + "~" + name;
if (!ignoreContext)
{
if (sPathLoadContext != "")
{
if (path[0] == '$')
{
if (Prefab::sLoadingPrefab)
path = "";
else
path = path.substr(1, path.length() - 1);
}
else
{
path = sPathLoadContext + path;
}
}
if (sPathSaveContext != "")
{
if (strstr(path.c_str(), sPathSaveContext.c_str()) == path.c_str()) //path starts with sSaveContext
path = path.substr(sPathSaveContext.length(), path.length() - sPathSaveContext.length());
else
path = "$" + path; //path is outside of our context, and therefore invalid
}
}
return path;
}
bool IClickable::CheckNeedsDraw()
{
return mShowing;
}
float IClickable::GetBeaconAmount() const
{
return ofClamp(((mBeaconTime + 250) - gTime) / 250, 0, 1);
}
void IClickable::DrawBeacon(int x, int y)
{
float size = GetBeaconAmount();
if (size > 0)
{
ofPushStyle();
ofFill();
ofSetColor(255, 255, 0, 40);
ofCircle(x, y, size * 40);
ofSetColor(255, 255, 0, 150);
ofCircle(x, y, size * 3);
ofPopStyle();
}
}
``` | /content/code_sandbox/Source/IClickable.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,279 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// WaveformViewer.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/19/12.
//
//
#include "WaveformViewer.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "Scale.h"
WaveformViewer::WaveformViewer()
: IAudioProcessor(gBufferSize)
{
mBufferVizOffset[0] = 0;
mBufferVizOffset[1] = 0;
mVizPhase[0] = 0;
mVizPhase[1] = 0;
for (int i = 0; i < BUFFER_VIZ_SIZE; ++i)
{
for (int j = 0; j < 2; ++j)
mAudioView[i][j] = 0;
}
}
void WaveformViewer::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mDisplayFreqEntry = new TextEntry(this, "freq", 3, 3, 10, &mDisplayFreq, 1, 10000);
mLengthSamplesSlider = new IntSlider(this, "length", mDisplayFreqEntry, kAnchor_Below, 100, 15, &mLengthSamples, 1024, BUFFER_VIZ_SIZE);
mDrawGainSlider = new FloatSlider(this, "draw gain", mLengthSamplesSlider, kAnchor_Below, 100, 15, &mDrawGain, .1f, 5);
mDisplayFreqEntry->DrawLabel(true);
/*mHueNote = new FloatSlider(this,"note",5,0,100,15,&IDrawableModule::sHueNote,0,255);
mHueAudio = new FloatSlider(this,"audio",5,15,100,15,&IDrawableModule::sHueAudio,0,255);
mHueInstrument = new FloatSlider(this,"instrument",110,0,100,15,&IDrawableModule::sHueInstrument,0,255);
mHueNoteSource = new FloatSlider(this,"notesource",110,15,100,15,&IDrawableModule::sHueNoteSource,0,255);
mSaturation = new FloatSlider(this,"saturation",215,0,100,15,&IDrawableModule::sSaturation,0,255);
mBrightness = new FloatSlider(this,"brightness",215,15,100,15,&IDrawableModule::sBrightness,0,255);*/
}
WaveformViewer::~WaveformViewer()
{
}
void WaveformViewer::Process(double time)
{
PROFILER(WaveformViewer);
SyncBuffers();
if (mEnabled)
{
ComputeSliders(0);
int lengthSamples = MIN(mLengthSamples, BUFFER_VIZ_SIZE);
int bufferSize = GetBuffer()->BufferSize();
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
{
if (ch == 0)
BufferCopy(gWorkBuffer, GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize());
else
Add(gWorkBuffer, GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize());
}
for (int i = 0; i < bufferSize; ++i)
mAudioView[(i + mBufferVizOffset[!mDoubleBufferFlip]) % lengthSamples][!mDoubleBufferFlip] = gWorkBuffer[i];
float vizPhaseInc = GetPhaseInc(mDisplayFreq / 2);
mVizPhase[!mDoubleBufferFlip] += vizPhaseInc * bufferSize;
while (mVizPhase[!mDoubleBufferFlip] > FTWO_PI)
{
mVizPhase[!mDoubleBufferFlip] -= FTWO_PI;
}
mBufferVizOffset[!mDoubleBufferFlip] = (mBufferVizOffset[!mDoubleBufferFlip] + bufferSize) % lengthSamples;
}
IAudioReceiver* target = GetTarget();
if (target)
{
ChannelBuffer* out = target->GetBuffer();
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
{
Add(out->GetChannel(ch), GetBuffer()->GetChannel(ch), out->BufferSize());
GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize(), ch);
}
}
GetBuffer()->Reset();
}
void WaveformViewer::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mDisplayFreqEntry->Draw();
mLengthSamplesSlider->Draw();
mDrawGainSlider->Draw();
/*mHueNote->Draw();
mHueAudio->Draw();
mHueInstrument->Draw();
mHueNoteSource->Draw();
mSaturation->Draw();
mBrightness->Draw();*/
if (!mEnabled)
return;
ofPushStyle();
ofPushMatrix();
ofSetColor(245, 58, 135);
ofSetLineWidth(2);
float w, h;
GetDimensions(w, h);
int lengthSamples = MIN(mLengthSamples, BUFFER_VIZ_SIZE);
float vizPhaseInc = GetPhaseInc(mDisplayFreq / 2);
float phaseStart = (FTWO_PI - mVizPhase[mDoubleBufferFlip]) / vizPhaseInc;
float end = lengthSamples - (FTWO_PI / vizPhaseInc);
if (mDrawWaveform)
{
ofBeginShape();
for (int i = phaseStart; i < lengthSamples; i++)
{
float x = ofMap(i - phaseStart, 0, end, 0, w, true);
float samp = mAudioView[(i + mBufferVizOffset[mDoubleBufferFlip]) % lengthSamples][mDoubleBufferFlip];
samp *= mDrawGain;
if (x < w)
ofVertex(x, h / 2 - samp * (h / 2));
}
ofEndShape(false);
}
if (mDrawCircle)
{
ofSetCircleResolution(32);
ofSetLineWidth(1);
for (int i = phaseStart; i < lengthSamples; i++)
{
float a = float(i - phaseStart) / end;
if (a < 1)
{
float rad = a * MIN(w, h) / 2;
float samp = mAudioView[(i + mBufferVizOffset[mDoubleBufferFlip]) % lengthSamples][mDoubleBufferFlip];
if (samp > 0)
ofSetColor(245, 58, 135, ofMap(samp * mDrawGain / 10, 0, 1, 0, 255, true));
else
ofSetColor(58, 245, 135, ofMap(-samp * mDrawGain / 10, 0, 1, 0, 255, true));
ofCircle(w / 2, h / 2, rad);
}
}
}
ofPopMatrix();
ofPopStyle();
for (int i = 0; i < lengthSamples; ++i)
mAudioView[i][mDoubleBufferFlip] = mAudioView[i][!mDoubleBufferFlip];
mBufferVizOffset[mDoubleBufferFlip] = mBufferVizOffset[!mDoubleBufferFlip];
mVizPhase[mDoubleBufferFlip] = mVizPhase[!mDoubleBufferFlip];
mDoubleBufferFlip = !mDoubleBufferFlip;
}
void WaveformViewer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (velocity > 0)
{
float floatPitch = pitch;
if (modulation.pitchBend != nullptr)
floatPitch += modulation.pitchBend->GetValue(0);
mDisplayFreq = TheScale->PitchToFreq(floatPitch);
}
}
void WaveformViewer::Resize(float w, float h)
{
mWidth = w;
mHeight = h;
}
void WaveformViewer::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadInt("width", moduleInfo, 600, 50, 2000, K(isTextField));
mModuleSaveData.LoadInt("height", moduleInfo, 150, 50, 2000, K(isTextField));
mModuleSaveData.LoadBool("draw_waveform", moduleInfo, true);
mModuleSaveData.LoadBool("draw_circle", moduleInfo, false);
SetUpFromSaveData();
}
void WaveformViewer::SaveLayout(ofxJSONElement& moduleInfo)
{
moduleInfo["width"] = mWidth;
moduleInfo["height"] = mHeight;
}
void WaveformViewer::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
mWidth = mModuleSaveData.GetInt("width");
mHeight = mModuleSaveData.GetInt("height");
mDrawWaveform = mModuleSaveData.GetBool("draw_waveform");
mDrawCircle = mModuleSaveData.GetBool("draw_circle");
}
``` | /content/code_sandbox/Source/WaveformViewer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,068 |
```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
**/
//
// EffectFactory.h
// Bespoke
//
// Created by Ryan Challinor on 12/1/14.
//
//
#pragma once
#include "IAudioEffect.h"
typedef IAudioEffect* (*CreateEffectFn)(void);
class EffectFactory
{
public:
EffectFactory();
IAudioEffect* MakeEffect(std::string type);
std::vector<std::string> GetSpawnableEffects();
private:
void Register(std::string type, CreateEffectFn creator);
std::map<std::string, CreateEffectFn> mFactoryMap;
};
``` | /content/code_sandbox/Source/EffectFactory.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 215 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// ModulationChain.cpp
// Bespoke
//
// Created by Ryan Challinor on 12/26/15.
//
//
#include "ModulationChain.h"
ModulationChain::ModulationChain(float initialValue)
{
mRamp.SetValue(initialValue);
mLFO.SetMode(kLFOMode_Oscillator);
}
float ModulationChain::GetValue(int samplesIn) const
{
float value = GetIndividualValue(samplesIn);
if (mMultiplyIn)
value *= mMultiplyIn->GetIndividualValue(samplesIn);
if (mSidechain)
value += mSidechain->GetIndividualValue(samplesIn);
if (mPrev)
value += mPrev->GetValue(samplesIn);
if (std::isnan(value))
return 0;
return value;
}
float ModulationChain::GetIndividualValue(int samplesIn) const
{
double time = gTime + gInvSampleRateMs * samplesIn;
float value;
if (mRamp.HasValue(time))
value = mRamp.Value(time);
else
value = 0;
if (mLFOAmount != 0)
value += mLFO.Value(samplesIn) * mLFOAmount;
if (mBuffer != nullptr && samplesIn >= 0 && samplesIn < gBufferSize)
value += mBuffer[samplesIn];
return value;
}
void ModulationChain::SetValue(float value)
{
mRamp.Start(gTime, value, gTime + gInvSampleRateMs * gBufferSize);
}
void ModulationChain::RampValue(double time, float from, float to, double length)
{
mRamp.Start(time, from, to, time + length);
}
void ModulationChain::SetLFO(NoteInterval interval, float amount)
{
mLFO.SetPeriod(interval);
mLFOAmount = amount;
}
void ModulationChain::AppendTo(ModulationChain* chain)
{
mPrev = chain;
}
void ModulationChain::SetSidechain(ModulationChain* chain)
{
mSidechain = chain;
}
void ModulationChain::MultiplyIn(ModulationChain* chain)
{
mMultiplyIn = chain;
}
void ModulationChain::CreateBuffer()
{
if (mBuffer == nullptr)
mBuffer = new float[gBufferSize];
Clear(mBuffer, gBufferSize);
}
void ModulationChain::FillBuffer(float* buffer)
{
if (mBuffer != nullptr)
BufferCopy(mBuffer, buffer, gBufferSize);
}
float ModulationChain::GetBufferValue(int sampleIdx)
{
if (mBuffer != nullptr && sampleIdx >= 0 && sampleIdx < gBufferSize)
return mBuffer[sampleIdx];
return 0;
}
Modulations::Modulations(bool isGlobalEffect)
{
mVoiceModulations.resize(kNumVoices);
if (isGlobalEffect)
{
for (int i = 0; i < kNumVoices; ++i)
{
mVoiceModulations[i].mPitchBend.SetSidechain(&mGlobalModulation.mPitchBend);
mVoiceModulations[i].mModWheel.SetSidechain(&mGlobalModulation.mModWheel);
mVoiceModulations[i].mPressure.SetSidechain(&mGlobalModulation.mPressure);
}
}
}
ModulationChain* Modulations::GetPitchBend(int voiceIdx)
{
if (voiceIdx == -1)
return &mGlobalModulation.mPitchBend;
else
return &mVoiceModulations[voiceIdx].mPitchBend;
}
ModulationChain* Modulations::GetModWheel(int voiceIdx)
{
if (voiceIdx == -1)
return &mGlobalModulation.mModWheel;
else
return &mVoiceModulations[voiceIdx].mModWheel;
}
ModulationChain* Modulations::GetPressure(int voiceIdx)
{
if (voiceIdx == -1)
return &mGlobalModulation.mPressure;
else
return &mVoiceModulations[voiceIdx].mPressure;
}
``` | /content/code_sandbox/Source/ModulationChain.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 949 |
```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
**/
/*
==============================================================================
CodeEntry.h
Created: 19 Apr 2020 9:26:55am
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IUIControl.h"
#include "SynthGlobals.h"
class ICodeEntryListener
{
public:
virtual ~ICodeEntryListener() {}
virtual void ExecuteCode() = 0;
virtual std::pair<int, int> ExecuteBlock(int lineStart, int lineEnd) = 0; //return start/end lines that actually ran
virtual void OnCodeUpdated() {}
};
class CodeEntry : public IUIControl, public IKeyboardFocusListener
{
public:
CodeEntry(ICodeEntryListener* owner, const char* name, int x, int y, float w, float h);
void OnKeyPressed(int key, bool isRepeat) override;
void Render() override;
void Poll() override;
void RenderOverlay();
void MakeActive();
void Publish();
void ClearInput()
{
mString = "";
mCaretPosition = 0;
}
const std::string GetText(bool published) const { return published ? mPublishedString : mString; }
const std::vector<std::string> GetLines(bool published) const { return ofSplitString(published ? mPublishedString : mString, "\n"); }
void SetText(std::string text) { UpdateString(text); }
void SetError(bool error, int errorLine = -1);
void SetDoSyntaxHighlighting(bool highlight) { mDoSyntaxHighlighting = highlight; }
static bool HasJediNotInstalledWarning() { return sWarnJediNotInstalled; }
static void OnPythonInit();
void GetDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void SetDimensions(float width, float height);
//IUIControl
void SetFromMidiCC(float slider, double time, bool setViaModulator) override {}
void SetValue(float value, double time, bool forceUpdate = false) 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 IsTextEntry() const override { return true; }
bool GetNoHover() const override { return true; }
ofVec2f GetLinePos(int lineNum, bool end, bool published = true);
float GetCharHeight() const { return mCharHeight; }
float GetCharWidth() const { return mCharWidth; }
void SetStyleFromJSON(const ofxJSONElement& vdict);
protected:
~CodeEntry(); //protected so that it can't be created on the stack
private:
void AddCharacter(char c);
void AddString(std::string s);
bool AllowCharacter(char c);
int GetCaretPosition(int col, int row);
int GetColForX(float x);
int GetRowForY(float y);
ofVec2f GetCaretCoords(int caret);
void RemoveSelectedText();
void ShiftLines(bool backwards);
void MoveCaret(int pos, bool allowSelection = true);
void MoveCaretToStart();
void MoveCaretToEnd();
void MoveCaretToNextToken(bool backwards);
void Undo();
void Redo();
void UpdateString(std::string newString);
void DrawSyntaxHighlight(std::string input, ofColor color, std::vector<int> mapping, int filter1, int filter2);
std::string FilterText(std::string input, std::vector<int> mapping, int filter1, int filter2);
void OnCodeUpdated();
std::string GetVisibleCode();
bool IsAutocompleteShowing();
void AcceptAutocompletion();
void OnClicked(float x, float y, bool right) override;
bool MouseMoved(float x, float y) override;
bool MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) override;
static bool sWarnJediNotInstalled;
struct UndoBufferEntry
{
std::string mString;
int mCaretPos{ 0 };
};
struct AutocompleteSignatureInfo
{
bool valid{ false };
int entryIndex{ 0 };
std::vector<std::string> params;
int caretPos{ 0 };
};
struct AutocompleteInfo
{
bool valid{ false };
std::string autocompleteFull;
std::string autocompleteRest;
};
ICodeEntryListener* mListener;
float mWidth{ 200 };
float mHeight{ 20 };
float mCharWidth{ 5.85 };
float mCharHeight{ 15 };
std::string mString;
std::string mPublishedString;
std::array<UndoBufferEntry, 50> mUndoBuffer;
int mUndoBufferPos{ 0 };
int mUndosLeft{ 0 };
int mRedosLeft{ 0 };
int mCaretPosition{ 0 };
int mCaretPosition2{ 0 };
float mCaretBlinkTimer{ 0 };
bool mCaretBlink{ true };
bool mHovered{ false };
double mLastPublishTime{ -999 };
int mLastPublishedLineStart{ 0 };
int mLastPublishedLineEnd{ 0 };
bool mHasError{ false };
int mErrorLine{ -1 };
ofVec2f mScroll;
std::vector<int> mSyntaxHighlightMapping;
/*
* For syntax highlighting we have both a static (system wide) and mDo (per insdtance)
* control and then we use and
*/
static bool sDoSyntaxHighlighting;
static bool sDoPythonAutocomplete;
bool mDoSyntaxHighlighting{ false };
std::array<AutocompleteSignatureInfo, 10> mAutocompleteSignatures;
std::array<AutocompleteInfo, 10> mAutocompletes;
float mAutocompleteUpdateTimer{ 0 };
ofVec2f mAutocompleteCaretCoords;
bool mWantToShowAutocomplete{ false };
int mAutocompleteHighlightIndex{ 0 };
bool mCodeUpdated{ false };
// Style Sheet
ofColor currentBg{ 60, 60, 60 }, publishedBg{ 25, 35, 25 }, unpublishedBg{ 35, 35, 35 };
ofColor stringColor{ (int)(0.9 * 255), (int)(0.7 * 255), (int)(0.6 * 255), 255 };
ofColor numberColor{ (int)(0.9 * 255), (int)(0.9 * 255), (int)(1.0 * 255), 255 };
ofColor name1Color{ (int)(0.4 * 255), (int)(0.9 * 255), (int)(0.8 * 255), 255 };
ofColor name2Color{ (int)(0.7 * 255), (int)(0.9 * 255), (int)(0.3 * 255), 255 };
ofColor name3Color{ (int)(0.3 * 255), (int)(0.9 * 255), (int)(0.4 * 255), 255 };
ofColor definedColor{ (int)(0.6 * 255), (int)(1.0 * 255), (int)(0.9 * 255), 255 };
ofColor equalsColor{ (int)(0.9 * 255), (int)(0.7 * 255), (int)(0.6 * 255), 255 };
ofColor parenColor{ (int)(0.6 * 255), (int)(0.5 * 255), (int)(0.9 * 255), 255 };
ofColor braceColor{ (int)(0.4 * 255), (int)(0.5 * 255), (int)(0.7 * 255), 255 };
ofColor bracketColor{ (int)(0.5 * 255), (int)(0.8 * 255), (int)(0.7 * 255), 255 };
ofColor opColor{ (int)(0.9 * 255), (int)(0.3 * 255), (int)(0.6 * 255), 255 };
ofColor commaColor{ (int)(0.5 * 255), (int)(0.6 * 255), (int)(0.5 * 255), 255 };
ofColor commentColor{ (int)(0.5 * 255), (int)(0.5 * 255), (int)(0.5 * 255), 255 };
ofColor selectedOverlay{ 255, 255, 255, 50 };
ofColor jediBg{ 70, 70, 70 };
ofColor jediIndexBg{ 100, 100, 100 };
ofColor jediAutoComplete{ 200, 200, 200 };
ofColor jediAutoCompleteRest{ 255, 255, 255 };
ofColor jediParams{ 170, 170, 255 };
ofColor jediParamsHighlight{ 230, 230, 255 };
ofColor unknownColor = ofColor::white;
float mFontSize{ 12 };
};
``` | /content/code_sandbox/Source/CodeEntry.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,167 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
ModulatorAddCentered.cpp
Created: 22 Nov 2017 9:50:17am
Author: Ryan Challinor
==============================================================================
*/
#include "ModulatorAddCentered.h"
#include "Profiler.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
ModulatorAddCentered::ModulatorAddCentered()
{
}
void ModulatorAddCentered::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mValue1Slider = new FloatSlider(this, "value 1", 3, 2, 100, 15, &mValue1, 0, 1);
mValue2Slider = new FloatSlider(this, "value 2", mValue1Slider, kAnchor_Below, 100, 15, &mValue2, -1, 1);
mValue2RangeSlider = new FloatSlider(this, "range 2", mValue2Slider, kAnchor_Below, 100, 15, &mValue2Range, 0, 1);
mTargetCable = new PatchCableSource(this, kConnectionType_Modulator);
mTargetCable->SetModulatorOwner(this);
AddPatchCableSource(mTargetCable);
}
ModulatorAddCentered::~ModulatorAddCentered()
{
}
void ModulatorAddCentered::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mValue1Slider->Draw();
mValue2Slider->Draw();
mValue2RangeSlider->Draw();
}
void ModulatorAddCentered::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
OnModulatorRepatch();
if (GetSliderTarget() && fromUserClick)
{
mValue1 = GetSliderTarget()->GetValue();
mValue2 = 0;
mValue1Slider->SetExtents(GetSliderTarget()->GetMin(), GetSliderTarget()->GetMax());
mValue1Slider->SetMode(GetSliderTarget()->GetMode());
mValue2RangeSlider->SetExtents(0, GetSliderTarget()->GetMax() - GetSliderTarget()->GetMin());
}
}
float ModulatorAddCentered::Value(int samplesIn)
{
ComputeSliders(samplesIn);
if (GetSliderTarget())
return ofClamp(mValue1 + mValue2 * mValue2Range, GetSliderTarget()->GetMin(), GetSliderTarget()->GetMax());
else
return mValue1 + mValue2 * mValue2Range;
}
void ModulatorAddCentered::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void ModulatorAddCentered::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void ModulatorAddCentered::SetUpFromSaveData()
{
}
``` | /content/code_sandbox/Source/ModulatorAddCentered.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 711 |
```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
**/
//
// Polyrhythms.h
// modularSynth
//
// Created by Ryan Challinor on 3/12/13.
//
//
#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 Polyrhythms;
class RhythmLine
{
public:
RhythmLine(Polyrhythms* owner, int index);
void Draw();
void OnClicked(float x, float y, bool right);
void MouseReleased();
void MouseMoved(float x, float y);
void CreateUIControls();
void OnResize();
void UpdateGrid();
int mIndex{ 0 };
UIGrid* mGrid{ nullptr };
int mLength{ 4 };
DropdownList* mLengthSelector{ nullptr };
int mPitch{ 0 };
TextEntry* mNoteSelector{ nullptr };
Polyrhythms* mOwner{ nullptr };
};
class Polyrhythms : public INoteSource, public IDrawableModule, public IAudioPoller, public IDropdownListener, public ITextEntryListener
{
public:
Polyrhythms();
~Polyrhythms();
static IDrawableModule* Create() { return new Polyrhythms(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
bool IsResizable() const override { return true; }
void Resize(float w, float h) 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 DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void TextEntryComplete(TextEntry* entry) override {}
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void LoadState(FileStreamIn& in, int rev) override;
void SaveState(FileStreamOut& out) 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
{
width = mWidth;
height = mHeight;
}
void OnClicked(float x, float y, bool right) override;
float mWidth{ 350 };
float mHeight;
std::array<RhythmLine*, 8> mRhythmLines;
};
``` | /content/code_sandbox/Source/Polyrhythms.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 723 |
```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
**/
/*
==============================================================================
ModulatorAdd.h
Created: 19 Nov 2017 2:04:23pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "Slider.h"
#include "IModulator.h"
class PatchCableSource;
class ModulatorAdd : public IDrawableModule, public IFloatSliderListener, public IModulator
{
public:
ModulatorAdd();
virtual ~ModulatorAdd();
static IDrawableModule* Create() { return new ModulatorAdd(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
//IModulator
float Value(int samplesIn = 0) override;
bool Active() const override { return mEnabled; }
bool CanAdjustRange() const override { return false; }
FloatSlider* GetTarget() { return GetSliderTarget(); }
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void SaveLayout(ofxJSONElement& moduleInfo) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = 106;
h = 17 * 2 + 4;
}
float mValue1{ 0 };
float mValue2{ 0 };
FloatSlider* mValue1Slider{ nullptr };
FloatSlider* mValue2Slider{ nullptr };
};
``` | /content/code_sandbox/Source/ModulatorAdd.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 527 |
```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
**/
//
// FeedbackModule.h
// Bespoke
//
// Created by Ryan Challinor on 2/1/16.
//
//
#pragma once
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "DelayEffect.h"
class PatchCableSource;
class FeedbackModule : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener
{
public:
FeedbackModule();
virtual ~FeedbackModule();
static IDrawableModule* Create() { return new FeedbackModule(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = 115;
h = 125;
}
DelayEffect mDelay;
IAudioReceiver* mFeedbackTarget{ nullptr };
PatchCableSource* mFeedbackTargetCable{ nullptr };
RollingBuffer mFeedbackVizBuffer;
float mSignalLimit{ 1 };
double mGainScale[ChannelBuffer::kMaxNumChannels];
FloatSlider* mSignalLimitSlider{ nullptr };
};
``` | /content/code_sandbox/Source/FeedbackModule.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 504 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Autotalent.cpp
// modularSynth
//
// Created by Ryan Challinor on 1/27/13.
//
//
#include "Autotalent.h"
#include "SynthGlobals.h"
#include "FFT.h"
#include "Scale.h"
#include "ModularSynth.h"
#include "Profiler.h"
#define L2SC (float)3.32192809488736218171
Autotalent::Autotalent()
: IAudioProcessor(gBufferSize)
{
mWorkingBuffer = new float[GetBuffer()->BufferSize()];
Clear(mWorkingBuffer, GetBuffer()->BufferSize());
mfs = gSampleRate;
mcbsize = 2048;
mcorrsize = mcbsize / 2 + 1;
mpmax = 1 / (float)70; // max and min periods (ms)
mpmin = 1 / (float)700; // eventually may want to bring these out as sliders
mnmax = (unsigned long)(gSampleRate * mpmax);
if (mnmax > mcorrsize)
{
mnmax = mcorrsize;
}
mnmin = (unsigned long)(gSampleRate * mpmin);
mcbi = (float*)calloc(mcbsize, sizeof(float));
mcbf = (float*)calloc(mcbsize, sizeof(float));
mcbo = (float*)calloc(mcbsize, sizeof(float));
mcbiwr = 0;
mcbord = 0;
mlfophase = 0;
// Initialize formant corrector
mford = 7; // should be sufficient to capture formants
mfalph = pow(0.001f, (float)80 / (gSampleRate));
mflamb = -(0.8517 * sqrt(atan(0.06583 * gSampleRate)) - 0.1916); // or about -0.88 @ 44.1kHz
mfk = (float*)calloc(mford, sizeof(float));
mfb = (float*)calloc(mford, sizeof(float));
mfc = (float*)calloc(mford, sizeof(float));
mfrb = (float*)calloc(mford, sizeof(float));
mfrc = (float*)calloc(mford, sizeof(float));
mfsig = (float*)calloc(mford, sizeof(float));
mfsmooth = (float*)calloc(mford, sizeof(float));
mfhp = 0;
mflp = 0;
mflpa = pow(0.001f, (float)10 / (gSampleRate));
mfbuff = (float**)malloc((mford) * sizeof(float*));
for (int ti = 0; ti < mford; ti++)
{
mfbuff[ti] = (float*)calloc(mcbsize, sizeof(float));
}
mftvec = (float*)calloc(mford, sizeof(float));
mfmute = 1;
mfmutealph = pow(0.001f, (float)1 / (gSampleRate));
// Standard raised cosine window, max height at N/2
mhannwindow = (float*)calloc(mcbsize, sizeof(float));
for (int ti = 0; ti < mcbsize; ti++)
{
mhannwindow[ti] = -0.5 * cos(2 * PI * ti / mcbsize) + 0.5;
}
// Generate a window with a single raised cosine from N/4 to 3N/4
mcbwindow = (float*)calloc(mcbsize, sizeof(float));
for (int ti = 0; ti < (mcbsize / 2); ti++)
{
mcbwindow[ti + mcbsize / 4] = -0.5 * cos(4 * PI * ti / (mcbsize - 1)) + 0.5;
}
mnoverlap = 4;
mFFT = new ::FFT((int)mcbsize);
mffttime = (float*)calloc(mcbsize, sizeof(float));
mfftfreqre = (float*)calloc(mcorrsize, sizeof(float));
mfftfreqim = (float*)calloc(mcorrsize, sizeof(float));
// ---- Calculate autocorrelation of window ----
macwinv = (float*)calloc(mcbsize, sizeof(float));
for (int ti = 0; ti < mcbsize; ti++)
{
mffttime[ti] = mcbwindow[ti];
}
mFFT->Forward(mcbwindow, mfftfreqre, mfftfreqim);
for (int ti = 0; ti < mcorrsize; ti++)
{
mfftfreqre[ti] = (mfftfreqre[ti]) * (mfftfreqre[ti]) + (mfftfreqim[ti]) * (mfftfreqim[ti]);
mfftfreqim[ti] = 0;
}
mFFT->Inverse(mfftfreqre, mfftfreqim, mffttime);
for (long ti = 1; ti < mcbsize; ti++)
{
macwinv[ti] = mffttime[ti] / mffttime[0];
if (macwinv[ti] > 0.000001)
{
macwinv[ti] = (float)1 / macwinv[ti];
}
else
{
macwinv[ti] = 0;
}
}
macwinv[0] = 1;
// ---- END Calculate autocorrelation of window ----
mlrshift = 0;
mptarget = 0;
msptarget = 0;
mvthresh = 0.7; // The voiced confidence (unbiased peak) threshold level
// Pitch shifter initialization
mphprdd = 0.01; // Default period
minphinc = (float)1 / (mphprdd * gSampleRate);
mphincfact = 1;
mphasein = 0;
mphaseout = 0;
mfrag = (float*)calloc(mcbsize, sizeof(float));
mfragsize = 0;
}
void Autotalent::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mASelector = new RadioButton(this, "A", 4, 40, &mA);
mBbSelector = new RadioButton(this, "Bb", 24, 40, &mBb);
mBSelector = new RadioButton(this, "B", 44, 40, &mB);
mCSelector = new RadioButton(this, "C", 64, 40, &mC);
mDbSelector = new RadioButton(this, "Db", 84, 40, &mDb);
mDSelector = new RadioButton(this, "D", 104, 40, &mD);
mEbSelector = new RadioButton(this, "Eb", 124, 40, &mEb);
mESelector = new RadioButton(this, "E", 144, 40, &mE);
mFSelector = new RadioButton(this, "F", 164, 40, &mF);
mGbSelector = new RadioButton(this, "Gb", 184, 40, &mGb);
mGSelector = new RadioButton(this, "G", 204, 40, &mG);
mAbSelector = new RadioButton(this, "Ab", 224, 40, &mAb);
mAmountSlider = new FloatSlider(this, "amount", 4, 100, 150, 15, &mAmount, 0, 1);
mSmoothSlider = new FloatSlider(this, "smooth", 4, 120, 150, 15, &mSmooth, 0, .8f);
mShiftSlider = new IntSlider(this, "shift", 4, 140, 150, 15, &mShift, -6, 6);
mScwarpSlider = new IntSlider(this, "scwarp", 4, 160, 150, 15, &mScwarp, -3, 3);
mLfoampSlider = new FloatSlider(this, "lfoamp", 4, 180, 150, 15, &mLfoamp, 0, 1);
mLforateSlider = new FloatSlider(this, "lforate", 4, 200, 150, 15, &mLforate, 0, 20);
mLfoshapeSlider = new IntSlider(this, "lfoshape", 4, 220, 150, 15, &mLfoshape, -1, 1);
mLfosymmSlider = new FloatSlider(this, "lfosymm", 4, 240, 150, 15, &mLfosymm, 0, 1);
mLfoquantCheckbox = new Checkbox(this, "lfoquant", 4, 260, &mLfoquant);
mFcorrCheckbox = new Checkbox(this, "formant correct", 4, 280, &mFcorr);
mFwarpSlider = new FloatSlider(this, "fwarp", 4, 300, 150, 15, &mFwarp, -5, 5);
mMixSlider = new FloatSlider(this, "mix", 4, 320, 150, 15, &mMix, 0, 1);
mSetFromScaleButton = new ClickButton(this, "set from scale", 4, 340);
mASelector->AddLabel("A ", 1);
mASelector->AddLabel(" ", 0);
mASelector->AddLabel("-", -1);
mBbSelector->AddLabel("Bb", 1);
mBbSelector->AddLabel(" ", 0);
mBbSelector->AddLabel("-", -1);
mBSelector->AddLabel("B ", 1);
mBSelector->AddLabel(" ", 0);
mBSelector->AddLabel("-", -1);
mCSelector->AddLabel("C ", 1);
mCSelector->AddLabel(" ", 0);
mCSelector->AddLabel("-", -1);
mDbSelector->AddLabel("Db", 1);
mDbSelector->AddLabel(" ", 0);
mDbSelector->AddLabel("-", -1);
mDSelector->AddLabel("D ", 1);
mDSelector->AddLabel(" ", 0);
mDSelector->AddLabel("-", -1);
mEbSelector->AddLabel("Eb", 1);
mEbSelector->AddLabel(" ", 0);
mEbSelector->AddLabel("-", -1);
mESelector->AddLabel("E ", 1);
mESelector->AddLabel(" ", 0);
mESelector->AddLabel("-", -1);
mFSelector->AddLabel("F ", 1);
mFSelector->AddLabel(" ", 0);
mFSelector->AddLabel("-", -1);
mGbSelector->AddLabel("Gb", 1);
mGbSelector->AddLabel(" ", 0);
mGbSelector->AddLabel("-", -1);
mGSelector->AddLabel("G ", 1);
mGSelector->AddLabel(" ", 0);
mGSelector->AddLabel("-", -1);
mAbSelector->AddLabel("Ab", 1);
mAbSelector->AddLabel(" ", 0);
mAbSelector->AddLabel("-", -1);
}
Autotalent::~Autotalent()
{
delete mFFT;
free(mcbi);
free(mcbf);
free(mcbo);
free(mcbwindow);
free(mhannwindow);
free(macwinv);
free(mfrag);
free(mffttime);
free(mfftfreqre);
free(mfftfreqim);
free(mfk);
free(mfb);
free(mfc);
free(mfrb);
free(mfrc);
free(mfsmooth);
free(mfsig);
for (int ti = 0; ti < mford; ti++)
{
free(mfbuff[ti]);
}
free(mfbuff);
free(mftvec);
}
void Autotalent::Process(double time)
{
PROFILER(Autotalent);
IAudioReceiver* target = GetTarget();
if (!mEnabled || target == nullptr)
return;
ComputeSliders(0);
SyncBuffers();
int iNotes[12];
int iPitch2Note[12];
int iNote2Pitch[12];
int numNotes;
int iScwarp;
long int N;
long int Nf;
long int fs;
long int ti;
long int ti2;
long int ti3;
long int ti4;
float tf;
float tf2;
// Variables for cubic spline interpolator
float indd;
int ind0;
int ind1;
int ind2;
int ind3;
float vald;
float val0;
float val1;
float val2;
float val3;
int lowersnap;
int uppersnap;
float lfoval;
float pperiod;
float fa;
float fb;
float fc;
float fk;
float flamb;
float frlamb;
float falph;
float foma;
float f1resp;
float f0resp;
float flpa;
int ford;
float* pfInput = GetBuffer()->GetChannel(0);
int bufferSize = GetBuffer()->BufferSize();
Clear(mWorkingBuffer, GetBuffer()->BufferSize());
float* pfOutput = mWorkingBuffer;
iNotes[0] = mA;
iNotes[1] = mBb;
iNotes[2] = mB;
iNotes[3] = mC;
iNotes[4] = mDb;
iNotes[5] = mD;
iNotes[6] = mEb;
iNotes[7] = mE;
iNotes[8] = mF;
iNotes[9] = mGb;
iNotes[10] = mG;
iNotes[11] = mAb;
iScwarp = mScwarp;
// Some logic for the semitone->scale and scale->semitone conversion
// If no notes are selected as being in the scale, instead snap to all notes
ti2 = 0;
for (ti = 0; ti < 12; ti++)
{
if (iNotes[ti] >= 0)
{
iPitch2Note[ti] = (int)ti2;
iNote2Pitch[ti2] = (int)ti;
ti2 = ti2 + 1;
}
else
{
iPitch2Note[ti] = -1;
}
}
numNotes = (int)ti2;
while (ti2 < 12)
{
iNote2Pitch[ti2] = -1;
ti2 = ti2 + 1;
}
if (numNotes == 0)
{
for (ti = 0; ti < 12; ti++)
{
iNotes[ti] = 1;
iPitch2Note[ti] = (int)ti;
iNote2Pitch[ti] = (int)ti;
}
numNotes = 12;
}
iScwarp = (iScwarp + numNotes * 5) % numNotes;
ford = mford;
falph = mfalph;
foma = (float)1 - falph;
flpa = mflpa;
flamb = mflamb;
tf = pow((float)2, mFwarp / 2) * (1 + flamb) / (1 - flamb);
frlamb = (tf - 1) / (tf + 1);
maref = (float)mTune;
N = mcbsize;
Nf = mcorrsize;
fs = mfs;
pperiod = mpmax;
float inpitch = minpitch;
float conf = mconf;
float outpitch = moutpitch;
/*******************
* MAIN DSP LOOP *
*******************/
for (int lSampleIndex = 0; lSampleIndex < bufferSize; lSampleIndex++)
{
// load data into circular buffer
tf = (float)*(pfInput++);
ti4 = mcbiwr;
mcbi[ti4] = tf;
if (mFcorr)
{
// Somewhat experimental formant corrector
// formants are removed using an adaptive pre-filter and
// re-introduced after pitch manipulation using post-filter
// tf is signal input
fa = tf - mfhp; // highpass pre-emphasis filter
mfhp = tf;
fb = fa;
for (ti = 0; ti < ford; ti++)
{
mfsig[ti] = fa * fa * foma + mfsig[ti] * falph;
fc = (fb - mfc[ti]) * flamb + mfb[ti];
mfc[ti] = fc;
mfb[ti] = fb;
fk = fa * fc * foma + mfk[ti] * falph;
mfk[ti] = fk;
tf = fk / (mfsig[ti] + 0.000001);
tf = tf * foma + mfsmooth[ti] * falph;
mfsmooth[ti] = tf;
mfbuff[ti][ti4] = tf;
fb = fc - tf * fa;
fa = fa - tf * fc;
}
mcbf[ti4] = fa;
// Now hopefully the formants are reduced
// More formant correction code at the end of the DSP loop
}
else
{
mcbf[ti4] = tf;
}
// Input write pointer logic
mcbiwr++;
if (mcbiwr >= N)
{
mcbiwr = 0;
}
// ********************
// * Low-rate section *
// ********************
// Every N/noverlap samples, run pitch estimation / manipulation code
if ((mcbiwr) % (N / mnoverlap) == 0)
{
// ---- Obtain autocovariance ----
// Window and fill FFT buffer
ti2 = mcbiwr;
for (ti = 0; ti < N; ti++)
{
mffttime[ti] = (float)(mcbi[(ti2 - ti + N) % N] * mcbwindow[ti]);
}
// Calculate FFT
mFFT->Forward(mffttime, mfftfreqre, mfftfreqim);
// Remove DC
mfftfreqre[0] = 0;
mfftfreqim[0] = 0;
// Take magnitude squared
for (ti = 1; ti < Nf; ti++)
{
mfftfreqre[ti] = (mfftfreqre[ti]) * (mfftfreqre[ti]) + (mfftfreqim[ti]) * (mfftfreqim[ti]);
mfftfreqim[ti] = 0;
}
// Calculate IFFT
mFFT->Inverse(mfftfreqre, mfftfreqim, mffttime);
// Normalize
tf = (float)1 / mffttime[0];
for (ti = 1; ti < N; ti++)
{
mffttime[ti] = mffttime[ti] * tf;
}
mffttime[0] = 1;
// ---- END Obtain autocovariance ----
// ---- Calculate pitch and confidence ----
// Calculate pitch period
// Pitch period is determined by the location of the max (biased)
// peak within a given range
// Confidence is determined by the corresponding unbiased height
tf2 = 0;
pperiod = mpmin;
for (ti = mnmin; ti < mnmax; ti++)
{
ti2 = ti - 1;
ti3 = ti + 1;
if (ti2 < 0)
{
ti2 = 0;
}
if (ti3 > Nf)
{
ti3 = Nf;
}
tf = mffttime[ti];
if (tf > mffttime[ti2] && tf >= mffttime[ti3] && tf > tf2)
{
tf2 = tf;
ti4 = ti;
}
}
if (tf2 > 0)
{
conf = tf2 * macwinv[ti4];
if (ti4 > 0 && ti4 < Nf)
{
// Find the center of mass in the vicinity of the detected peak
tf = mffttime[ti4 - 1] * (ti4 - 1);
tf = tf + mffttime[ti4] * (ti4);
tf = tf + mffttime[ti4 + 1] * (ti4 + 1);
tf = tf / (mffttime[ti4 - 1] + mffttime[ti4] + mffttime[ti4 + 1]);
pperiod = tf / fs;
}
else
{
pperiod = (float)ti4 / fs;
}
}
// Convert to semitones
tf = (float)-12 * log10((float)maref * pperiod) * L2SC;
if (conf >= mvthresh)
{
inpitch = tf;
minpitch = tf; // update pitch only if voiced
}
mconf = conf;
mPitch = inpitch + 69;
mConfidence = conf;
// ---- END Calculate pitch and confidence ----
// ---- Modify pitch in all kinds of ways! ----
outpitch = inpitch;
// Pull to fixed pitch
outpitch = (1 - mPull) * outpitch + mPull * mFixed;
// -- Convert from semitones to scale notes --
ti = (int)(outpitch / 12 + 32) - 32; // octave
tf = outpitch - ti * 12; // semitone in octave
ti2 = (int)tf;
ti3 = ti2 + 1;
// a little bit of pitch correction logic, since it's a convenient place for it
if (iNotes[ti2 % 12] < 0 || iNotes[ti3 % 12] < 0) // if between 2 notes that are more than a semitone apart
{
lowersnap = 1;
uppersnap = 1;
}
else
{
lowersnap = 0;
uppersnap = 0;
if (iNotes[ti2 % 12] == 1) // if specified by user
{
lowersnap = 1;
}
if (iNotes[ti3 % 12] == 1) // if specified by user
{
uppersnap = 1;
}
}
// (back to the semitone->scale conversion)
// finding next lower pitch in scale
while (iNotes[(ti2 + 12) % 12] < 0)
{
ti2 = ti2 - 1;
}
// finding next higher pitch in scale
while (iNotes[ti3 % 12] < 0)
{
ti3 = ti3 + 1;
}
tf = (tf - ti2) / (ti3 - ti2) + iPitch2Note[(ti2 + 12) % 12];
if (ti2 < 0)
{
tf = tf - numNotes;
}
outpitch = tf + numNotes * ti;
// -- Done converting to scale notes --
// The actual pitch correction
ti = (int)(outpitch + 128) - 128;
tf = outpitch - ti - 0.5;
ti2 = ti3 - ti2;
if (ti2 > 2)
{ // if more than 2 semitones apart, put a 2-semitone-like transition halfway between
tf2 = (float)ti2 / 2;
}
else
{
tf2 = (float)1;
}
if (mSmooth < 0.001)
{
tf2 = tf * tf2 / 0.001;
}
else
{
tf2 = tf * tf2 / mSmooth;
}
if (tf2 < -0.5)
tf2 = -0.5;
if (tf2 > 0.5)
tf2 = 0.5;
tf2 = 0.5 * sin(PI * tf2) + 0.5; // jumping between notes using horizontally-scaled sine segment
tf2 = tf2 + ti;
if ((tf < 0.5 && lowersnap) || (tf >= 0.5 && uppersnap))
{
outpitch = mAmount * tf2 + ((float)1 - mAmount) * outpitch;
}
// Add in pitch shift
outpitch = outpitch + mShift;
// LFO logic
tf = mLforate * N / (mnoverlap * fs);
if (tf > 1)
tf = 1;
mlfophase = mlfophase + tf;
if (mlfophase > 1)
mlfophase = mlfophase - 1;
lfoval = mlfophase;
tf = (mLfosymm + 1) / 2;
if (tf <= 0 || tf >= 1)
{
if (tf <= 0)
lfoval = 1 - lfoval;
}
else
{
if (lfoval <= tf)
{
lfoval = lfoval / tf;
}
else
{
lfoval = 1 - (lfoval - tf) / (1 - tf);
}
}
if (mLfoshape >= 0)
{
// linear combination of cos and line
lfoval = (0.5 - 0.5 * cos(lfoval * PI)) * mLfoshape + lfoval * (1 - mLfoshape);
lfoval = mLfoamp * (lfoval * 2 - 1);
}
else
{
// smoosh the sine horizontally until it's squarish
tf = 1 + mLfoshape;
if (tf < 0.001)
{
lfoval = (lfoval - 0.5) * 2 / 0.001;
}
else
{
lfoval = (lfoval - 0.5) * 2 / tf;
}
if (lfoval > 1)
lfoval = 1;
if (lfoval < -1)
lfoval = -1;
lfoval = mLfoamp * sin(lfoval * PI * 0.5);
}
// add in quantized LFO
if (mLfoquant)
{
outpitch = outpitch + (int)(numNotes * lfoval + numNotes + 0.5) - numNotes;
}
// Convert back from scale notes to semitones
outpitch = outpitch + iScwarp; // output scale rotate implemented here
ti = (int)(outpitch / numNotes + 32) - 32;
tf = outpitch - ti * numNotes;
ti2 = (int)tf;
ti3 = ti2 + 1;
outpitch = iNote2Pitch[ti3 % numNotes] - iNote2Pitch[ti2];
if (ti3 >= numNotes)
{
outpitch = outpitch + 12;
}
outpitch = outpitch * (tf - ti2) + iNote2Pitch[ti2];
outpitch = outpitch + 12 * ti;
outpitch = outpitch - (iNote2Pitch[iScwarp] - iNote2Pitch[0]); //more scale rotation here
// add in unquantized LFO
if (!mLfoquant)
{
outpitch = outpitch + lfoval * 2;
}
if (outpitch < -36)
outpitch = -48;
if (outpitch > 24)
outpitch = 24;
moutpitch = outpitch;
// ---- END Modify pitch in all kinds of ways! ----
// Compute variables for pitch shifter that depend on pitch
minphinc = maref * Pow2(inpitch / 12) / fs;
moutphinc = maref * Pow2(outpitch / 12) / fs;
mphincfact = moutphinc / minphinc;
}
// ************************
// * END Low-Rate Section *
// ************************
// *****************
// * Pitch Shifter *
// *****************
// Pitch shifter (kind of like a pitch-synchronous version of Fairbanks' technique)
// Note: pitch estimate is naturally N/2 samples old
mphasein = mphasein + minphinc;
mphaseout = mphaseout + moutphinc;
// When input phase resets, take a snippet from N/2 samples in the past
if (mphasein >= 1)
{
mphasein = mphasein - 1;
ti2 = mcbiwr - N / 2;
for (ti = -N / 2; ti < N / 2; ti++)
{
mfrag[(ti + N) % N] = mcbf[(ti + ti2 + N) % N];
}
}
// When output phase resets, put a snippet N/2 samples in the future
if (mphaseout >= 1)
{
mfragsize = mfragsize * 2;
if (mfragsize > N)
{
mfragsize = N;
}
mphaseout = mphaseout - 1;
ti2 = mcbord + N / 2;
ti3 = (long int)(((float)mfragsize) / mphincfact);
if (ti3 >= N / 2)
{
ti3 = N / 2 - 1;
}
for (ti = -ti3 / 2; ti < (ti3 / 2); ti++)
{
tf = mhannwindow[(long int)N / 2 + ti * (long int)N / ti3];
// 3rd degree polynomial interpolator - based on eqns from Hal Chamberlin's book
indd = mphincfact * ti;
ind1 = (int)indd;
ind2 = ind1 + 1;
ind3 = ind1 + 2;
ind0 = ind1 - 1;
val0 = mfrag[(ind0 + N) % N];
val1 = mfrag[(ind1 + N) % N];
val2 = mfrag[(ind2 + N) % N];
val3 = mfrag[(ind3 + N) % N];
vald = 0;
vald = vald - (float)0.166666666667 * val0 * (indd - ind1) * (indd - ind2) * (indd - ind3);
vald = vald + (float)0.5 * val1 * (indd - ind0) * (indd - ind2) * (indd - ind3);
vald = vald - (float)0.5 * val2 * (indd - ind0) * (indd - ind1) * (indd - ind3);
vald = vald + (float)0.166666666667 * val3 * (indd - ind0) * (indd - ind1) * (indd - ind2);
mcbo[(ti + ti2 + N) % N] = mcbo[(ti + ti2 + N) % N] + vald * tf;
}
mfragsize = 0;
}
mfragsize++;
// Get output signal from buffer
tf = mcbo[mcbord]; // read buffer
mcbo[mcbord] = 0; // erase for next cycle
mcbord++; // increment read pointer
if (mcbord >= N)
{
mcbord = 0;
}
// *********************
// * END Pitch Shifter *
// *********************
ti4 = (mcbiwr + 2) % N;
if (mFcorr)
{
// The second part of the formant corrector
// This is a post-filter that re-applies the formants, designed
// to result in the exact original signal when no pitch
// manipulation is performed.
// tf is signal input
// gotta run it 3 times because of a pesky delay free loop
// first time: compute 0-response
tf2 = tf;
fa = 0;
fb = fa;
for (ti = 0; ti < ford; ti++)
{
fc = (fb - mfrc[ti]) * frlamb + mfrb[ti];
tf = mfbuff[ti][ti4];
fb = fc - tf * fa;
mftvec[ti] = tf * fc;
fa = fa - mftvec[ti];
}
tf = -fa;
for (ti = ford - 1; ti >= 0; ti--)
{
tf = tf + mftvec[ti];
}
f0resp = tf;
// second time: compute 1-response
fa = 1;
fb = fa;
for (ti = 0; ti < ford; ti++)
{
fc = (fb - mfrc[ti]) * frlamb + mfrb[ti];
tf = mfbuff[ti][ti4];
fb = fc - tf * fa;
mftvec[ti] = tf * fc;
fa = fa - mftvec[ti];
}
tf = -fa;
for (ti = ford - 1; ti >= 0; ti--)
{
tf = tf + mftvec[ti];
}
f1resp = tf;
// now solve equations for output, based on 0-response and 1-response
tf = (float)2 * tf2;
tf2 = tf;
tf = ((float)1 - f1resp + f0resp);
if (tf != 0)
{
tf2 = (tf2 + f0resp) / tf;
}
else
{
tf2 = 0;
}
// third time: update delay registers
fa = tf2;
fb = fa;
for (ti = 0; ti < ford; ti++)
{
fc = (fb - mfrc[ti]) * frlamb + mfrb[ti];
mfrc[ti] = fc;
mfrb[ti] = fb;
tf = mfbuff[ti][ti4];
fb = fc - tf * fa;
fa = fa - tf * fc;
}
tf = tf2;
tf = tf + flpa * mflp; // lowpass post-emphasis filter
mflp = tf;
// Bring up the gain slowly when formant correction goes from disabled
// to enabled, while things stabilize.
if (mfmute > 0.5)
{
tf = tf * (mfmute - 0.5) * 2;
}
else
{
tf = 0;
}
tf2 = mfmutealph;
mfmute = (1 - tf2) + tf2 * mfmute;
// now tf is signal output
// ...and we're done messing with formants
}
else
{
mfmute = 0;
}
// Write audio to output of plugin
// Mix (blend between original (delayed) =0 and processed =1)
*(pfOutput++) = mMix * tf + (1 - mMix) * mcbi[ti4];
}
Add(target->GetBuffer()->GetChannel(0), mWorkingBuffer, bufferSize);
GetVizBuffer()->WriteChunk(mWorkingBuffer, bufferSize, 0);
GetBuffer()->Reset();
// Tell the host the algorithm latency
mLatency = (N - 1);
}
void Autotalent::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mASelector->Draw();
mBbSelector->Draw();
mBSelector->Draw();
mCSelector->Draw();
mDbSelector->Draw();
mDSelector->Draw();
mEbSelector->Draw();
mESelector->Draw();
mFSelector->Draw();
mGbSelector->Draw();
mGSelector->Draw();
mAbSelector->Draw();
mAmountSlider->Draw();
mSmoothSlider->Draw();
mShiftSlider->Draw();
mScwarpSlider->Draw();
mLfoampSlider->Draw();
mLforateSlider->Draw();
mLfoshapeSlider->Draw();
mLfosymmSlider->Draw();
mLfoquantCheckbox->Draw();
mFcorrCheckbox->Draw();
mFwarpSlider->Draw();
mMixSlider->Draw();
mSetFromScaleButton->Draw();
float pitch = mPitch;
while (pitch > 12)
pitch -= 12;
while (pitch < 0)
pitch += 12;
float x = ofMap(pitch, 0, 12, 4, 244);
ofSetColor(255, 0, 255);
ofLine(x, 90, x, 90 - ofMap(mConfidence, 0, 1, 0, 50));
}
void Autotalent::ButtonClicked(ClickButton* button, double time)
{
if (button == mSetFromScaleButton)
{
mA = TheScale->MakeDiatonic(69) == 69 ? 1 : -1;
mBb = TheScale->MakeDiatonic(70) == 70 ? 1 : -1;
mB = TheScale->MakeDiatonic(71) == 71 ? 1 : -1;
mC = TheScale->MakeDiatonic(72) == 72 ? 1 : -1;
mDb = TheScale->MakeDiatonic(73) == 73 ? 1 : -1;
mD = TheScale->MakeDiatonic(74) == 74 ? 1 : -1;
mEb = TheScale->MakeDiatonic(75) == 75 ? 1 : -1;
mE = TheScale->MakeDiatonic(76) == 76 ? 1 : -1;
mF = TheScale->MakeDiatonic(77) == 77 ? 1 : -1;
mGb = TheScale->MakeDiatonic(78) == 78 ? 1 : -1;
mG = TheScale->MakeDiatonic(79) == 79 ? 1 : -1;
mAb = TheScale->MakeDiatonic(80) == 80 ? 1 : -1;
UpdateShiftSlider();
}
}
void Autotalent::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (velocity > 0)
{
mC = (pitch % 12) == 0 ? 1 : -1;
mDb = (pitch % 12) == 1 ? 1 : -1;
mD = (pitch % 12) == 2 ? 1 : -1;
mEb = (pitch % 12) == 3 ? 1 : -1;
mE = (pitch % 12) == 4 ? 1 : -1;
mF = (pitch % 12) == 5 ? 1 : -1;
mGb = (pitch % 12) == 6 ? 1 : -1;
mG = (pitch % 12) == 7 ? 1 : -1;
mAb = (pitch % 12) == 8 ? 1 : -1;
mA = (pitch % 12) == 9 ? 1 : -1;
mBb = (pitch % 12) == 10 ? 1 : -1;
mB = (pitch % 12) == 11 ? 1 : -1;
UpdateShiftSlider();
}
}
void Autotalent::UpdateShiftSlider()
{
int numTones = 1;
if (mA != -1)
++numTones;
if (mBb != -1)
++numTones;
if (mB != -1)
++numTones;
if (mC != -1)
++numTones;
if (mDb != -1)
++numTones;
if (mD != -1)
++numTones;
if (mEb != -1)
++numTones;
if (mE != -1)
++numTones;
if (mF != -1)
++numTones;
if (mGb != -1)
++numTones;
if (mG != -1)
++numTones;
if (mAb != -1)
++numTones;
mShiftSlider->SetExtents(-numTones, numTones);
}
void Autotalent::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void Autotalent::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
``` | /content/code_sandbox/Source/Autotalent.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 9,500 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// PeakTracker.h
// modularSynth
//
// Created by Ryan Challinor on 1/4/14.
//
//
#pragma once
class PeakTracker
{
public:
void Process(float* buffer, int bufferSize);
float GetPeak() const { return mPeak; }
void SetDecayTime(float time) { mDecayTime = time; }
void SetLimit(float limit) { mLimit = limit; }
void Reset() { mPeak = 0; }
double GetLastHitLimitTime() const { return mHitLimitTime; }
private:
float mPeak{ 0 };
float mDecayTime{ .01 };
float mLimit{ -1 };
double mHitLimitTime{ -9999 };
};
``` | /content/code_sandbox/Source/PeakTracker.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 259 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
PulseTrain.cpp
Created: 10 Mar 2020 9:15:47pm
Author: Ryan Challinor
==============================================================================
*/
#include "PulseTrain.h"
#include "OpenFrameworksPort.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "PatchCableSource.h"
PulseTrain::PulseTrain()
{
for (int i = 0; i < kMaxSteps; ++i)
mVels[i] = 1;
}
void PulseTrain::Init()
{
IDrawableModule::Init();
TheTransport->AddListener(this, mInterval, OffsetInfo(0, true), false);
TheTransport->AddAudioPoller(this);
}
void PulseTrain::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mLengthSlider = new IntSlider(this, "length", 3, 2, 96, 15, &mLength, 1, kMaxSteps);
mIntervalSelector = new DropdownList(this, "interval", mLengthSlider, kAnchor_Right, (int*)(&mInterval));
mVelocityGrid = new UIGrid("uigrid", 3, 20, 174, 15, mLength, 1, this);
mIntervalSelector->AddLabel("1n", kInterval_1n);
mIntervalSelector->AddLabel("2n", kInterval_2n);
mIntervalSelector->AddLabel("4n", kInterval_4n);
mIntervalSelector->AddLabel("4nt", kInterval_4nt);
mIntervalSelector->AddLabel("8n", kInterval_8n);
mIntervalSelector->AddLabel("8nt", kInterval_8nt);
mIntervalSelector->AddLabel("16n", kInterval_16n);
mIntervalSelector->AddLabel("16nt", kInterval_16nt);
mIntervalSelector->AddLabel("32n", kInterval_32n);
mIntervalSelector->AddLabel("64n", kInterval_64n);
mIntervalSelector->AddLabel("none", kInterval_None);
mVelocityGrid->SetGridMode(UIGrid::kMultisliderBipolar);
mVelocityGrid->SetRequireShiftForMultislider(true);
mVelocityGrid->SetListener(this);
for (int i = 0; i < kMaxSteps; ++i)
mVelocityGrid->SetVal(i, 0, mVels[i], !K(notifyListener));
for (int i = 0; i < kIndividualStepCables; ++i)
{
mStepCables[i] = new PatchCableSource(this, kConnectionType_Pulse);
mStepCables[i]->SetOverrideCableDir(ofVec2f(0, 1), PatchCableSource::Side::kBottom);
AddPatchCableSource(mStepCables[i]);
}
}
PulseTrain::~PulseTrain()
{
TheTransport->RemoveListener(this);
TheTransport->RemoveAudioPoller(this);
}
void PulseTrain::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
ofSetColor(255, 255, 255, gModuleDrawAlpha);
mIntervalSelector->Draw();
mLengthSlider->Draw();
mVelocityGrid->Draw();
for (int i = 0; i < kIndividualStepCables; ++i)
{
if (i < mLength)
{
ofVec2f pos = mVelocityGrid->GetCellPosition(i, 0) + mVelocityGrid->GetPosition(true);
pos.x += mVelocityGrid->GetWidth() / float(mLength) * .5f;
pos.y += mVelocityGrid->GetHeight() + 8;
mStepCables[i]->SetManualPosition(pos.x, pos.y);
mStepCables[i]->SetEnabled(true);
}
else
{
mStepCables[i]->SetEnabled(false);
}
}
}
void PulseTrain::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void PulseTrain::OnTransportAdvanced(float amount)
{
PROFILER(PulseTrain);
ComputeSliders(0);
}
void PulseTrain::OnTimeEvent(double time)
{
Step(time, 1, 0);
}
void PulseTrain::OnPulse(double time, float velocity, int flags)
{
mStep = 0;
Step(time, velocity, kPulseFlag_Reset);
}
void PulseTrain::Step(double time, float velocity, int flags)
{
if (!mEnabled)
return;
bool isReset = (flags & kPulseFlag_Reset);
if (mStep >= mLength && !isReset)
return;
++mStep;
if (isReset)
mStep = 0;
if (mStep < mLength)
{
float v = mVels[mStep] * velocity;
int new_flags = 0;
if (mResetOnStart && mStep == 0)
new_flags = kPulseFlag_Reset;
if (v > 0)
{
DispatchPulse(GetPatchCableSource(), time, v, new_flags);
if (mStep < kIndividualStepCables)
DispatchPulse(mStepCables[mStep], time, v, new_flags);
}
}
mVelocityGrid->SetHighlightCol(time, mStep);
}
void PulseTrain::GetModuleDimensions(float& width, float& height)
{
width = 180;
height = 52;
}
void PulseTrain::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
mVelocityGrid->TestClick(x, y, right);
}
void PulseTrain::MouseReleased()
{
IDrawableModule::MouseReleased();
mVelocityGrid->MouseReleased();
}
bool PulseTrain::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
mVelocityGrid->NotifyMouseMoved(x, y);
return false;
}
bool PulseTrain::MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll)
{
mVelocityGrid->NotifyMouseScrolled(x, y, scrollX, scrollY, isSmoothScroll, isInvertedScroll);
return false;
}
void PulseTrain::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mIntervalSelector)
{
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
transportListenerInfo->mInterval = mInterval;
}
}
void PulseTrain::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void PulseTrain::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
if (slider == mLengthSlider)
{
mVelocityGrid->SetGrid(mLength, 1);
GridUpdated(mVelocityGrid, 0, 0, 0, 0);
}
}
void PulseTrain::GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue)
{
if (grid == mVelocityGrid)
{
for (int i = 0; i < mVelocityGrid->GetCols(); ++i)
mVels[i] = mVelocityGrid->GetVal(i, 0);
}
}
void PulseTrain::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
mVelocityGrid->SaveState(out);
}
void PulseTrain::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
mVelocityGrid->LoadState(in);
GridUpdated(mVelocityGrid, 0, 0, 0, 0);
}
void PulseTrain::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void PulseTrain::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void PulseTrain::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/PulseTrain.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,925 |
```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
**/
//
// RollingBuffer.h
// modularSynth
//
// Created by Ryan Challinor on 11/25/12.
//
//
#pragma once
#include "FileStream.h"
#include "ChannelBuffer.h"
class RollingBuffer
{
public:
RollingBuffer(int sizeInSamples);
~RollingBuffer();
float GetSample(int samplesAgo, int channel);
void ReadChunk(float* dst, int size, int samplesAgo, int channel);
void WriteChunk(float* samples, int size, int channel);
void Write(float sample, int channel);
void ClearBuffer();
void Draw(int x, int y, int width, int height, int length = -1, int channel = -1, int delayOffset = 0);
int Size() { return mBuffer.BufferSize(); }
ChannelBuffer* GetRawBuffer() { return &mBuffer; }
int GetRawBufferOffset(int channel) { return mOffsetToNow[channel]; }
void Accum(int samplesAgo, float sample, int channel);
void SetNumChannels(int channels) { mBuffer.SetNumActiveChannels(channels); }
int NumChannels() const { return mBuffer.NumActiveChannels(); }
void SaveState(FileStreamOut& out);
void LoadState(FileStreamIn& in);
private:
int mOffsetToNow[ChannelBuffer::kMaxNumChannels]{};
ChannelBuffer mBuffer;
};
``` | /content/code_sandbox/Source/RollingBuffer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 392 |
```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
**/
/*
==============================================================================
NoteStepper.h
Created: 15 Jul 2021 9:11:21pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "INoteSource.h"
#include "Slider.h"
#include "ClickButton.h"
class NoteStepper : public INoteReceiver, public INoteSource, public IDrawableModule, public IIntSliderListener, public IButtonListener
{
public:
NoteStepper();
static IDrawableModule* Create() { return new NoteStepper(); }
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 IntSliderUpdated(IntSlider* slider, int oldVal, double time) override {}
void ButtonClicked(ClickButton* button, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
virtual void SaveLayout(ofxJSONElement& moduleInfo) override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void SendNoteToIndex(int index, double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation);
static const int kMaxDestinations = 16;
std::array<AdditionalNoteCable*, kMaxDestinations> mDestinationCables{};
float mWidth{ 200 };
float mHeight{ 20 };
std::array<int, 128> mLastNoteDestinations{};
int mCurrentDestinationIndex{ -1 };
ClickButton* mResetButton{ nullptr };
int mLength{ 4 };
IntSlider* mLengthSlider{ nullptr };
double mLastNoteOnTime{ -9999 };
bool mAllowChords{ false };
};
``` | /content/code_sandbox/Source/NoteStepper.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 596 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// InputChannel.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/16/12.
//
//
#include "InputChannel.h"
#include "ModularSynth.h"
#include "Profiler.h"
InputChannel::InputChannel()
: IAudioProcessor(gBufferSize)
{
}
InputChannel::~InputChannel()
{
}
void InputChannel::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mChannelSelector = new DropdownList(this, "ch", 3, 3, &mChannelSelectionIndex);
for (int i = 0; i < TheSynth->GetNumInputChannels(); ++i)
mChannelSelector->AddLabel(ofToString(i + 1), i);
mStereoSelectionOffset = mChannelSelector->GetNumValues(); //after this, the stereo pairs
for (int i = 0; i < TheSynth->GetNumInputChannels() - 1; ++i)
mChannelSelector->AddLabel(ofToString(i + 1) + "&" + ofToString(i + 2), mChannelSelector->GetNumValues());
mChannelSelector->DrawLabel(true);
mChannelSelector->SetWidth(43);
}
void InputChannel::Process(double time)
{
PROFILER(InputChannel);
if (!mEnabled)
return;
int channelSelectionIndex = mChannelSelectionIndex;
int numChannels = 1;
if (mChannelSelectionIndex >= mStereoSelectionOffset)
numChannels = 2;
SyncBuffers(numChannels);
IAudioReceiver* target = GetTarget();
if (mChannelSelectionIndex < mStereoSelectionOffset) //mono
{
float* buffer = gZeroBuffer;
int channel = mChannelSelectionIndex;
if (channel >= 0 && channel < TheSynth->GetNumInputChannels())
buffer = TheSynth->GetInputBuffer(channel);
if (target)
Add(target->GetBuffer()->GetChannel(0), buffer, gBufferSize);
GetVizBuffer()->WriteChunk(buffer, gBufferSize, 0);
}
else //stereo
{
float* buffer1 = gZeroBuffer;
float* buffer2 = gZeroBuffer;
int channel1 = channelSelectionIndex - mStereoSelectionOffset;
if (channel1 >= 0 && channel1 < TheSynth->GetNumInputChannels())
buffer1 = TheSynth->GetInputBuffer(channel1);
int channel2 = channel1 + 1;
if (channel2 >= 0 && channel2 < TheSynth->GetNumInputChannels())
buffer2 = TheSynth->GetInputBuffer(channel2);
if (target)
{
Add(target->GetBuffer()->GetChannel(0), buffer1, gBufferSize);
Add(target->GetBuffer()->GetChannel(1), buffer2, gBufferSize);
}
GetVizBuffer()->WriteChunk(buffer1, gBufferSize, 0);
GetVizBuffer()->WriteChunk(buffer2, gBufferSize, 1);
}
}
void InputChannel::DrawModule()
{
mChannelSelector->Draw();
if (gHoveredUIControl == mChannelSelector && TheSynth->GetNumInputChannels() == 0)
TheSynth->SetNextDrawTooltip("selected input device has zero channels. choose a new audio_input_device in 'settings'.");
}
void InputChannel::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadEnum<int>("channels", moduleInfo, 0, mChannelSelector);
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void InputChannel::SetUpFromSaveData()
{
mChannelSelectionIndex = mModuleSaveData.GetEnum<int>("channels");
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
``` | /content/code_sandbox/Source/InputChannel.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 919 |
```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
**/
/*
==============================================================================
TakeRecorder.h
Created: 9 Aug 2017 11:31:57pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "Slider.h"
class TakeRecorder : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public IIntSliderListener
{
public:
TakeRecorder();
virtual ~TakeRecorder();
static IDrawableModule* Create() { return new TakeRecorder(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IAudioProcessor
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 = 120;
h = 22;
}
float mStartSeconds{ 0 };
FloatSlider* mStartSecondsSlider{ nullptr };
};
``` | /content/code_sandbox/Source/TakeRecorder.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 455 |
```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
**/
//
// Scale.h
// modularSynth
//
// Created by Ryan Challinor on 11/24/12.
//
//
#pragma once
#include "IDrawableModule.h"
#include "DropdownList.h"
#include "LFO.h"
#include "Chord.h"
#include "ChordDatabase.h"
#include <atomic>
class IScaleListener
{
public:
virtual ~IScaleListener() {}
virtual void OnScaleChanged() = 0;
};
struct Accidental
{
Accidental(int pitch, int direction)
: mPitch(pitch)
, mDirection(direction)
{}
int mPitch;
int mDirection;
};
inline bool operator==(const Accidental& lhs, const Accidental& rhs)
{
return lhs.mPitch == rhs.mPitch && lhs.mDirection == rhs.mDirection;
}
struct ScalePitches
{
int mScaleRoot{ 0 };
std::string mScaleType;
std::vector<int> mScalePitches[2]; //double-buffered to avoid thread safety issues when modifying
std::atomic<int> mScalePitchesFlip{ 0 };
std::vector<Accidental> mAccidentals;
void SetRoot(int root);
void SetScaleType(std::string type);
void SetAccidentals(const std::vector<Accidental>& accidentals);
const std::vector<int>& GetPitches() const { return mScalePitches[mScalePitchesFlip]; }
int ScaleRoot() const { return mScaleRoot; }
std::string GetType() const { return mScaleType; }
void GetChordDegreeAndAccidentals(const Chord& chord, int& degree, std::vector<Accidental>& accidentals) const;
int GetScalePitch(int index) const;
bool IsRoot(int pitch) const;
bool IsInPentatonic(int pitch) const;
bool IsInScale(int pitch) const;
int GetPitchFromTone(int n) const;
int GetToneFromPitch(int pitch) const;
int NumTonesInScale() const;
};
class MTSClient;
class Scale : public IDrawableModule, public IDropdownListener, public IFloatSliderListener, public IIntSliderListener, public ITextEntryListener, public IButtonListener
{
public:
Scale();
~Scale();
void Init() override;
void CreateUIControls() override;
bool IsSingleton() const override { return true; }
int MakeDiatonic(int pitch);
bool IsRoot(int pitch);
bool IsInPentatonic(int pitch);
bool IsInScale(int pitch);
int GetPitchFromTone(int n);
int GetToneFromPitch(int pitch);
void SetScale(int root, std::string type);
int ScaleRoot() { return mScale.mScaleRoot; }
std::string GetType() { return mScale.mScaleType; }
void SetRoot(int root, bool force = true);
void SetScaleType(std::string type, bool force = true);
void AddListener(IScaleListener* listener);
void RemoveListener(IScaleListener* listener);
void ClearListeners();
void Poll() override;
void SetScaleDegree(int degree);
int GetScaleDegree() { return mScaleDegree; }
void SetAccidentals(const std::vector<Accidental>& accidentals);
void GetChordDegreeAndAccidentals(const Chord& chord, int& degree, std::vector<Accidental>& accidentals);
ScalePitches& GetScalePitches() { return mScale; }
std::vector<int> GetPitchesForScale(std::string type);
void SetRandomSeptatonicScale();
int GetNumScaleTypes() { return (int)mScales.size(); }
std::string GetScaleName(int index) { return mScales[index].mName; }
int NumTonesInScale() const { return mScale.NumTonesInScale(); }
int GetPitchesPerOctave() const { return MAX(1, mPitchesPerOctave); }
float PitchToFreq(float pitch);
float FreqToPitch(float freq);
const ChordDatabase& GetChordDatabase() const { return mChordDatabase; }
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 TextEntryComplete(TextEntry* entry) override;
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 1; }
bool IsEnabled() const override { return true; }
private:
struct ScaleInfo
{
ScaleInfo() {}
ScaleInfo(std::string name, std::vector<int> pitches)
: mName(name)
, mPitches(pitches)
{}
std::string mName;
std::vector<int> mPitches;
};
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void NotifyListeners();
void SetUpRootList();
float RationalizeNumber(float input);
void UpdateTuningTable();
float GetTuningTableRatio(int semitonesFromCenter);
void SetRandomRootAndScale();
enum IntonationMode
{
kIntonation_Equal,
kIntonation_Just,
kIntonation_Pythagorean,
kIntonation_Meantone,
kIntonation_Rational,
kIntonation_SclFile,
kIntonation_Oddsound
};
ScalePitches mScale;
std::list<IScaleListener*> mListeners;
DropdownList* mRootSelector{ nullptr };
DropdownList* mScaleSelector{ nullptr };
IntSlider* mScaleDegreeSlider{ nullptr };
int mScaleDegree{ 0 };
ClickButton* mLoadSCLButton{ nullptr };
ClickButton* mLoadKBMButton{ nullptr };
ClickButton* mQueuedButtonPress{ nullptr };
std::vector<ScaleInfo> mScales;
int mNumSeptatonicScales{ 0 };
int mScaleIndex{ 0 };
int mPitchesPerOctave{ 12 };
float mReferenceFreq{ 440 };
float mReferencePitch{ 69 };
TextEntry* mPitchesPerOctaveEntry{ nullptr };
TextEntry* mReferenceFreqEntry{ nullptr };
TextEntry* mReferencePitchEntry{ nullptr };
IntonationMode mIntonation{ IntonationMode::kIntonation_Equal };
DropdownList* mIntonationSelector{ nullptr };
std::array<float, 256> mTuningTable{};
ChordDatabase mChordDatabase;
MTSClient* mOddsoundMTSClient{ nullptr };
std::string mSclContents;
std::string mKbmContents;
std::string mCustomScaleDescription;
bool mWantSetRandomRootAndScale{ false };
};
extern Scale* TheScale;
``` | /content/code_sandbox/Source/Scale.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,690 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without 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.cpp
// Bespoke
//
// Created by Ryan Challinor on 2/10/15.
//
//
#include "ComboGridController.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
ComboGridController::ComboGridController()
{
assert(false);
}
void ComboGridController::CreateUIControls()
{
IDrawableModule::CreateUIControls();
}
void ComboGridController::Init()
{
IDrawableModule::Init();
InitializeCombo();
}
void ComboGridController::InitializeCombo()
{
//for (int i=0; i<mGrids.size(); ++i)
// mGrids[i]->SetTarget(this);
mCols = 0;
mRows = 0;
mArrangement = mModuleSaveData.GetEnum<Arrangements>("arrangement");
if (mArrangement == kHorizontal)
{
for (int i = 0; i < mGrids.size(); ++i)
{
mCols += mGrids[i]->NumCols();
mRows = MAX(mRows, mGrids[i]->NumRows());
}
}
else if (mArrangement == kVertical)
{
for (int i = 0; i < mGrids.size(); ++i)
{
mCols = MAX(mCols, mGrids[i]->NumCols());
mRows += mGrids[i]->NumRows();
}
}
else if (mArrangement == kSquare)
{
assert(false); //TODO(Ryan) implement
}
}
void ComboGridController::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
}
void ComboGridController::OnGridButton(int x, int y, float velocity, IGridController* grid)
{
if (mArrangement == kHorizontal)
{
for (int i = 0; i < mGrids.size(); ++i)
{
if (mGrids[i] == grid)
break;
x += mGrids[i]->NumCols();
}
}
else if (mArrangement == kVertical)
{
for (int i = 0; i < mGrids.size(); ++i)
{
if (mGrids[i] == grid)
break;
y += mGrids[i]->NumRows();
}
}
else if (mArrangement == kSquare)
{
assert(false); //TODO(Ryan) implement
}
for (auto cable : GetPatchCableSource()->GetPatchCables())
{
auto* listener = dynamic_cast<IGridControllerListener*>(cable->GetTarget());
if (listener)
listener->OnGridButton(x, y, velocity, this);
}
GetPatchCableSource()->AddHistoryEvent(gTime, HasInput());
}
bool ComboGridController::HasInput() const
{
for (int i = 0; i < mGrids.size(); ++i)
{
if (mGrids[i]->HasInput())
return true;
}
return false;
}
void ComboGridController::SetLight(int x, int y, GridColor color, bool force)
{
if (mArrangement == kHorizontal)
{
for (int i = 0; i < mGrids.size(); ++i)
{
if (x < mGrids[i]->NumCols())
{
mGrids[i]->SetLight(x, y, color, force);
break;
}
x -= mGrids[i]->NumCols();
}
}
else if (mArrangement == kVertical)
{
for (int i = 0; i < mGrids.size(); ++i)
{
if (y < mGrids[i]->NumRows())
{
mGrids[i]->SetLight(x, y, color, force);
break;
}
y -= mGrids[i]->NumRows();
}
}
else if (mArrangement == kSquare)
{
assert(false); //TODO(Ryan) implement
}
}
void ComboGridController::SetLightDirect(int x, int y, int color, bool force)
{
assert(false); //TODO(Ryan) implement, maybe
}
void ComboGridController::ResetLights()
{
for (int i = 0; i < mCols; ++i)
{
for (int j = 0; j < mRows; ++j)
{
SetLight(i, j, kGridColorOff);
}
}
}
void ComboGridController::GetModuleDimensions(float& w, float& h)
{
w = 0;
h = 0;
}
void ComboGridController::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("grids", moduleInfo);
EnumMap map;
map["horizontal"] = kHorizontal;
map["vertical"] = kVertical;
map["square"] = kSquare;
mModuleSaveData.LoadEnum<Arrangements>("arrangement", moduleInfo, kHorizontal, nullptr, &map);
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void ComboGridController::SaveLayout(ofxJSONElement& moduleInfo)
{
std::string grids = "";
for (int i = 0; i < mGrids.size(); ++i)
{
IDrawableModule* grid = dynamic_cast<IDrawableModule*>(mGrids[i]);
if (grid)
{
grids += grid->Name();
if (i < mGrids.size() - 1)
grids += ",";
}
}
moduleInfo["grids"] = grids;
}
void ComboGridController::SetUpFromSaveData()
{
std::string grids = mModuleSaveData.GetString("grids");
std::vector<std::string> gridVec = ofSplitString(grids, ",");
mGrids.clear();
if (grids != "")
{
for (int i = 0; i < gridVec.size(); ++i)
mGrids.push_back(dynamic_cast<IGridController*>(TheSynth->FindModule(gridVec[i])));
}
//for (int i=0; i<mGrids.size(); ++i)
// mGrids[i]->SetTarget(this);
SetUpPatchCables(mModuleSaveData.GetString("target"));
InitializeCombo();
}
``` | /content/code_sandbox/Source/ComboGridController.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,482 |
```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
**/
/*
==============================================================================
PitchPanner.h
Created: 25 Mar 2018 9:57:23am
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "INoteSource.h"
#include "Slider.h"
class PitchPanner : public NoteEffectBase, public IDrawableModule, public IIntSliderListener
{
public:
PitchPanner();
static IDrawableModule* Create() { return new PitchPanner(); }
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 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& width, float& height) override
{
width = 108;
height = 40;
}
int mPitchLeft;
IntSlider* mPitchLeftSlider;
int mPitchRight;
IntSlider* mPitchRightSlider;
};
``` | /content/code_sandbox/Source/PitchPanner.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 445 |
```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
**/
//
// FreqDelay.h
// modularSynth
//
// Created by Ryan Challinor on 5/10/13.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "INoteReceiver.h"
#include "DelayEffect.h"
#include "Slider.h"
class FreqDelay : public IAudioProcessor, public IDrawableModule, public INoteReceiver, public IFloatSliderListener
{
public:
FreqDelay();
virtual ~FreqDelay();
static IDrawableModule* Create() { return new FreqDelay(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//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 {}
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 130;
height = 120;
}
ChannelBuffer mDryBuffer;
float mDryWet{ 1 };
FloatSlider* mDryWetSlider{ nullptr };
DelayEffect mDelayEffect;
};
``` | /content/code_sandbox/Source/FreqDelay.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 481 |
```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
**/
//
// Minimap.h
// Bespoke
//
// Created by Ryan Challinor on 09/25/21.
//
//
#pragma once
#include "IDrawableModule.h"
#include "UIGrid.h"
class Minimap : public IDrawableModule
{
public:
Minimap();
~Minimap();
void CreateUIControls() override;
void DrawModule() override;
bool AlwaysOnTop() override { return true; };
void GetDimensions(float& width, float& height) override;
void GetDimensionsMinimap(float& width, float& height);
private:
bool IsSingleton() const override { return true; };
bool HasTitleBar() const override { return false; };
bool IsSaveable() override { return false; }
void ComputeBoundingBox(ofRectangle& rect);
ofRectangle CoordsToMinimap(ofRectangle& boundingBox, ofRectangle& source);
void DrawModulesOnMinimap(ofRectangle& boundingBox);
void RectUnion(ofRectangle& target, ofRectangle& unionRect);
void OnClicked(float x, float y, bool right) override;
void MouseReleased() override;
bool MouseMoved(float x, float y) override;
ofVec2f CoordsToViewport(ofRectangle& boundingBox, float x, float y);
void ForcePosition();
bool mClick{ false };
UIGrid* mGrid{ nullptr };
GridCell mHoveredBookmarkPos{ -1, -1 };
};
``` | /content/code_sandbox/Source/Minimap.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 407 |
```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
**/
//
// SampleVoice.h
// modularSynth
//
// Created by Ryan Challinor on 2/5/14.
//
//
#pragma once
#include "IMidiVoice.h"
#include "IVoiceParams.h"
#include "ADSR.h"
#include "EnvOscillator.h"
class IDrawableModule;
class SampleVoiceParams : public IVoiceParams
{
public:
::ADSR mAdsr{ 10, 0, 1, 10 };
float mVol{ 1 };
float* mSampleData{ nullptr };
int mSampleLength{ 0 };
float mDetectedFreq{ -1 };
bool mLoop{ false };
};
class SampleVoice : public IMidiVoice
{
public:
SampleVoice(IDrawableModule* owner = nullptr);
~SampleVoice();
// 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:
::ADSR mAdsr;
SampleVoiceParams* mVoiceParams{};
float mPos{ 0 };
IDrawableModule* mOwner{ nullptr };
};
``` | /content/code_sandbox/Source/SampleVoice.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 380 |
```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
**/
//
// ModuleSaveDataPanel.h
// modularSynth
//
// Created by Ryan Challinor on 1/28/14.
//
//
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "Checkbox.h"
#include "Slider.h"
#include "TextEntry.h"
#include "DropdownList.h"
#include "ClickButton.h"
#include "ModuleSaveData.h"
class ModuleSaveDataPanel;
extern ModuleSaveDataPanel* TheSaveDataPanel;
class ModuleSaveDataPanel : public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public ITextEntryListener, public IDropdownListener, public IButtonListener
{
public:
ModuleSaveDataPanel();
~ModuleSaveDataPanel();
static IDrawableModule* Create() { return new ModuleSaveDataPanel(); }
static bool CanCreate() { return TheSaveDataPanel == nullptr; }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
std::string GetTitleLabel() const override { return ""; }
bool AlwaysOnTop() override { return true; }
bool CanMinimize() override { return false; }
bool IsSingleton() const override { return true; }
void Poll() override;
void SetModule(IDrawableModule* module);
IDrawableModule* GetModule() { return mSaveModule; }
void UpdatePosition();
void ReloadSaveData();
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void TextEntryComplete(TextEntry* entry) override;
void DropdownClicked(DropdownList* list) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
bool IsSaveable() override { return false; }
bool IsEnabled() const override { return true; }
static void LoadPreset(IDrawableModule* module, std::string presetFilePath);
private:
void ApplyChanges();
void FillDropdownList(DropdownList* list, ModuleSaveData::SaveVal* save);
void RefreshPresetFiles();
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
IDrawableModule* mSaveModule{ nullptr };
TextEntry* mNameEntry{ nullptr };
DropdownList* mPresetFileSelector{ nullptr };
ClickButton* mSavePresetAsButton{ nullptr };
std::vector<IUIControl*> mSaveDataControls;
std::vector<std::string> mLabels;
ClickButton* mApplyButton{ nullptr };
ClickButton* mDeleteButton{ nullptr };
Checkbox* mDrawDebugCheckbox{ nullptr };
ClickButton* mResetSequencerButton{ nullptr };
TextEntry* mTransportPriorityEntry{ nullptr };
std::map<DropdownList*, ModuleSaveData::SaveVal*> mStringDropdowns;
int mHeight{ 100 };
float mAppearAmount{ 0 };
float mAlignmentX{ 100 };
int mPresetFileIndex{ 0 };
bool mPresetFileUpdateQueued{ false };
std::vector<std::string> mPresetFilePaths;
};
``` | /content/code_sandbox/Source/ModuleSaveDataPanel.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 841 |
```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
**/
//
// AudioRouter.h
// modularSynth
//
// Created by Ryan Challinor on 4/7/13.
//
//
#pragma once
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "RadioButton.h"
#include "Ramp.h"
class AudioRouter : public IAudioProcessor, public IDrawableModule, public IRadioButtonListener
{
public:
AudioRouter();
virtual ~AudioRouter();
static IDrawableModule* Create() { return new AudioRouter(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Poll() override;
void SetActiveIndex(int index) { mRouteIndex = index; }
//IAudioSource
void Process(double time) override;
int GetNumTargets() override { return (int)mDestinationCables.size() + 1; }
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
//IRadioButtonListener
void RadioButtonUpdated(RadioButton* button, int oldVal, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
virtual void SaveLayout(ofxJSONElement& moduleInfo) override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override;
int mRouteIndex{ 0 };
RadioButton* mRouteSelector{ nullptr };
std::vector<PatchCableSource*> mDestinationCables;
RollingBuffer mBlankVizBuffer;
std::array<Ramp, 16> mSwitchAndRampIn;
int mLastProcessedRouteIndex{ 0 };
bool mOnlyShowActiveCable{ false };
};
``` | /content/code_sandbox/Source/AudioRouter.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 524 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
PitchToSpeed.cpp
Created: 28 Nov 2017 9:44:15pm
Author: Ryan Challinor
==============================================================================
*/
#include "PitchToSpeed.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
#include "ModulationChain.h"
PitchToSpeed::PitchToSpeed()
{
}
PitchToSpeed::~PitchToSpeed()
{
}
void PitchToSpeed::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mTargetCable = new PatchCableSource(this, kConnectionType_Modulator);
mTargetCable->SetModulatorOwner(this);
AddPatchCableSource(mTargetCable);
mReferenceFreqSlider = new FloatSlider(this, "ref freq", 3, 2, 100, 15, &mReferenceFreq, 10, 1000);
}
void PitchToSpeed::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mReferenceFreqSlider->Draw();
}
void PitchToSpeed::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
OnModulatorRepatch();
}
void PitchToSpeed::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mEnabled && velocity > 0)
{
mPitch = pitch;
mPitchBend = modulation.pitchBend;
}
}
float PitchToSpeed::Value(int samplesIn)
{
float bend = mPitchBend ? mPitchBend->GetValue(samplesIn) : 0;
return TheScale->PitchToFreq(mPitch + bend) / mReferenceFreq;
}
void PitchToSpeed::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void PitchToSpeed::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void PitchToSpeed::SetUpFromSaveData()
{
}
``` | /content/code_sandbox/Source/PitchToSpeed.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 523 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
UnstableModWheel.cpp
Created: 2 Mar 2021 7:48:49pm
Author: Ryan Challinor
==============================================================================
*/
#include "UnstableModWheel.h"
#include "OpenFrameworksPort.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
UnstableModWheel::UnstableModWheel()
{
for (int voice = 0; voice < kNumVoices; ++voice)
mModulation.GetModWheel(voice)->CreateBuffer();
}
void UnstableModWheel::Init()
{
IDrawableModule::Init();
TheTransport->AddAudioPoller(this);
}
UnstableModWheel::~UnstableModWheel()
{
TheTransport->RemoveAudioPoller(this);
}
void UnstableModWheel::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK(3, 40, 140);
FLOATSLIDER(mAmountSlider, "amount", &mPerlin.mPerlinAmount, 0, 1);
FLOATSLIDER(mWarbleSlider, "warble", &mPerlin.mPerlinWarble, 0, 1);
FLOATSLIDER(mNoiseSlider, "noise", &mPerlin.mPerlinNoise, 0, 1);
ENDUIBLOCK(mWidth, mHeight);
mWarbleSlider->SetMode(FloatSlider::kSquare);
mNoiseSlider->SetMode(FloatSlider::kSquare);
}
void UnstableModWheel::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
ofPushStyle();
ofRectangle rect(3, 3, mWidth - 6, 34);
const int kGridSize = 30;
ofFill();
for (int col = 0; col < kGridSize; ++col)
{
float x = rect.x + col * (rect.width / kGridSize);
float y = rect.y;
float val = mPerlin.GetValue(gTime, x / rect.width * 10, 0) * ofClamp(mPerlin.mPerlinAmount * 5, 0, 1);
ofSetColor(val * 255, 0, val * 255);
ofRect(x, y, (rect.width / kGridSize) + .5f, rect.height + .5f, 0);
}
ofNoFill();
ofSetColor(0, 255, 0, 90);
for (int voice = 0; voice < kNumVoices; ++voice)
{
if (mIsVoiceUsed[voice])
{
ofBeginShape();
for (int i = 0; i < gBufferSize; ++i)
{
float sample = ofClamp(mModulation.GetModWheel(voice)->GetBufferValue(i), -1, 1);
ofVertex((i * rect.width) / gBufferSize + rect.x, rect.y + (1 - sample) * rect.height);
}
ofEndShape();
}
}
ofPopStyle();
mAmountSlider->Draw();
mWarbleSlider->Draw();
mNoiseSlider->Draw();
}
void UnstableModWheel::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (mEnabled)
{
if (voiceIdx == -1)
{
if (velocity > 0)
{
bool foundVoice = false;
for (size_t i = 0; i < mIsVoiceUsed.size(); ++i)
{
int voiceToCheck = (i + mVoiceRoundRobin) % kNumVoices;
if (mIsVoiceUsed[voiceToCheck] == false)
{
voiceIdx = voiceToCheck;
mVoiceRoundRobin = (mVoiceRoundRobin + 1) % kNumVoices;
foundVoice = true;
break;
}
}
if (!foundVoice)
{
voiceIdx = mVoiceRoundRobin;
mVoiceRoundRobin = (mVoiceRoundRobin + 1) % kNumVoices;
}
}
else
{
voiceIdx = mPitchToVoice[pitch];
}
}
if (voiceIdx < 0 || voiceIdx >= kNumVoices)
voiceIdx = 0;
mIsVoiceUsed[voiceIdx] = velocity > 0;
mPitchToVoice[pitch] = (velocity > 0) ? voiceIdx : -1;
mModulation.GetModWheel(voiceIdx)->AppendTo(modulation.modWheel);
modulation.modWheel = mModulation.GetModWheel(voiceIdx);
}
FillModulationBuffer(time, voiceIdx);
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
void UnstableModWheel::OnTransportAdvanced(float amount)
{
ComputeSliders(0);
for (int voice = 0; voice < kNumVoices; ++voice)
{
if (mIsVoiceUsed[voice])
FillModulationBuffer(gTime, voice);
}
}
void UnstableModWheel::FillModulationBuffer(double time, int voiceIdx)
{
for (int i = 0; i < gBufferSize; ++i)
gWorkBuffer[i] = ofMap(mPerlin.GetValue(time + i * gInvSampleRateMs, (time + i * gInvSampleRateMs) / 1000, voiceIdx), 0, 1, 0, mPerlin.mPerlinAmount);
mModulation.GetModWheel(voiceIdx)->FillBuffer(gWorkBuffer);
}
void UnstableModWheel::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void UnstableModWheel::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
if (!mEnabled)
{
for (size_t i = 0; i < mIsVoiceUsed.size(); ++i)
mIsVoiceUsed[i] = false;
}
}
}
void UnstableModWheel::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void UnstableModWheel::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/UnstableModWheel.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,468 |
```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
**/
//
// NamedMutex.h
// modularSynth
//
// Created by Ryan Challinor on 1/20/14.
//
//
#pragma once
#include "OpenFrameworksPort.h"
class NamedMutex
{
public:
void Lock(std::string locker);
void Unlock();
private:
ofMutex mMutex;
std::string mLocker{ "<none>" };
int mExtraLockCount{ 0 };
};
class ScopedMutex
{
public:
ScopedMutex(NamedMutex* mutex, std::string locker);
~ScopedMutex();
private:
NamedMutex* mMutex;
};
``` | /content/code_sandbox/Source/NamedMutex.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
**/
/*
==============================================================================
ScriptModule.h
Created: 19 Apr 2020 1:52:34pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "OpenFrameworksPort.h"
#include "CodeEntry.h"
#include "ClickButton.h"
#include "NoteEffectBase.h"
#include "IPulseReceiver.h"
#include "Slider.h"
#include "DropdownList.h"
#include "ModulationChain.h"
#include "MidiController.h"
#include "juce_osc/juce_osc.h"
class ScriptModule : public IDrawableModule, public IButtonListener, public NoteEffectBase, public IPulseReceiver, public ICodeEntryListener, public IFloatSliderListener, public IDropdownListener, private juce::OSCReceiver, private juce::OSCReceiver::Listener<juce::OSCReceiver::MessageLoopCallback>
{
public:
ScriptModule();
virtual ~ScriptModule();
static IDrawableModule* Create() { return new ScriptModule(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return true; }
static void UninitializePython();
static void InitializePythonIfNecessary();
static void CheckIfPythonEverSuccessfullyInitialized();
void CreateUIControls() override;
void Poll() override;
void PlayNoteFromScript(float pitch, float velocity, float pan, int noteOutputIndex);
void PlayNoteFromScriptAfterDelay(float pitch, float velocity, double delayMeasureTime, float pan, int noteOutputIndex);
void SendCCFromScript(int control, int value, int noteOutputIndex);
void ScheduleMethod(std::string method, double delayMeasureTime);
void ScheduleUIControlValue(IUIControl* control, float value, double delayMeasureTime);
void HighlightLine(int lineNum, int scriptModuleIndex);
void PrintText(std::string text);
IUIControl* GetUIControl(std::string path);
void Stop();
double GetScheduledTime(double delayMeasureTime);
void SetNumNoteOutputs(int num);
void ConnectOscInput(int port);
void MidiReceived(MidiMessageType messageType, int control, float value, int channel);
void OnModuleReferenceBound(IDrawableModule* target);
void SetContext();
void ClearContext();
bool IsScriptTrusted() const { return !mIsScriptUntrusted; }
void RunCode(double time, std::string code);
void OnPulse(double time, float velocity, int flags) override;
void ButtonClicked(ClickButton* button, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldValue, double time) override {}
void DropdownClicked(DropdownList* list) override;
void DropdownUpdated(DropdownList* list, int oldValue, double time) override;
//ICodeEntryListener
void ExecuteCode() override;
std::pair<int, int> ExecuteBlock(int lineStart, int lineEnd) override;
void OnCodeUpdated() override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
//OSCReceiver
void oscMessageReceived(const juce::OSCMessage& msg) override;
bool HasDebugDraw() const override { return true; }
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 2; }
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveLayout(ofxJSONElement& moduleInfo) override;
static std::vector<ScriptModule*> sScriptModules;
static std::list<ScriptModule*> sScriptsRequestingInitExecution;
static ScriptModule* sMostRecentLineExecutedModule;
static ScriptModule* sPriorExecutedModule;
static float GetScriptMeasureTime();
static float GetTimeSigRatio();
static std::string sBackgroundTextString;
static float sBackgroundTextSize;
static ofVec2f sBackgroundTextPos;
static ofColor sBackgroundTextColor;
static bool sPythonInitialized;
static bool sHasPythonEverSuccessfullyInitialized;
static bool sHasLoadedUntrustedScript;
static double sMostRecentRunTime;
ModulationChain* GetPitchBend(int pitch) { return &mPitchBends[pitch]; }
ModulationChain* GetModWheel(int pitch) { return &mModWheels[pitch]; }
ModulationChain* GetPressure(int pitch) { return &mPressures[pitch]; }
static std::string GetBootstrapImportString() { return "import bespoke; import module; import scriptmodule; import random; import math"; }
bool IsEnabled() const override { return true; }
private:
void PlayNote(double time, float pitch, float velocity, float pan, int noteOutputIndex, int lineNum);
void AdjustUIControl(IUIControl* control, float value, double time, int lineNum);
std::pair<int, int> RunScript(double time, int lineStart = -1, int lineEnd = -1);
void FixUpCode(std::string& code);
void ScheduleNote(double time, float pitch, float velocity, float pan, int noteOutputIndex);
void SendNoteToIndex(int index, double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation);
std::string GetThisName();
std::string GetIndentation(std::string line);
std::string GetMethodPrefix();
bool ShouldDisplayLineExecutionPre(std::string priorLine, std::string line);
void GetFirstAndLastCharacter(std::string line, char& first, char& last);
bool IsNonWhitespace(std::string line);
void DrawTimer(int lineNum, double startTime, double endTime, ofColor color, bool filled);
void RefreshScriptFiles();
void RefreshStyleFiles();
void Reset();
juce::String GetScriptChecksum() const;
void RecordScriptAsTrusted();
//IDrawableModule
void DrawModule() override;
void DrawModuleUnclipped() override;
void GetModuleDimensions(float& width, float& height) override;
bool IsResizable() const override { return true; }
void Resize(float w, float h) override;
void OnClicked(float x, float y, bool right) override;
bool MouseMoved(float x, float y) override;
//IPatchable
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
ClickButton* mPythonInstalledConfirmButton{ nullptr };
DropdownList* mLoadScriptSelector{ nullptr };
ClickButton* mLoadScriptButton{ nullptr };
ClickButton* mSaveScriptButton{ nullptr };
ClickButton* mShowReferenceButton{ nullptr };
CodeEntry* mCodeEntry{ nullptr };
ClickButton* mRunButton{ nullptr };
ClickButton* mStopButton{ nullptr };
FloatSlider* mASlider{ nullptr };
FloatSlider* mBSlider{ nullptr };
FloatSlider* mCSlider{ nullptr };
FloatSlider* mDSlider{ nullptr };
ClickButton* mTrustScriptButton{ nullptr };
ClickButton* mDontTrustScriptButton{ nullptr };
int mLoadScriptIndex{ 0 };
std::string mLoadedScriptPath;
juce::Time mLoadedScriptFiletime;
bool mHotloadScripts{ false };
bool mDrawBoundModuleConnections{ true };
static ofxJSONElement sStyleJSON;
float mA{ 0 };
float mB{ 0 };
float mC{ 0 };
float mD{ 0 };
float mWidth{ 200 };
float mHeight{ 20 };
std::array<double, 20> mScheduledPulseTimes{};
std::string mLastError;
size_t mScriptModuleIndex;
std::string mLastRunLiteralCode;
int mNextLineToExecute{ -1 };
int mInitExecutePriority{ 0 };
int mOscInputPort{ -1 };
bool mIsScriptUntrusted{ false };
struct ScheduledNoteOutput
{
double startTime{ 0 };
double time{ 0 };
float pitch{ 0 };
float velocity{ 0 };
float pan{ .5 };
int noteOutputIndex{ -1 };
int lineNum{ -1 };
};
std::array<ScheduledNoteOutput, 200> mScheduledNoteOutput;
struct ScheduledMethodCall
{
double startTime{ 0 };
double time{ 0 };
std::string method;
int lineNum{ -1 };
};
std::array<ScheduledMethodCall, 50> mScheduledMethodCall;
struct ScheduledUIControlValue
{
double startTime{ 0 };
double time{ 0 };
IUIControl* control{ nullptr };
float value{ 0 };
int lineNum{ -1 };
};
std::array<ScheduledUIControlValue, 50> mScheduledUIControlValue;
struct PendingNoteInput
{
double time{ 0 };
int pitch{ 0 };
int velocity{ 0 };
};
std::array<PendingNoteInput, 50> mPendingNoteInput;
struct PrintDisplay
{
double time{ 0 };
std::string text;
int lineNum{ -1 };
};
std::array<PrintDisplay, 10> mPrintDisplay;
struct UIControlModificationDisplay
{
double time{ 0 };
ofVec2f position;
float value{ 0 };
int lineNum{ -1 };
};
std::array<UIControlModificationDisplay, 10> mUIControlModifications;
class LineEventTracker
{
public:
LineEventTracker()
{
for (size_t i = 0; i < mTimes.size(); ++i)
mTimes[i] = -999;
}
void AddEvent(int lineNum, std::string text = "")
{
if (lineNum >= 0 && lineNum < (int)mTimes.size())
{
mTimes[lineNum] = gTime;
mText[lineNum] = text;
}
}
void Draw(CodeEntry* codeEntry, int style, ofColor color);
private:
std::array<double, 256> mTimes{};
std::array<std::string, 256> mText{};
};
LineEventTracker mLineExecuteTracker;
LineEventTracker mMethodCallTracker;
LineEventTracker mNotePlayTracker;
LineEventTracker mUIControlTracker;
struct BoundModuleConnection
{
int mLineIndex{ -1 };
std::string mLineText;
IDrawableModule* mTarget{ nullptr };
};
std::vector<BoundModuleConnection> mBoundModuleConnections;
std::vector<std::string> mScriptFilePaths;
std::vector<AdditionalNoteCable*> mExtraNoteOutputs{};
std::array<ModulationChain, 128> mPitchBends{ ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend, ModulationParameters::kDefaultPitchBend };
std::array<ModulationChain, 128> mModWheels{ ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel, ModulationParameters::kDefaultModWheel };
std::array<ModulationChain, 128> mPressures{ ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure, ModulationParameters::kDefaultPressure };
std::list<std::string> mMidiMessageQueue;
ofMutex mMidiMessageQueueMutex;
bool mShowJediWarning{ false };
};
class ScriptReferenceDisplay : public IDrawableModule, public IButtonListener
{
public:
ScriptReferenceDisplay();
virtual ~ScriptReferenceDisplay();
static IDrawableModule* Create() { return new ScriptReferenceDisplay(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void ButtonClicked(ClickButton* button, double time) override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override;
bool IsResizable() const override { return true; }
void Resize(float w, float h) override
{
mWidth = w;
mHeight = h;
}
bool MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) override;
void LoadText();
std::vector<std::string> mText;
ClickButton* mCloseButton{ nullptr };
float mWidth{ 750 };
float mHeight{ 335 };
ofVec2f mScrollOffset;
float mMaxScrollAmount{ 0 };
};
class ScriptWarningPopup : public IDrawableModule
{
public:
ScriptWarningPopup() {}
virtual ~ScriptWarningPopup() {}
static IDrawableModule* Create() { return new ScriptWarningPopup(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Poll() override;
void GetDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
bool IsEnabled() const override { return true; }
private:
void DrawModule() override;
int mWidth{ 600 };
int mHeight{ 120 };
int mRemainingUntrustedScriptModules{ 0 };
};
``` | /content/code_sandbox/Source/ScriptModule.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 6,488 |
```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
**/
/*
==============================================================================
PitchToSpeed.h
Created: 28 Nov 2017 9:44:14pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "INoteReceiver.h"
#include "IModulator.h"
#include "Slider.h"
class PatchCableSource;
class PitchToSpeed : public IDrawableModule, public INoteReceiver, public IModulator, public IFloatSliderListener
{
public:
PitchToSpeed();
virtual ~PitchToSpeed();
static IDrawableModule* Create() { return new PitchToSpeed(); }
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; }
virtual bool CanAdjustRange() const override { return false; }
//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;
}
float mPitch{ 0 };
ModulationChain* mPitchBend{ nullptr };
FloatSlider* mReferenceFreqSlider{ nullptr };
float mReferenceFreq{ 440 };
};
``` | /content/code_sandbox/Source/PitchToSpeed.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 578 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// FreqDomainBoilerplate.cpp
// modularSynth
//
// Created by Ryan Challinor on 4/24/13.
//
//
#include "FreqDomainBoilerplate.h"
#include "Profiler.h"
namespace
{
const int fftWindowSize = 1024;
const int fftFreqDomainSize = fftWindowSize / 2 + 1;
}
FreqDomainBoilerplate::FreqDomainBoilerplate()
: IAudioProcessor(gBufferSize)
, mFFT(fftWindowSize)
, mRollingInputBuffer(fftWindowSize)
, mRollingOutputBuffer(fftWindowSize)
, mFFTData(fftWindowSize, fftFreqDomainSize)
{
// Generate a window with a single raised cosine from N/4 to 3N/4
mWindower = new float[fftWindowSize];
for (int i = 0; i < fftWindowSize; ++i)
mWindower[i] = -.5 * cos(FTWO_PI * i / fftWindowSize) + .5;
}
void FreqDomainBoilerplate::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mInputSlider = new FloatSlider(this, "input", 5, 29, 100, 15, &mInputPreamp, 0, 2);
mValue1Slider = new FloatSlider(this, "value 1", 5, 47, 100, 15, &mValue1, 0, 2);
mVolumeSlider = new FloatSlider(this, "volume", 5, 65, 100, 15, &mVolume, 0, 2);
mDryWetSlider = new FloatSlider(this, "dry/wet", 5, 83, 100, 15, &mDryWet, 0, 1);
mValue2Slider = new FloatSlider(this, "value 2", 5, 101, 100, 15, &mValue2, 0, 1);
mValue3Slider = new FloatSlider(this, "value 3", 5, 119, 100, 15, &mValue3, 0, 1);
mPhaseOffsetSlider = new FloatSlider(this, "phase off", 5, 137, 100, 15, &mPhaseOffset, 0, FTWO_PI);
}
FreqDomainBoilerplate::~FreqDomainBoilerplate()
{
delete[] mWindower;
}
void FreqDomainBoilerplate::Process(double time)
{
PROFILER(FreqDomainBoilerplate);
IAudioReceiver* target = GetTarget();
if (target == nullptr || !mEnabled)
return;
ComputeSliders(0);
SyncBuffers();
float inputPreampSq = mInputPreamp * mInputPreamp;
float volSq = mVolume * mVolume;
int bufferSize = GetBuffer()->BufferSize();
mRollingInputBuffer.WriteChunk(GetBuffer()->GetChannel(0), bufferSize, 0);
//copy rolling input buffer into working buffer and window it
mRollingInputBuffer.ReadChunk(mFFTData.mTimeDomain, fftWindowSize, 0, 0);
Mult(mFFTData.mTimeDomain, mWindower, fftWindowSize);
Mult(mFFTData.mTimeDomain, inputPreampSq, fftWindowSize);
mFFT.Forward(mFFTData.mTimeDomain,
mFFTData.mRealValues,
mFFTData.mImaginaryValues);
for (int i = 0; i < fftFreqDomainSize; ++i)
{
float real = mFFTData.mRealValues[i];
float imag = mFFTData.mImaginaryValues[i];
//cartesian to polar
float amp = 2. * sqrtf(real * real + imag * imag);
float phase = atan2(imag, real);
phase = FloatWrap(phase + mPhaseOffset, FTWO_PI);
//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 < fftWindowSize; ++i)
mRollingOutputBuffer.Accum(fftWindowSize - 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(fftWindowSize - i - 1, 0) * volSq * mDryWet;
Add(target->GetBuffer()->GetChannel(0), GetBuffer()->GetChannel(0), bufferSize);
GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(0), bufferSize, 0);
GetBuffer()->Reset();
}
void FreqDomainBoilerplate::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mInputSlider->Draw();
mValue1Slider->Draw();
mVolumeSlider->Draw();
mDryWetSlider->Draw();
mValue2Slider->Draw();
mValue3Slider->Draw();
mPhaseOffsetSlider->Draw();
}
void FreqDomainBoilerplate::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
``` | /content/code_sandbox/Source/FreqDomainBoilerplate.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,358 |
```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
**/
/*
==============================================================================
GridModule.h
Created: 19 Jul 2020 10:36:16pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <iostream>
#include "INoteReceiver.h"
#include "IDrawableModule.h"
#include "Checkbox.h"
#include "MidiDevice.h"
#include "GridController.h"
#include "UIGrid.h"
class ScriptModule;
class GridModule : public IDrawableModule, public IGridControllerListener, public UIGridListener, public INoteReceiver, public IGridController
{
public:
GridModule();
~GridModule();
static IDrawableModule* Create() { return new GridModule(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetGrid(int cols, int rows) { mGrid->SetGrid(cols, rows); }
void SetLabel(int row, std::string label);
void Set(int col, int row, float value)
{
mGrid->SetVal(col, row, value, !K(notifyListener));
UpdateLights();
}
float Get(int col, int row) { return mGrid->GetVal(col, row); }
void HighlightCell(int col, int row, double time, double duration, int colorIndex);
void SetDivision(int steps) { return mGrid->SetMajorColSize(steps); }
int GetCols() const { return mGrid->GetCols(); }
int GetRows() const { return mGrid->GetRows(); }
void SetColor(int colorIndex, ofColor color);
void SetMomentary(bool momentary) { mGrid->SetMomentary(momentary); }
void SetCellColor(int col, int row, int colorIndex);
int GetCellColor(int col, int row) { return mGridOverlay[row * kGridOverlayMaxDim + col]; }
void AddListener(ScriptModule* listener);
void Clear();
//IGridControllerListener
void OnControllerPageSelected() override;
void OnGridButton(int x, int y, float velocity, IGridController* grid) override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendCC(int control, int value, int voiceIdx = -1) override {}
//UIGridListener
void GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) override;
//IGridController
void SetGridControllerOwner(IGridControllerListener* owner) override { mGridControllerOwner = 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 GetCols(); }
int NumRows() override { return GetRows(); }
bool HasInput() const override;
bool IsConnected() const override { return true; }
void CheckboxUpdated(Checkbox* checkbox, 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 4; }
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void OnClicked(float x, float y, bool right) override;
void MouseReleased() override;
bool IsResizable() const override { return true; }
void Resize(float w, float h) override;
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
ofColor GetColor(int colorIndex) const;
void UpdateLights();
GridControlTarget* mGridControlTarget{ nullptr };
PatchCableSource* mGridOutputCable{ nullptr };
IGridControllerListener* mGridControllerOwner{ nullptr };
UIGrid* mGrid{ nullptr };
std::vector<std::string> mLabels;
std::vector<ofColor> mColors;
struct HighlightCellElement
{
double time{ -1 };
Vec2i position;
double duration{ 0 };
ofColor color;
};
std::array<HighlightCellElement, 50> mHighlightCells;
static const int kGridOverlayMaxDim = 256;
std::array<int, kGridOverlayMaxDim * kGridOverlayMaxDim> mGridOverlay;
std::list<ScriptModule*> mScriptListeners;
Checkbox* mMomentaryCheckbox{ nullptr };
bool mMomentary{ false };
bool mDirectColorMode{ true };
};
``` | /content/code_sandbox/Source/GridModule.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,198 |
```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
**/
/*
==============================================================================
ModulatorExpression.h
Created: 8 May 2021 5:36:59pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IModulator.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "ClickButton.h"
#include "TextEntry.h"
#include "exprtk/exprtk.hpp"
class ModulatorExpression : public IDrawableModule, public IFloatSliderListener, public ITextEntryListener, public IModulator
{
public:
ModulatorExpression();
virtual ~ModulatorExpression();
static IDrawableModule* Create() { return new ModulatorExpression(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IModulator
float Value(int samplesIn = 0) override;
bool Active() const override { return mEnabled; }
bool CanAdjustRange() const override { return false; }
void PostRepatch(PatchCableSource* cableSource, bool fromUserClick) override;
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
//ITextEntryListener
void TextEntryComplete(TextEntry* entry) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override;
float mExpressionInput{ 0 };
FloatSlider* mExpressionInputSlider{ nullptr };
float mA{ 0 };
FloatSlider* mASlider{ nullptr };
float mB{ 0 };
FloatSlider* mBSlider{ nullptr };
float mC{ 0 };
FloatSlider* mCSlider{ nullptr };
float mD{ 0 };
FloatSlider* mDSlider{ nullptr };
float mE{ 0 };
FloatSlider* mESlider{ nullptr };
std::string mEntryString{ "x" };
TextEntry* mTextEntry{ nullptr };
exprtk::symbol_table<float> mSymbolTable;
exprtk::expression<float> mExpression;
exprtk::symbol_table<float> mSymbolTableDraw;
exprtk::expression<float> mExpressionDraw;
float mExpressionInputDraw{ 0 };
float mT{ 0 };
bool mExpressionValid{ false };
float mLastDrawMinOutput{ 0 };
float mLastDrawMaxOutput{ 1 };
};
``` | /content/code_sandbox/Source/ModulatorExpression.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
**/
//
// ModwheelToPressure.h
// Bespoke
//
// Created by Ryan Challinor on 1/4/16.
//
//
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "ModulationChain.h"
class ModwheelToPressure : public NoteEffectBase, public IDrawableModule
{
public:
ModwheelToPressure();
virtual ~ModwheelToPressure();
static IDrawableModule* Create() { return new ModwheelToPressure(); }
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/ModwheelToPressure.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 378 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// NoteFlusher.h
// Bespoke
//
// Created by Ryan Challinor on 12/23/14.
//
//
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "ClickButton.h"
class NoteFlusher : public NoteEffectBase, public IDrawableModule, public IButtonListener
{
public:
NoteFlusher();
static IDrawableModule* Create() { return new NoteFlusher(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void ButtonClicked(ClickButton* button, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 90;
height = 18;
}
ClickButton* mFlushButton{ nullptr };
};
``` | /content/code_sandbox/Source/NoteFlusher.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 357 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without 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.cpp
// modularSynth
//
// Created by Ryan Challinor on 2/11/13.
//
//
#include "KarplusStrong.h"
#include "OpenFrameworksPort.h"
#include "SynthGlobals.h"
#include "IAudioReceiver.h"
#include "ModularSynth.h"
#include "Profiler.h"
KarplusStrong::KarplusStrong()
: IAudioProcessor(gBufferSize)
, mPolyMgr(this)
, mNoteInputBuffer(this)
, mWriteBuffer(gBufferSize)
{
mPolyMgr.Init(kVoiceType_Karplus, &mVoiceParams);
AddChild(&mBiquad);
mBiquad.SetPosition(150, 15);
mBiquad.SetEnabled(true);
mBiquad.SetFilterType(kFilterType_Lowpass);
mBiquad.SetFilterParams(3000, sqrt(2) / 2);
mBiquad.SetName("biquad");
for (int i = 0; i < ChannelBuffer::kMaxNumChannels; ++i)
{
mDCRemover[i].SetFilterParams(10, sqrt(2) / 2);
mDCRemover[i].SetFilterType(kFilterType_Highpass);
mDCRemover[i].UpdateFilterCoeff();
}
}
void KarplusStrong::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mVolSlider = new FloatSlider(this, "vol", 3, 2, 80, 15, &mVolume, 0, 2);
mInvertCheckbox = new Checkbox(this, "invert", mVolSlider, kAnchor_Right, &mVoiceParams.mInvert);
mFilterSlider = new FloatSlider(this, "filter", mVolSlider, kAnchor_Below, 140, 15, &mVoiceParams.mFilter, 0, 5);
mFeedbackSlider = new FloatSlider(this, "feedback", mFilterSlider, kAnchor_Below, 140, 15, &mVoiceParams.mFeedback, .5f, .9999f, 4);
mSourceDropdown = new DropdownList(this, "source type", mFeedbackSlider, kAnchor_Below, (int*)&mVoiceParams.mSourceType, 52);
mExciterFreqSlider = new FloatSlider(this, "x freq", mSourceDropdown, kAnchor_Right, 85, 15, &mVoiceParams.mExciterFreq, 10, 1000);
mExciterAttackSlider = new FloatSlider(this, "x att", mSourceDropdown, kAnchor_Below, 69, 15, &mVoiceParams.mExciterAttack, 0.01f, 40);
mExciterDecaySlider = new FloatSlider(this, "x dec", mExciterAttackSlider, kAnchor_Right, 68, 15, &mVoiceParams.mExciterDecay, 0.01f, 40);
mVelToVolumeSlider = new FloatSlider(this, "vel2vol", mExciterAttackSlider, kAnchor_Below, 140, 15, &mVoiceParams.mVelToVolume, 0, 1);
mVelToEnvelopeSlider = new FloatSlider(this, "vel2env", mVelToVolumeSlider, kAnchor_Below, 140, 15, &mVoiceParams.mVelToEnvelope, -1, 1);
mPitchToneSlider = new FloatSlider(this, "pitchtone", mVelToVolumeSlider, kAnchor_Right, 125, 15, &mVoiceParams.mPitchTone, -2, 2);
mLiteCPUModeCheckbox = new Checkbox(this, "lite cpu", mPitchToneSlider, kAnchor_Below, &mVoiceParams.mLiteCPUMode);
//mStretchCheckbox = new Checkbox(this,"stretch",mVolSlider,kAnchor_Right,&mVoiceParams.mStretch);
mSourceDropdown->AddLabel("sin", kSourceTypeSin);
mSourceDropdown->AddLabel("white", kSourceTypeNoise);
mSourceDropdown->AddLabel("mix", kSourceTypeMix);
mSourceDropdown->AddLabel("saw", kSourceTypeSaw);
mSourceDropdown->AddLabel("input", kSourceTypeInput);
mSourceDropdown->AddLabel("input*", kSourceTypeInputNoEnvelope);
mFilterSlider->SetMode(FloatSlider::kSquare);
mExciterFreqSlider->SetMode(FloatSlider::kSquare);
mExciterAttackSlider->SetMode(FloatSlider::kSquare);
mExciterDecaySlider->SetMode(FloatSlider::kSquare);
mBiquad.CreateUIControls();
}
KarplusStrong::~KarplusStrong()
{
}
void KarplusStrong::Process(double time)
{
PROFILER(KarplusStrong);
IAudioReceiver* target = GetTarget();
if (!mEnabled || target == nullptr)
return;
SyncBuffers(mWriteBuffer.NumActiveChannels());
mNoteInputBuffer.Process(time);
ComputeSliders(0);
int bufferSize = target->GetBuffer()->BufferSize();
assert(bufferSize == gBufferSize);
mWriteBuffer.Clear();
mPolyMgr.Process(time, &mWriteBuffer, bufferSize);
for (int ch = 0; ch < mWriteBuffer.NumActiveChannels(); ++ch)
{
Mult(mWriteBuffer.GetChannel(ch), mVolume, bufferSize);
if (!mVoiceParams.mInvert) //unnecessary if inversion is eliminating dc offset
mDCRemover[ch].Filter(mWriteBuffer.GetChannel(ch), bufferSize);
}
mBiquad.ProcessAudio(time, &mWriteBuffer);
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 KarplusStrong::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);
else
mPolyMgr.Stop(time, pitch, voiceIdx);
}
void KarplusStrong::SetEnabled(bool enabled)
{
mEnabled = enabled;
}
void KarplusStrong::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mFilterSlider->Draw();
mFeedbackSlider->Draw();
mVolSlider->Draw();
mSourceDropdown->Draw();
mInvertCheckbox->Draw();
mPitchToneSlider->Draw();
mVelToVolumeSlider->Draw();
mVelToEnvelopeSlider->Draw();
mLiteCPUModeCheckbox->Draw();
mExciterFreqSlider->SetShowing(mVoiceParams.mSourceType == kSourceTypeSin || mVoiceParams.mSourceType == kSourceTypeSaw || mVoiceParams.mSourceType == kSourceTypeMix);
mExciterAttackSlider->SetShowing(mVoiceParams.mSourceType != kSourceTypeInputNoEnvelope);
mExciterDecaySlider->SetShowing(mVoiceParams.mSourceType != kSourceTypeInputNoEnvelope);
//mStretchCheckbox->Draw();
mExciterFreqSlider->Draw();
mExciterAttackSlider->Draw();
mExciterDecaySlider->Draw();
mBiquad.Draw();
}
void KarplusStrong::DrawModuleUnclipped()
{
if (mDrawDebug)
{
mPolyMgr.DrawDebug(250, 0);
}
}
void KarplusStrong::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void KarplusStrong::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void KarplusStrong::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
mPolyMgr.KillAll();
for (int ch = 0; ch < ChannelBuffer::kMaxNumChannels; ++ch)
mDCRemover[ch].Clear();
mBiquad.Clear();
}
}
void KarplusStrong::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 KarplusStrong::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/KarplusStrong.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,190 |
```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
**/
/*
==============================================================================
SampleCapturer.h
Created: 12 Nov 2020 6:36:00pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "ClickButton.h"
#include <array>
class SampleCapturer : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public IButtonListener
{
public:
SampleCapturer();
virtual ~SampleCapturer();
static IDrawableModule* Create() { return new SampleCapturer(); }
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; }
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void ButtonClicked(ClickButton* button, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 0; }
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override;
void OnClicked(float x, float y, bool right) override;
bool MouseMoved(float x, float y) override;
void MouseReleased() override;
static const int kMaxSampleLengthSeconds = 3;
struct SampleElement
{
SampleElement()
: mBuffer(gSampleRate * kMaxSampleLengthSeconds)
{
}
ChannelBuffer mBuffer;
int mRecordingLength{ 0 };
int mPlaybackPos{ -1 };
};
std::array<SampleElement, 10> mSamples;
int mCurrentSampleIndex{ 0 };
bool mWantRecord{ false };
Checkbox* mWantRecordCheckbox{ nullptr };
bool mIsRecording{ false };
ClickButton* mDeleteButton{ nullptr };
ClickButton* mSaveButton{ nullptr };
ClickButton* mPlayButton{ nullptr };
bool mIsDragging{ false };
};
``` | /content/code_sandbox/Source/SampleCapturer.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
**/
//
// ScaleDetect.h
// modularSynth
//
// Created by Ryan Challinor on 2/10/13.
//
//
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "ClickButton.h"
#include "Scale.h"
#include "DropdownList.h"
struct MatchingScale
{
MatchingScale(int root, std::string type)
: mRoot(root)
, mType(type)
{}
int mRoot;
std::string mType;
};
class ScaleDetect : public NoteEffectBase, public IDrawableModule, public IButtonListener, public IDropdownListener
{
public:
ScaleDetect();
static IDrawableModule* Create() { return new ScaleDetect(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void ButtonClicked(ClickButton* button, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return true; }
private:
bool ScaleSatisfied(int root, std::string type);
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 140;
height = 36;
}
std::array<bool, 128> mPitchOn{ false };
ClickButton* mResetButton{ nullptr };
int mLastPitch{ 0 };
bool mDoDetect{ true };
bool mNeedsUpdate{ false };
DropdownList* mMatchesDropdown{ nullptr };
int mSelectedMatch{ 0 };
};
``` | /content/code_sandbox/Source/ScaleDetect.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 540 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
PulseRouter.cpp
Created: 31/03/2024
Author: Ryan Challinor / ArkyonVeil
==============================================================================
*/
#include "PulseRouter.h"
#include "OpenFrameworksPort.h"
#include "ModularSynth.h"
#include "PatchCable.h"
#include "PatchCableSource.h"
PulseRouter::PulseRouter()
{
}
void PulseRouter::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mRouteSelector = new RadioButton(this, "route", 5, 3, &mRouteMask);
GetPatchCableSource()->SetEnabled(false);
}
void PulseRouter::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mRouteSelector->Draw();
for (int i = 0; i < (int)mDestinationCables.size(); ++i)
{
ofVec2f pos = mRouteSelector->GetOptionPosition(i) - mRouteSelector->GetPosition();
mDestinationCables[i]->SetManualPosition(pos.x + 10, pos.y + 4);
}
}
void PulseRouter::SetSelectedMask(int mask)
{
mRouteMask = mask;
}
bool PulseRouter::IsIndexActive(int idx) const
{
if (mRadioButtonMode)
return mRouteMask == idx;
return mRouteMask & (1 << idx);
}
void PulseRouter::OnPulse(double time, float velocity, int flags)
{
for (int i = 0; i < (int)mDestinationCables.size(); ++i)
{
if (IsIndexActive(i))
{
DispatchPulse(mDestinationCables[i], time, velocity, flags);
}
}
}
void PulseRouter::RadioButtonUpdated(RadioButton* radio, int oldVal, double time)
{
}
void PulseRouter::Poll()
{
for (int i = 0; i < (int)mDestinationCables.size(); ++i)
mDestinationCables[i]->SetShowing(!mOnlyShowActiveCables || IsIndexActive(i));
}
void PulseRouter::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
//Hopefully this isn't important.
//INoteSource::PostRepatch(cableSource, fromUserClick);
for (int i = 0; i < (int)mDestinationCables.size(); ++i)
{
if (cableSource == mDestinationCables[i])
{
IClickable* target = cableSource->GetTarget();
std::string name = target ? target->Name() : " ";
mRouteSelector->SetLabel(name.c_str(), i);
}
}
}
void PulseRouter::GetModuleDimensions(float& width, float& height)
{
float w, h;
mRouteSelector->GetDimensions(w, h);
width = 20 + w;
height = 8 + h;
}
void PulseRouter::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadInt("num_items", moduleInfo, 2, 1, 99, K(isTextField));
mModuleSaveData.LoadBool("radiobuttonmode", moduleInfo, true);
mModuleSaveData.LoadBool("only_show_active_cables", moduleInfo, false);
SetUpFromSaveData();
}
void PulseRouter::SetUpFromSaveData()
{
int numItems = mModuleSaveData.GetInt("num_items");
int oldNumItems = (int)mDestinationCables.size();
if (numItems > oldNumItems)
{
for (int i = oldNumItems; i < numItems; ++i)
{
mDestinationCables.push_back(new PatchCableSource(this, kConnectionType_Pulse));
mRouteSelector->AddLabel(" ", i);
AddPatchCableSource(mDestinationCables[i]);
mDestinationCables[i]->SetOverrideCableDir(ofVec2f(1, 0), PatchCableSource::Side::kRight);
ofRectangle rect = GetRect(true);
mDestinationCables[i]->SetManualPosition(rect.getMaxX() + 10, rect.y + rect.height / 2);
}
}
else if (numItems < oldNumItems)
{
for (int i = oldNumItems - 1; i >= numItems; --i)
{
mRouteSelector->RemoveLabel(i);
RemovePatchCableSource(mDestinationCables[i]);
}
mDestinationCables.resize(numItems);
}
mRadioButtonMode = mModuleSaveData.GetBool("radiobuttonmode");
mRouteSelector->SetMultiSelect(!mRadioButtonMode);
mOnlyShowActiveCables = mModuleSaveData.GetBool("only_show_active_cables");
}
void PulseRouter::SaveLayout(ofxJSONElement& moduleInfo)
{
moduleInfo["num_items"] = (int)mDestinationCables.size();
}
``` | /content/code_sandbox/Source/PulseRouter.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,148 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// ADSR.cpp
// additiveSynth
//
// Created by Ryan Challinor on 11/19/12.
//
//
#include "ADSR.h"
#include "OpenFrameworksPort.h"
#include "MathUtils.h"
#include "FileStream.h"
#include "SynthGlobals.h"
void ::ADSR::Set(float a, float d, float s, float r, float h /*=-1*/)
{
mStages[0].target = 1;
mStages[0].time = MAX(a, 1);
mStages[0].curve = 0;
mStages[1].target = MAX(s, .0001f);
mStages[1].time = MAX(d, 1);
mStages[1].curve = -.5f;
mStages[2].target = 0;
mStages[2].time = MAX(r, 1);
mStages[2].curve = -.5f;
mNumStages = 3;
mSustainStage = 1;
mMaxSustain = h;
mHasSustainStage = true;
}
void ::ADSR::Set(const ADSR& other)
{
for (int i = 0; i < other.mNumStages; ++i)
mStages[i] = other.mStages[i];
mNumStages = other.mNumStages;
mSustainStage = other.mSustainStage;
mMaxSustain = other.mMaxSustain;
mHasSustainStage = other.mHasSustainStage;
mFreeReleaseLevel = other.mFreeReleaseLevel;
}
void ::ADSR::Start(double time, float target, float a, float d, float s, float r, float timeScale /*=1*/)
{
Set(a, d, s, r);
Start(time, target, timeScale);
}
void ::ADSR::Start(double time, float target, const ADSR& adsr, float timeScale)
{
Set(adsr);
Start(time, target, timeScale);
}
void ::ADSR::Start(double time, float target, float timeScale /*=1*/)
{
mEvents[mNextEventPointer].Reset();
mEvents[mNextEventPointer].mStartBlendFromValue = Value(time);
mEvents[mNextEventPointer].mStartTime = time;
mEvents[mNextEventPointer].mMult = target;
mNextEventPointer = (mNextEventPointer + 1) % mEvents.size();
mTimeScale = timeScale;
if (mMaxSustain >= 0 && mHasSustainStage)
{
float stopTime = time;
for (int i = 0; i < mNumStages; ++i)
{
stopTime += mStages[i].time * timeScale;
if (i == mSustainStage)
break;
}
stopTime += mMaxSustain;
Stop(stopTime);
}
}
void ::ADSR::Stop(double time, bool warn /*= true*/)
{
EventInfo* e = GetEvent(time);
e->mStopBlendFromValue = Value(time);
if (time <= e->mStartTime)
{
if (warn)
ofLog() << "trying to stop before we started (" << time << "<=" << e->mStartTime << ")";
time = e->mStartTime + .0001f; //must be after start
}
e->mStopTime = time;
}
::ADSR::EventInfo* ::ADSR::GetEvent(double time)
{
int ret = 0;
double latestTime = -1;
for (int i = 0; i < (int)mEvents.size(); ++i)
{
if (mEvents[i].mStartTime < time && mEvents[i].mStartTime > latestTime)
{
ret = i;
latestTime = mEvents[i].mStartTime;
}
}
return &(mEvents[ret]);
}
const ::ADSR::EventInfo* ::ADSR::GetEventConst(double time) const
{
int ret = 0;
double latestTime = -1;
for (int i = 0; i < (int)mEvents.size(); ++i)
{
if (mEvents[i].mStartTime < time && mEvents[i].mStartTime > latestTime)
{
ret = i;
latestTime = mEvents[i].mStartTime;
}
}
return &(mEvents[ret]);
}
float ::ADSR::Value(double time) const
{
const EventInfo* e = GetEventConst(time);
return Value(time, e);
}
float ::ADSR::Value(double time, const EventInfo* e) const
{
float stageStartValue;
double stageStartTime;
int stage = GetStage(time, stageStartTime, e);
if (stage == mNumStages) //done
return mStages[stage - 1].target;
if (stage == 0)
stageStartValue = e->mStartBlendFromValue;
else if (mHasSustainStage && stage == mSustainStage + 1 && e->mStopBlendFromValue != std::numeric_limits<float>::max())
stageStartValue = e->mStopBlendFromValue;
else
stageStartValue = mStages[stage - 1].target * e->mMult;
if (mHasSustainStage && stage == mSustainStage && time > stageStartTime + (mStages[mSustainStage].time * GetStageTimeScale(mSustainStage)))
return mStages[mSustainStage].target * e->mMult;
float stageTimeScale = GetStageTimeScale(stage);
float lerp = ofClamp((time - stageStartTime) / (mStages[stage].time * stageTimeScale), 0, 1);
if (mStages[stage].curve != 0)
lerp = MathUtils::Curve(lerp, mStages[stage].curve * ((stageStartValue < mStages[stage].target * e->mMult) ? 1 : -1));
return ofLerp(stageStartValue, mStages[stage].target * e->mMult, lerp);
}
float ::ADSR::GetStageTimeScale(int stage) const
{
if (stage >= mNumStages - 1)
return 1;
return mTimeScale;
}
int ::ADSR::GetStage(double time, double& stageStartTimeOut) const
{
const EventInfo* e = GetEventConst(time);
return GetStage(time, stageStartTimeOut, e);
}
int ::ADSR::GetStage(double time, double& stageStartTimeOut, const EventInfo* e) const
{
if (e->mStartTime < 0)
return mNumStages;
int stage = 0;
stageStartTimeOut = e->mStartTime;
if (time >= e->mStartTime)
{
if (mHasSustainStage && time >= e->mStopTime && e->mStopTime > e->mStartTime)
{
stage = mSustainStage + 1;
stageStartTimeOut = e->mStopTime;
}
while (time > mStages[stage].time * GetStageTimeScale(stage) + stageStartTimeOut && stage < mNumStages)
{
stageStartTimeOut += mStages[stage].time * GetStageTimeScale(stage);
++stage;
if (mHasSustainStage && stage == mSustainStage)
break;
}
}
return stage;
}
bool ::ADSR::IsDone(double time) const
{
double dummy;
return GetStage(time, dummy) == mNumStages;
}
namespace
{
const int kSaveStateRev = 1;
}
void ::ADSR::SaveState(FileStreamOut& out)
{
out << kSaveStateRev;
float dummy;
out << dummy;
out << mSustainStage;
out << mMaxSustain;
out << mNumStages;
out << mHasSustainStage;
out << mFreeReleaseLevel;
out << MAX_ADSR_STAGES;
for (int i = 0; i < MAX_ADSR_STAGES; ++i)
{
out << mStages[i].curve;
out << mStages[i].target;
out << mStages[i].time;
}
out << mTimeScale;
}
void ::ADSR::LoadState(FileStreamIn& in)
{
int rev;
in >> rev;
LoadStateValidate(rev <= kSaveStateRev);
float dummy;
in >> dummy;
in >> mSustainStage;
in >> mMaxSustain;
in >> mNumStages;
in >> mHasSustainStage;
in >> mFreeReleaseLevel;
int maxNumStages;
in >> maxNumStages;
assert(maxNumStages == MAX_ADSR_STAGES);
for (int i = 0; i < maxNumStages; ++i)
{
in >> mStages[i].curve;
in >> mStages[i].target;
in >> mStages[i].time;
}
if (rev >= 1)
in >> mTimeScale;
}
``` | /content/code_sandbox/Source/ADSR.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,118 |
```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
**/
/*
==============================================================================
UnstablePressure.h
Created: 2 Mar 2021 7:49:00pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "ModulationChain.h"
#include "Transport.h"
#include "UnstablePitch.h"
class UnstablePressure : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public IAudioPoller
{
public:
UnstablePressure();
virtual ~UnstablePressure();
static IDrawableModule* Create() { return new UnstablePressure(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void Init() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
//IAudioPoller
void OnTransportAdvanced(float amount) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void FillModulationBuffer(double time, int voiceIdx);
UnstablePerlinModulation mPerlin{ .2, .1, 0 };
FloatSlider* mAmountSlider{ nullptr };
FloatSlider* mWarbleSlider{ nullptr };
FloatSlider* mNoiseSlider{ nullptr };
float mWidth{ 200 };
float mHeight{ 20 };
std::array<bool, kNumVoices> mIsVoiceUsed{ false };
std::array<int, 128> mPitchToVoice{};
int mVoiceRoundRobin{ 0 };
Modulations mModulation{ false };
};
``` | /content/code_sandbox/Source/UnstablePressure.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 607 |
```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
**/
/*
==============================================================================
CanvasTimeline.h
Created: 20 Mar 2021 12:35:05am
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IUIControl.h"
class Canvas;
class CanvasTimeline : public IUIControl
{
public:
CanvasTimeline(Canvas* canvas, std::string name);
~CanvasTimeline() {}
void SetDimensions(float width, float height)
{
mWidth = width;
mHeight = height;
}
//IUIControl
void SetFromMidiCC(float slider, double time, bool setViaModulator) override {}
void SetValue(float value, double time, bool forceUpdate = false) override {}
void KeyPressed(int key, bool isRepeat) 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; }
void Render() override;
void MouseReleased() override;
bool MouseMoved(float x, float y) override;
bool MouseScrolled(float x, float y, float scrollX, float scrollY, bool isSmoothScroll, bool isInvertedScroll) override;
private:
void OnClicked(float x, float y, bool right) override;
void GetDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
enum class HoverMode
{
kNone,
kStart,
kEnd,
kMiddle
};
void DrawTriangle(float posX, int direction);
float GetQuantizedForX(float posX, HoverMode clampSide);
float mWidth{ 200 };
float mHeight{ 20 };
bool mClick{ false };
ofVec2f mClickMousePos;
ofVec2f mDragOffset;
HoverMode mHoverMode{ HoverMode::kNone };
Canvas* mCanvas{ nullptr };
};
``` | /content/code_sandbox/Source/CanvasTimeline.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 545 |
```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
**/
//
// VSTPlayhead.h
// Bespoke
//
// Created by Ryan Challinor on 1/20/16.
//
//
#pragma once
#include "juce_audio_basics/juce_audio_basics.h"
class VSTPlayhead : public juce::AudioPlayHead
{
public:
juce::Optional<AudioPlayHead::PositionInfo> getPosition() const override;
};
``` | /content/code_sandbox/Source/VSTPlayhead.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 179 |
```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
**/
//
// SignalGenerator.h
// Bespoke
//
// Created by Ryan Challinor on 6/26/14.
//
//
#pragma once
#include <iostream>
#include "IAudioSource.h"
#include "INoteReceiver.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "DropdownList.h"
#include "EnvOscillator.h"
#include "Ramp.h"
#include "IPulseReceiver.h"
class ofxJSONElement;
class SignalGenerator : public IAudioSource, public INoteReceiver, public IDrawableModule, public IDropdownListener, public IFloatSliderListener, public IIntSliderListener, public IPulseReceiver
{
public:
SignalGenerator();
~SignalGenerator();
static IDrawableModule* Create() { return new SignalGenerator(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return true; }
void CreateUIControls() override;
void SetVol(float vol) { mVol = vol; }
//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 {}
//IPulseReceiver
void OnPulse(double time, float velocity, int flags) override;
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;
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 LoadOldControl(FileStreamIn& in, std::string& oldName) override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
enum FreqMode
{
kFreqMode_Instant,
kFreqMode_Root,
kFreqMode_Ramp,
kFreqMode_Slider
};
void SetType(OscillatorType type);
void SetFreqMode(FreqMode mode);
float mVol{ 0 };
FloatSlider* mVolSlider{ nullptr };
OscillatorType mOscType{ OscillatorType::kOsc_Sin };
DropdownList* mOscSelector{ nullptr };
float mPulseWidth{ .5 };
FloatSlider* mPulseWidthSlider{ nullptr };
float mShuffle{ 0 };
FloatSlider* mShuffleSlider{ nullptr };
int mMult{ 1 };
DropdownList* mMultSelector{ nullptr };
Oscillator::SyncMode mSyncMode{ Oscillator::SyncMode::None };
DropdownList* mSyncModeSelector{ nullptr };
float mSyncFreq{ 200 };
FloatSlider* mSyncFreqSlider{ nullptr };
float mSyncRatio{ 1 };
FloatSlider* mSyncRatioSlider{ nullptr };
float mDetune{ 0 };
FloatSlider* mDetuneSlider{ nullptr };
EnvOscillator mOsc{ OscillatorType::kOsc_Sin };
float mFreq{ 220 };
FloatSlider* mFreqSlider{ nullptr };
float mPhase{ 0 };
float mSyncPhase{ 0 };
FreqMode mFreqMode{ FreqMode::kFreqMode_Instant };
DropdownList* mFreqModeSelector{ nullptr };
float mFreqSliderStart{ 220 };
float mFreqSliderEnd{ 220 };
float mFreqSliderAmount{ 0 };
FloatSlider* mFreqSliderAmountSlider{ nullptr };
Ramp mFreqRamp;
float mFreqRampTime{ 200 };
FloatSlider* mFreqRampTimeSlider{ nullptr };
float mSoften{ 0 };
FloatSlider* mSoftenSlider{ nullptr };
float mPhaseOffset{ 0 };
FloatSlider* mPhaseOffsetSlider{ nullptr };
double mResetPhaseAtMs{ -9999 };
float* mWriteBuffer{ nullptr };
int mLoadRev{ -1 };
};
``` | /content/code_sandbox/Source/SignalGenerator.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,109 |
```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
**/
/*
==============================================================================
ChordDatabase.h
Created: 26 Mar 2018 9:54:44pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <numeric>
#include <set>
#include <string>
#include <vector>
class ChordDatabase
{
public:
ChordDatabase();
std::string GetChordName(std::vector<int> pitches) const;
std::set<std::string> GetChordNamesAdvanced(const std::vector<int>& pitches, bool useScaleDegrees, bool showIntervals) const;
std::vector<int> GetChord(std::string name, int inversion) const;
std::vector<std::string> GetChordNames() const;
private:
struct ChordShape
{
ChordShape(std::string name, std::vector<int> elements, float rootPosBias = 0.0f)
{
std::vector<float> weights(12);
mName = name;
mElements = elements;
mWeights = weights;
mWeightSum = 0;
mRootPosBias = rootPosBias;
}
ChordShape(std::string name, std::vector<int> elements, std::vector<float> weights, float rootPosBias = 0.0f)
{
mName = name;
mElements = elements;
mWeights = weights;
auto lambda = [&](float a, float b)
{
return b > 0.0f ? a - b : a;
};
mWeightSum = std::accumulate(
mWeights.begin(), mWeights.end(), 0.0f, lambda);
mRootPosBias = rootPosBias;
}
std::string mName;
std::vector<int> mElements;
std::vector<float> mWeights;
float mWeightSum;
float mRootPosBias;
};
std::vector<ChordShape> mChordShapes;
std::string GetChordNameAdvanced(const std::vector<int>& pitches, const int root, const ChordShape shape, bool useScaleDegrees) const;
std::string NoteNameScaleRelative(int pitch, bool useDegrees) const; // Helper function for GetChordNameAdvanced, may be better off moved to synthglobals?
std::string ChordNameScaleRelative(int rootPitch) const; // Helper function for GetChordNameAdvanced, may be better off moved to synthglobals?
};
``` | /content/code_sandbox/Source/ChordDatabase.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 617 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
ScriptStatus.cpp
Created: 25 Apr 2020 10:51:14pm
Author: Ryan Challinor
==============================================================================
*/
#if BESPOKE_WINDOWS
#define ssize_t ssize_t_undef_hack //fixes conflict with ssize_t typedefs between python and juce
#endif
#include "ScriptStatus.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
#include "ScriptModule.h"
#include "Prefab.h"
#if BESPOKE_WINDOWS
#undef ssize_t
#endif
#include "leathers/push"
#include "leathers/unused-value"
#include "leathers/range-loop-analysis"
#include "pybind11/embed.h"
#include "leathers/pop"
namespace py = pybind11;
ScriptStatus::ScriptStatus()
{
ScriptModule::CheckIfPythonEverSuccessfullyInitialized();
if ((TheSynth->IsLoadingState() || Prefab::sLoadingPrefab) && ScriptModule::sHasPythonEverSuccessfullyInitialized)
ScriptModule::InitializePythonIfNecessary();
}
ScriptStatus::~ScriptStatus()
{
}
void ScriptStatus::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
BUTTON(mResetAll, "reset all");
ENDUIBLOCK0();
mWidth = 400;
mHeight = 400;
}
void ScriptStatus::Poll()
{
if (ScriptModule::sHasPythonEverSuccessfullyInitialized)
ScriptModule::InitializePythonIfNecessary();
if (!ScriptModule::sPythonInitialized)
return;
if (gTime > mNextUpdateTime)
{
mStatus = py::str(py::globals());
ofStringReplace(mStatus, ",", "\n");
mNextUpdateTime = gTime + 100;
}
}
void ScriptStatus::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
if (!ScriptModule::sHasPythonEverSuccessfullyInitialized)
{
DrawTextNormal("please create a \"script\" module to initialize Python", 20, 20);
return;
}
mResetAll->Draw();
DrawTextNormal(mStatus, 3, 35);
}
void ScriptStatus::OnClicked(float x, float y, bool right)
{
if (ScriptModule::sHasPythonEverSuccessfullyInitialized)
{
IDrawableModule::OnClicked(x, y, right);
}
}
void ScriptStatus::ButtonClicked(ClickButton* button, double time)
{
ScriptModule::UninitializePython();
ScriptModule::InitializePythonIfNecessary();
}
void ScriptStatus::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void ScriptStatus::SetUpFromSaveData()
{
}
void ScriptStatus::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void ScriptStatus::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out << mWidth;
out << mHeight;
}
void ScriptStatus::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
in >> mWidth;
in >> mHeight;
}
``` | /content/code_sandbox/Source/ScriptStatus.cpp | 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
**/
//
// SaveStateLoader.cpp
// Bespoke
//
// Created by Ryan Challinor on 7/23/24.
//
//
#include "SaveStateLoader.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "UIControlMacros.h"
SaveStateLoader::SaveStateLoader()
{
}
SaveStateLoader::~SaveStateLoader()
{
}
void SaveStateLoader::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
for (size_t i = 0; i < mLoadButtons.size(); ++i)
{
BUTTON(mLoadButtons[i].mButton, ("load " + ofToString(i)).c_str());
mLoadButtons[i].mButton->SetOverrideDisplayName("<select file>");
mLoadButtons[i].mButton->UpdateWidth();
}
ENDUIBLOCK0();
}
void SaveStateLoader::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
for (size_t i = 0; i < mLoadButtons.size(); ++i)
{
mLoadButtons[i].mButton->SetShowing(i < mNumDisplayButtons);
mLoadButtons[i].mButton->Draw();
}
}
void SaveStateLoader::Poll()
{
for (size_t i = 0; i < mLoadButtons.size(); ++i)
{
if (mLoadButtons[i].mShouldShowSelectDialog)
{
mLoadButtons[i].mShouldShowSelectDialog = false;
juce::FileChooser chooser("Select state file", juce::File(ofToDataPath("savestate")), "*.bsk;*.bskt", true, false, TheSynth->GetFileChooserParent());
if (chooser.browseForFileToOpen())
{
mLoadButtons[i].mFilePath = chooser.getResult().getFullPathName().replace("\\", "/").toStdString();
UpdateButtonLabel(i);
}
}
}
}
void SaveStateLoader::GetModuleDimensions(float& w, float& h)
{
w = 100;
for (size_t i = 0; i < mLoadButtons.size(); ++i)
{
if (i < mNumDisplayButtons)
{
float buttonW, buttonH;
mLoadButtons[i].mButton->GetDimensions(buttonW, buttonH);
if (buttonW + 6 > w)
w = buttonW + 6;
}
}
h = 3 + 17 * mNumDisplayButtons;
}
bool SaveStateLoader::HasValidFile(int index) const
{
return juce::String(mLoadButtons[index].mFilePath).endsWith(".bsk") || juce::String(mLoadButtons[index].mFilePath).endsWith(".bskt");
}
void SaveStateLoader::ButtonClicked(ClickButton* button, double time)
{
for (size_t i = 0; i < mLoadButtons.size(); ++i)
{
if (button == mLoadButtons[i].mButton)
{
if (HasValidFile(i) && !(GetKeyModifiers() & kModifier_Shift))
TheSynth->LoadState(mLoadButtons[i].mFilePath);
else
mLoadButtons[i].mShouldShowSelectDialog = true;
}
}
}
void SaveStateLoader::UpdateButtonLabel(int index)
{
if (HasValidFile(index))
{
juce::File file(mLoadButtons[index].mFilePath);
mLoadButtons[index].mButton->SetOverrideDisplayName(("load " + file.getFileName()).toRawUTF8());
mLoadButtons[index].mButton->UpdateWidth();
}
}
void SaveStateLoader::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadInt("num_buttons", moduleInfo, 1, 1, (int)mLoadButtons.size(), true);
SetUpFromSaveData();
}
void SaveStateLoader::SetUpFromSaveData()
{
mNumDisplayButtons = mModuleSaveData.GetInt("num_buttons");
}
void SaveStateLoader::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out << (int)mLoadButtons.size();
for (size_t i = 0; i < mLoadButtons.size(); ++i)
out << mLoadButtons[i].mFilePath;
}
void SaveStateLoader::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
int count;
in >> count;
for (size_t i = 0; i < mLoadButtons.size() && i < count; ++i)
{
in >> mLoadButtons[i].mFilePath;
UpdateButtonLabel(i);
}
}
``` | /content/code_sandbox/Source/SaveStateLoader.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,113 |
```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
**/
//
// INoteReceiver.h
// modularSynth
//
// Created by Ryan Challinor on 12/2/12.
//
//
#pragma once
#include "ModulationChain.h"
namespace juce
{
class MidiMessage;
}
class INoteReceiver
{
public:
virtual ~INoteReceiver() {}
virtual void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) = 0;
virtual void SendPressure(int pitch, int pressure) {}
virtual void SendCC(int control, int value, int voiceIdx = -1) = 0;
virtual void SendMidi(const juce::MidiMessage& message) {}
};
struct NoteInputElement
{
double time{ 0 };
int pitch{ 0 };
float velocity{ 0 };
int voiceIdx{ -1 };
ModulationParameters modulation;
};
class NoteInputBuffer
{
public:
NoteInputBuffer(INoteReceiver* receiver);
void Process(double time);
void QueueNote(double time, int pitch, float velocity, int voiceIdx, ModulationParameters modulation);
static bool IsTimeWithinFrame(double time);
private:
static const int kBufferSize = 50;
NoteInputElement mBuffer[kBufferSize];
INoteReceiver* mReceiver{ nullptr };
};
``` | /content/code_sandbox/Source/INoteReceiver.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
**/
//
// ScaleDetect.cpp
// modularSynth
//
// Created by Ryan Challinor on 2/10/13.
//
//
#include "ScaleDetect.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
ScaleDetect::ScaleDetect()
{
}
void ScaleDetect::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mResetButton = new ClickButton(this, "reset", 4, 18);
mMatchesDropdown = new DropdownList(this, "matches", 25, 2, &mSelectedMatch);
}
void ScaleDetect::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mResetButton->Draw();
mMatchesDropdown->Draw();
DrawTextNormal(NoteName(mLastPitch), 5, 12);
if (mNeedsUpdate)
{
mMatchesDropdown->Clear();
int numMatches = 0;
mSelectedMatch = 0;
if (mDoDetect)
{
int numScaleTypes = TheScale->GetNumScaleTypes();
for (int j = 0; j < numScaleTypes - 1; ++j)
{
if (ScaleSatisfied(mLastPitch % TheScale->GetPitchesPerOctave(), TheScale->GetScaleName(j)))
mMatchesDropdown->AddLabel(TheScale->GetScaleName(j).c_str(), numMatches++);
}
}
mNeedsUpdate = false;
}
{
std::string pitchString;
std::vector<int> rootRelative;
for (int i = 0; i < 128; ++i)
{
if (mPitchOn[i])
{
int entry = (i - mLastPitch + TheScale->GetPitchesPerOctave() * 10) % TheScale->GetPitchesPerOctave();
if (!VectorContains(entry, rootRelative))
rootRelative.push_back(entry);
}
}
sort(rootRelative.begin(), rootRelative.end());
for (int i = 0; i < rootRelative.size(); ++i)
pitchString += ofToString(rootRelative[i]) + " ";
DrawTextNormal(pitchString, 40, 30);
}
}
void ScaleDetect::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
if (velocity > 0 && pitch >= 0 && pitch < 128)
{
mPitchOn[pitch] = true;
mLastPitch = pitch;
mNeedsUpdate = true;
}
}
bool ScaleDetect::ScaleSatisfied(int root, std::string type)
{
ScalePitches scale;
scale.SetRoot(root);
scale.SetScaleType(type);
for (int i = 0; i < 128; ++i)
{
if (mPitchOn[i] && !scale.IsInScale(i))
return false;
}
return true;
}
void ScaleDetect::ButtonClicked(ClickButton* button, double time)
{
if (button == mResetButton)
{
for (int i = 0; i < 128; ++i)
mPitchOn[i] = false;
mMatchesDropdown->Clear();
mNeedsUpdate = true;
}
}
void ScaleDetect::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mMatchesDropdown)
{
TheScale->SetScale(mLastPitch, mMatchesDropdown->GetLabel(mSelectedMatch));
}
}
void ScaleDetect::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void ScaleDetect::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/ScaleDetect.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 926 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
EnvelopeEditor.cpp
Created: 9 Nov 2017 5:20:48pm
Author: Ryan Challinor
==============================================================================
*/
#include "EnvelopeEditor.h"
#include "ofxJSONElement.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
#include "Checkbox.h"
#include "UIControlMacros.h"
namespace
{
float pointClickRadius = 4;
}
EnvelopeControl::EnvelopeControl(ofVec2f position, ofVec2f dimensions)
: mPosition(position)
, mDimensions(dimensions)
{
}
void EnvelopeControl::Draw()
{
ofPushStyle();
ofSetColor(100, 100, .8f * gModuleDrawAlpha);
ofSetLineWidth(.5f);
ofRect(mPosition.x, mPosition.y, mDimensions.x, mDimensions.y, 0);
ofSetColor(245, 58, 0, gModuleDrawAlpha);
if (mAdsr != nullptr)
{
ADSR::EventInfo adsrEvent(0, GetReleaseTime());
ofSetLineWidth(1);
ofBeginShape();
for (float i = 0; i < mDimensions.x; i += (.25f / gDrawScale))
{
float time = i / mDimensions.x * mViewLength;
if (time < GetPreSustainTime())
{
float value = mAdsr->Value(time, &adsrEvent);
AddVertex(i + mPosition.x, GetYForValue(value));
}
else
{
break;
}
}
AddVertex(GetXForTime(GetPreSustainTime()),
GetYForValue(mAdsr->Value(GetPreSustainTime(), &adsrEvent)));
ofEndShape(false);
ofPushStyle();
ofSetColor(0, 58, 245, gModuleDrawAlpha);
ofLine(ofClamp(GetXForTime(GetPreSustainTime()), mPosition.x, mPosition.x + mDimensions.x),
GetYForValue(mAdsr->Value(GetPreSustainTime(), &adsrEvent)),
ofClamp(GetXForTime(GetReleaseTime()), mPosition.x, mPosition.x + mDimensions.x),
GetYForValue(mAdsr->Value(GetReleaseTime(), &adsrEvent)));
ofPopStyle();
ofBeginShape();
AddVertex(GetXForTime(GetReleaseTime()),
GetYForValue(mAdsr->Value(GetReleaseTime(), &adsrEvent)));
for (float i = 0; i < mDimensions.x; i += (.25f / gDrawScale))
{
float time = i / mDimensions.x * mViewLength;
if (time >= GetReleaseTime())
{
float value = mAdsr->Value(time, &adsrEvent);
AddVertex(i + mPosition.x, GetYForValue(value));
}
}
ofEndShape(false);
ofSetLineWidth(3);
ofBeginShape();
bool started = false;
for (float i = 0; i < mDimensions.x; i += (.25f / gDrawScale))
{
float time = i / mDimensions.x * mViewLength;
double stageStartTime;
if (mAdsr->GetStage(time, stageStartTime, &adsrEvent) == mHighlightCurve)
{
if (!started)
{
started = true;
AddVertex(GetXForTime(stageStartTime), GetYForValue(mAdsr->Value(stageStartTime, &adsrEvent)));
}
if (mAdsr->GetHasSustainStage() && mHighlightCurve == mAdsr->GetSustainStage() && time > GetPreSustainTime())
break;
float value = mAdsr->Value(time, &adsrEvent);
AddVertex(i + mPosition.x, GetYForValue(value));
}
}
ofEndShape(false);
float time = 0;
ofSetLineWidth(.5f);
for (int i = 0; i < mAdsr->GetNumStages(); ++i)
{
if (mAdsr->GetHasSustainStage() && i == mAdsr->GetSustainStage() + 1)
time = GetReleaseTime();
time += mAdsr->GetStageData(i).time;
if (i == mAdsr->GetNumStages() - 1)
time += 0;
float value = mAdsr->Value(time, &adsrEvent);
if (i == mHighlightPoint)
ofFill();
else
ofNoFill();
float x = GetXForTime(time);
if (x < mPosition.x + mDimensions.x)
ofCircle(x, GetYForValue(value), i == mHighlightPoint ? 8 : pointClickRadius);
}
ofSetLineWidth(1);
ofSetColor(0, 255, 0, gModuleDrawAlpha * .5f);
float drawTime = 0;
if (mAdsr->GetStartTime(gTime) > 0 && mAdsr->GetStartTime(gTime) >= mAdsr->GetStopTime(gTime))
drawTime = ofClamp(gTime - mAdsr->GetStartTime(gTime), 0, GetReleaseTime());
if (mAdsr->GetStopTime(gTime) > mAdsr->GetStartTime(gTime))
drawTime = GetReleaseTime() + (gTime - mAdsr->GetStopTime(gTime));
if (drawTime > 0 && drawTime < mViewLength)
ofLine(GetXForTime(drawTime), mPosition.y, GetXForTime(drawTime), mPosition.y + mDimensions.y);
}
ofPopStyle();
}
void EnvelopeControl::OnClicked(float x, float y, bool right)
{
if (x > mPosition.x - pointClickRadius &&
x < mPosition.x + mDimensions.x + pointClickRadius &&
y > mPosition.y - pointClickRadius &&
y < mPosition.y + mDimensions.y + pointClickRadius &&
mAdsr != nullptr)
{
mClick = true;
if (right)
{
if (mHighlightCurve != -1)
{
mAdsr->GetStageData(mHighlightCurve).curve = 0;
}
if (mHighlightPoint != -1)
{
if (mHighlightPoint < mAdsr->GetNumStages() - 1)
{
mAdsr->GetStageData(mHighlightPoint + 1).time += mAdsr->GetStageData(mHighlightPoint).time;
mAdsr->GetStageData(mHighlightPoint + 1).curve = mAdsr->GetStageData(mHighlightPoint).curve;
for (int i = mHighlightPoint; i < mAdsr->GetNumStages(); ++i)
{
mAdsr->GetStageData(i).time = mAdsr->GetStageData(i + 1).time;
mAdsr->GetStageData(i).target = mAdsr->GetStageData(i + 1).target;
mAdsr->GetStageData(i).curve = mAdsr->GetStageData(i + 1).curve;
}
mAdsr->SetNumStages(mAdsr->GetNumStages() - 1);
if (mAdsr->GetHasSustainStage() &&
mHighlightPoint <= mAdsr->GetSustainStage())
mAdsr->SetSustainStage(mAdsr->GetSustainStage() - 1);
mHighlightPoint = -1;
}
}
}
else if (gTime < mLastClickTime + 500 &&
mHighlightCurve != -1 &&
(mClickStart - ofVec2f(x, y)).lengthSquared() < pointClickRadius * pointClickRadius)
{
float clickTime = GetTimeForX(x);
if (clickTime > GetPreSustainTime())
clickTime -= GetReleaseTime() - GetPreSustainTime();
for (int i = mAdsr->GetNumStages(); i > mHighlightCurve; --i)
{
mAdsr->GetStageData(i).time = mAdsr->GetStageData(i - 1).time;
mAdsr->GetStageData(i).target = mAdsr->GetStageData(i - 1).target;
mAdsr->GetStageData(i).curve = mAdsr->GetStageData(i - 1).curve;
}
float priorStageTimes = 0;
for (int i = 0; i < mHighlightCurve; ++i)
priorStageTimes += mAdsr->GetStageData(i).time;
mAdsr->GetStageData(mHighlightCurve).time = clickTime - priorStageTimes;
mAdsr->GetStageData(mHighlightCurve).target = GetValueForY(y);
mAdsr->GetStageData(mHighlightCurve + 1).time -= mAdsr->GetStageData(mHighlightCurve).time;
mAdsr->SetNumStages(mAdsr->GetNumStages() + 1);
if (mAdsr->GetHasSustainStage() &&
mHighlightCurve <= mAdsr->GetSustainStage())
mAdsr->SetSustainStage(mAdsr->GetSustainStage() + 1);
mHighlightPoint = mHighlightCurve;
mHighlightCurve = -1;
}
mLastClickTime = gTime;
mClickStart.set(x, y);
mClickAdsr.Set(*mAdsr);
}
}
void EnvelopeControl::MouseReleased()
{
mClick = false;
}
void EnvelopeControl::MouseMoved(float x, float y)
{
if (mAdsr == nullptr)
return;
if (!mClick)
{
ADSR::EventInfo adsrEvent(0, GetReleaseTime());
mHighlightPoint = -1;
float time = 0;
for (int i = 0; i < mAdsr->GetNumStages(); ++i)
{
if (mAdsr->GetHasSustainStage() && i == mAdsr->GetSustainStage() + 1)
time = GetReleaseTime();
time += mAdsr->GetStageData(i).time;
if (i == mAdsr->GetNumStages() - 1)
time += 0;
float value = mAdsr->Value(time, &adsrEvent);
float pointX = GetXForTime(time);
float pointY = GetYForValue(value);
if (fabsf(x - pointX) < 4 && fabsf(y - pointY) < 4)
{
mHighlightPoint = i;
mHighlightCurve = -1;
}
}
if (mHighlightPoint == -1)
{
float highlightTime = GetTimeForX(x);
float valueForY = GetValueForY(y);
double stageStartTime;
if (abs(mAdsr->Value(highlightTime, &adsrEvent) - valueForY) < .1f)
{
mHighlightCurve = mAdsr->GetStage(highlightTime, stageStartTime, &adsrEvent);
if (mAdsr->GetHasSustainStage() && mHighlightCurve == mAdsr->GetSustainStage() && highlightTime > GetPreSustainTime())
mHighlightCurve = -1;
if (mHighlightCurve >= mAdsr->GetNumStages())
mHighlightCurve = -1;
}
else
{
mHighlightCurve = -1;
}
}
}
else
{
if (mHighlightPoint != -1)
{
::ADSR::Stage& stage = mAdsr->GetStageData(mHighlightPoint);
::ADSR::Stage& originalStage = mClickAdsr.GetStageData(mHighlightPoint);
float maxLength = 10000;
if (mFixedLengthMode)
{
if (mHighlightPoint < mAdsr->GetNumStages() - 1)
maxLength = stage.time + mAdsr->GetStageData(mHighlightPoint + 1).time - 1;
else if (mHighlightPoint == mAdsr->GetNumStages() - 1)
{
float time = 0;
for (int i = 0; i < mAdsr->GetNumStages() - 1; ++i)
time += mAdsr->GetStageData(i).time;
maxLength = mViewLength - time - 1;
}
}
stage.time = ofClamp(originalStage.time + (x - mClickStart.x) / mDimensions.x * mViewLength, 0.001f, maxLength);
if (mFixedLengthMode && mHighlightPoint < mAdsr->GetNumStages() - 1)
{
float timeAdjustment = stage.time - originalStage.time;
mAdsr->GetStageData(mHighlightPoint + 1).time = mClickAdsr.GetStageData(mHighlightPoint + 1).time - timeAdjustment;
}
if (mHighlightPoint < mAdsr->GetNumStages() - 1 || mAdsr->GetFreeReleaseLevel())
stage.target = ofClamp(originalStage.target + ((mClickStart.y - y) / mDimensions.y), 0, 1);
else
stage.target = 0;
}
if (mHighlightCurve != -1)
{
::ADSR::Stage& stage = mAdsr->GetStageData(mHighlightCurve);
::ADSR::Stage& originalStage = mClickAdsr.GetStageData(mHighlightCurve);
stage.curve = ofClamp(originalStage.curve + ((mClickStart.y - y) / mDimensions.y), -1, 1);
}
}
}
void EnvelopeControl::AddVertex(float x, float y)
{
if (x >= mPosition.x && x <= mPosition.x + mDimensions.x)
ofVertex(x, y);
}
float EnvelopeControl::GetPreSustainTime()
{
float time = 0;
if (mAdsr != nullptr)
{
for (int i = 0; i <= mAdsr->GetSustainStage() || (!mAdsr->GetHasSustainStage() && i < mAdsr->GetNumStages()); ++i)
time += mAdsr->GetStageData(i).time;
}
return time;
}
float EnvelopeControl::GetReleaseTime()
{
if (mAdsr != nullptr && !mAdsr->GetHasSustainStage())
return GetPreSustainTime();
if (mAdsr != nullptr && mAdsr->GetMaxSustain() > 0)
return GetPreSustainTime() + mAdsr->GetMaxSustain();
else
return GetPreSustainTime() + mViewLength * .2f;
}
float EnvelopeControl::GetTimeForX(float x)
{
return ofMap(x, mPosition.x, mPosition.x + mDimensions.x, 0, mViewLength);
}
float EnvelopeControl::GetValueForY(float y)
{
return ofMap(y, mPosition.y, mPosition.y + mDimensions.y, 1, 0);
}
float EnvelopeControl::GetXForTime(float time)
{
return time / mViewLength * mDimensions.x + mPosition.x;
}
float EnvelopeControl::GetYForValue(float value)
{
return mDimensions.y * (1 - value) + mPosition.y;
}
EnvelopeEditor::EnvelopeEditor()
: mEnvelopeControl(ofVec2f(5, 25), ofVec2f(380, 200))
{
}
void EnvelopeEditor::CreateUIControls()
{
IDrawableModule::CreateUIControls();
static bool dummyBool;
static float dummyFloat;
UIBLOCK(3, 3, 130);
FLOATSLIDER(mADSRViewLengthSlider, "view length", &dummyFloat, 10, 10000);
UIBLOCK_SHIFTRIGHT();
FLOATSLIDER(mMaxSustainSlider, "max sustain", &dummyFloat, -1, 5000);
UIBLOCK_SHIFTRIGHT();
BUTTON(mPinButton, "pin");
UIBLOCK_SHIFTRIGHT();
CHECKBOX(mFreeReleaseLevelCheckbox, "free release", &dummyBool);
ENDUIBLOCK0();
UIBLOCK(3, mHeight - 70);
for (size_t i = 0; i < mStageControls.size(); ++i)
{
FLOATSLIDER(mStageControls[i].mTargetSlider, ("target" + ofToString(i)).c_str(), &dummyFloat, 0, 1);
FLOATSLIDER(mStageControls[i].mTimeSlider, ("time" + ofToString(i)).c_str(), &dummyFloat, 1, 1000);
FLOATSLIDER(mStageControls[i].mCurveSlider, ("curve" + ofToString(i)).c_str(), &dummyFloat, -1, 1);
CHECKBOX(mStageControls[i].mSustainCheckbox, ("sustain" + ofToString(i)).c_str(), &mStageControls[i].mIsSustainStage);
UIBLOCK_NEWCOLUMN();
mStageControls[i].mTimeSlider->SetMode(FloatSlider::kSquare);
}
ENDUIBLOCK0();
mADSRViewLengthSlider->SetMode(FloatSlider::kSquare);
mMaxSustainSlider->SetMode(FloatSlider::kSquare);
Resize(mWidth, mHeight);
}
EnvelopeEditor::~EnvelopeEditor()
{
}
void EnvelopeEditor::SetADSRDisplay(ADSRDisplay* adsrDisplay)
{
mEnvelopeControl.SetADSR(adsrDisplay->GetADSR());
mADSRDisplay = adsrDisplay;
mADSRViewLengthSlider->SetVar(&adsrDisplay->GetMaxTime());
mMaxSustainSlider->SetVar(&adsrDisplay->GetADSR()->GetMaxSustain());
mFreeReleaseLevelCheckbox->SetVar(&adsrDisplay->GetADSR()->GetFreeReleaseLevel());
for (int i = 0; i < (int)mStageControls.size(); ++i)
{
mStageControls[i].mTargetSlider->SetVar(&adsrDisplay->GetADSR()->GetStageData(i).target);
mStageControls[i].mTimeSlider->SetVar(&adsrDisplay->GetADSR()->GetStageData(i).time);
mStageControls[i].mCurveSlider->SetVar(&adsrDisplay->GetADSR()->GetStageData(i).curve);
mStageControls[i].mIsSustainStage = adsrDisplay->GetADSR()->GetHasSustainStage() && (adsrDisplay->GetADSR()->GetSustainStage() == i);
}
}
void EnvelopeEditor::DoSpecialDelete()
{
mEnabled = false;
mPinned = false;
}
void EnvelopeEditor::DrawModule()
{
if (!mPinned)
{
float w, h;
GetDimensions(w, h);
ofPushStyle();
ofSetColor(0, 0, 0);
ofFill();
ofSetLineWidth(.5f);
ofRect(0, 0, w, h);
ofNoFill();
ofSetColor(255, 255, 255);
ofRect(0, 0, w, h);
ofPopStyle();
}
mMaxSustainSlider->SetShowing(mADSRDisplay != nullptr && mADSRDisplay->GetADSR()->GetHasSustainStage());
mADSRViewLengthSlider->Draw();
mMaxSustainSlider->Draw();
mFreeReleaseLevelCheckbox->Draw();
if (!mPinned)
mPinButton->Draw();
if (mADSRDisplay != nullptr)
mEnvelopeControl.SetViewLength(mADSRDisplay->GetMaxTime());
mEnvelopeControl.Draw();
if (mADSRDisplay != nullptr)
{
int numStages = mADSRDisplay->GetADSR()->GetNumStages();
for (int i = 0; i < (int)mStageControls.size(); ++i)
{
mStageControls[i].mIsSustainStage = mADSRDisplay->GetADSR()->GetHasSustainStage() && (mADSRDisplay->GetADSR()->GetSustainStage() == i);
mStageControls[i].mTargetSlider->SetShowing(i < numStages);
mStageControls[i].mTimeSlider->SetShowing(i < numStages);
mStageControls[i].mCurveSlider->SetShowing(i < numStages);
mStageControls[i].mSustainCheckbox->SetShowing(i > 0 && i < numStages - 1);
mStageControls[i].mTargetSlider->Draw();
mStageControls[i].mTimeSlider->Draw();
mStageControls[i].mCurveSlider->Draw();
mStageControls[i].mSustainCheckbox->Draw();
}
//move release level checkbox below final stage control
ofVec2f pos = mStageControls[numStages - 1].mSustainCheckbox->GetPosition(K(local));
mFreeReleaseLevelCheckbox->SetPosition(pos.x, pos.y);
}
}
void EnvelopeEditor::Resize(float w, float h)
{
w = MAX(w, 250);
h = MAX(h, 150);
mEnvelopeControl.SetDimensions(ofVec2f(w - 10, h - 105));
for (int i = 0; i < (int)mStageControls.size(); ++i)
{
mStageControls[i].mTargetSlider->Move(0, h - mHeight);
mStageControls[i].mTimeSlider->Move(0, h - mHeight);
mStageControls[i].mCurveSlider->Move(0, h - mHeight);
mStageControls[i].mSustainCheckbox->Move(0, h - mHeight);
}
mWidth = w;
mHeight = h;
}
void EnvelopeEditor::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
mEnvelopeControl.OnClicked(x, y, right);
}
void EnvelopeEditor::MouseReleased()
{
IDrawableModule::MouseReleased();
mEnvelopeControl.MouseReleased();
}
bool EnvelopeEditor::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
mEnvelopeControl.MouseMoved(x, y);
return false;
}
void EnvelopeEditor::CheckboxUpdated(Checkbox* checkbox, double time)
{
for (int i = 0; i < (int)mStageControls.size(); ++i)
{
if (checkbox == mStageControls[i].mSustainCheckbox && mADSRDisplay != nullptr)
{
if (mStageControls[i].mIsSustainStage)
{
mADSRDisplay->GetADSR()->GetHasSustainStage() = true;
mADSRDisplay->GetADSR()->SetSustainStage(i);
}
else
{
mADSRDisplay->GetADSR()->GetHasSustainStage() = false;
}
}
}
}
void EnvelopeEditor::ButtonClicked(ClickButton* button, double time)
{
if (button == mPinButton)
{
if (!mPinned)
{
TheSynth->AddDynamicModule(this);
TheSynth->PopModalFocusItem();
SetName(GetUniqueName("envelopeeditor", TheSynth->GetModuleNames<EnvelopeEditor*>()).c_str());
Pin();
}
}
}
void EnvelopeEditor::Pin()
{
mPinned = true;
if (mTargetCable == nullptr)
{
mTargetCable = new PatchCableSource(this, kConnectionType_Modulator);
AddPatchCableSource(mTargetCable);
mTargetCable->SetTarget(mADSRDisplay);
mTargetCable->SetClickable(false);
}
}
void EnvelopeEditor::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mADSRViewLengthSlider)
{
for (int i = 0; i < (int)mStageControls.size(); ++i)
{
if (mADSRDisplay != nullptr)
mStageControls[i].mTimeSlider->SetExtents(1, mADSRDisplay->GetMaxTime());
}
}
}
void EnvelopeEditor::SaveLayout(ofxJSONElement& moduleInfo)
{
if (mADSRDisplay != nullptr)
moduleInfo["target"] = mADSRDisplay->Path();
moduleInfo["onthefly"] = false;
}
void EnvelopeEditor::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
if (moduleInfo["onthefly"] == false)
{
SetUpFromSaveData();
Pin();
// Since `mPinned` is set after `IDrawableModule::LoadBasics` we need to manually set minimized
// after setting `mPinned` which is used to check if this module has a titlebar.
SetMinimized(moduleInfo["start_minimized"].asBool(), false);
}
}
void EnvelopeEditor::SetUpFromSaveData()
{
ADSRDisplay* display = dynamic_cast<ADSRDisplay*>(TheSynth->FindUIControl(mModuleSaveData.GetString("target")));
if (display != nullptr)
SetADSRDisplay(display);
}
``` | /content/code_sandbox/Source/EnvelopeEditor.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 5,619 |
```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
**/
//
// NoteCreator.h
// Bespoke
//
// Created by Ryan Challinor on 12/28/15.
//
//
#pragma once
#include "IDrawableModule.h"
#include "INoteSource.h"
#include "ClickButton.h"
#include "TextEntry.h"
#include "Slider.h"
#include "IPulseReceiver.h"
class NoteCreator : public IDrawableModule, public INoteSource, public IButtonListener, public ITextEntryListener, public IFloatSliderListener, public IPulseReceiver
{
public:
NoteCreator();
virtual ~NoteCreator();
static IDrawableModule* Create() { return new NoteCreator(); }
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 OnPulse(double time, float velocity, int flags) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void TextEntryComplete(TextEntry* entry) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override {}
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
protected:
void TriggerNote(double time, float velocity);
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& w, float& h) override
{
w = mWidth;
h = mHeight;
}
int mWidth{ 200 };
int mHeight{ 20 };
ClickButton* mTriggerButton{ nullptr };
TextEntry* mPitchEntry{ nullptr };
FloatSlider* mVelocitySlider{ nullptr };
FloatSlider* mDurationSlider{ nullptr };
Checkbox* mNoteOnCheckbox{ nullptr };
int mPitch{ 48 };
float mVelocity{ 1 };
float mDuration{ 100 };
double mStartTime{ 0 };
bool mNoteOn{ false };
int mVoiceIndex{ -1 };
};
``` | /content/code_sandbox/Source/NoteCreator.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 586 |
```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
**/
//
// VSTPlugin.h
// Bespoke
//
// Created by Ryan Challinor on 1/18/16.
//
//
#pragma once
#include "IAudioProcessor.h"
#include "PolyphonyMgr.h"
#include "INoteReceiver.h"
#include "INoteSource.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "DropdownList.h"
#include "Ramp.h"
#include "VSTPlayhead.h"
#include "VSTWindow.h"
#include <atomic>
#include "juce_audio_processors/juce_audio_processors.h"
class ofxJSONElement;
//class NSWindowOverlay;
namespace VSTLookup
{
void GetAvailableVSTs(std::vector<juce::PluginDescription>& vsts);
void FillVSTList(DropdownList* list);
std::string GetVSTPath(std::string vstName);
bool GetPluginDesc(juce::PluginDescription& desc, juce::String pluginId);
void SortByLastUsed(std::vector<juce::PluginDescription>& vsts);
void GetRecentPlugins(std::vector<juce::PluginDescription>& recentPlugins, int num);
}
class VSTPlugin : public IAudioProcessor, public INoteReceiver, public IDrawableModule, public IDropdownListener, public IFloatSliderListener, public IIntSliderListener, public IButtonListener, public juce::AudioProcessorListener
{
public:
VSTPlugin();
virtual ~VSTPlugin() override;
static IDrawableModule* Create() { return new VSTPlugin(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
std::string GetTitleLabel() const override;
void CreateUIControls() override;
void SetVol(float vol) { mVol = vol; }
void Poll() override;
void Exit() override;
juce::AudioProcessor* GetAudioProcessor() { return mPlugin.get(); }
void SetVST(juce::PluginDescription pluginDesc);
void OnVSTWindowClosed();
//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 SendMidi(const juce::MidiMessage& message) override;
void DropdownClicked(DropdownList* list) override;
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 ButtonClicked(ClickButton* button, double time) override;
void OnUIControlRequested(const char* name) override;
virtual void SaveLayout(ofxJSONElement& moduleInfo) 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 3; }
std::vector<IUIControl*> ControlsToIgnoreInSaveState() const override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void PreDrawModule() override;
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void LoadVST(juce::PluginDescription desc);
void LoadVSTFromSaveData(FileStreamIn& in, int rev);
void GetVSTFileDesc(std::string vstName, juce::PluginDescription& desc);
std::string GetPluginName() const;
std::string GetPluginFormatName() const;
std::string GetPluginId() const;
void CreateParameterSliders();
void RefreshPresetFiles();
//juce::AudioProcessorListener
void audioProcessorParameterChanged(juce::AudioProcessor* processor, int parameterIndex, float newValue) override {}
void audioProcessorChanged(juce::AudioProcessor* processor, const ChangeDetails& details) override;
void audioProcessorParameterChangeGestureBegin(juce::AudioProcessor* processor, int parameterIndex) override;
float mVol{ 1 };
FloatSlider* mVolSlider{ nullptr };
int mPresetFileIndex{ -1 };
DropdownList* mPresetFileSelector{ nullptr };
bool mPresetFileUpdateQueued{ false };
ClickButton* mSavePresetFileButton{ nullptr };
std::vector<std::string> mPresetFilePaths;
ClickButton* mOpenEditorButton{ nullptr };
ClickButton* mPanicButton{ nullptr };
std::atomic<bool> mWantsPanic{ false };
bool mPluginReady{ false };
std::unique_ptr<juce::AudioProcessor> mPlugin;
std::string mPluginName;
std::string mPluginFormatName;
std::string mPluginId;
std::unique_ptr<VSTWindow> mWindow;
juce::MidiBuffer mMidiBuffer;
juce::MidiBuffer mFutureMidiBuffer;
juce::CriticalSection mMidiInputLock;
std::atomic<bool> mRescanParameterNames{ false };
juce::String cutOffIdHash(juce::String);
int mNumInputChannels{ 2 };
int mNumOutputChannels{ 2 };
int mNumInBuses{ 0 };
int mNumOutBuses{ 0 };
struct ParameterSlider
{
VSTPlugin* mOwner{ nullptr };
float mValue{ 0 };
FloatSlider* mSlider{ nullptr };
juce::AudioProcessorParameter* mParameter{ nullptr };
bool mShowing{ false };
bool mInSelectorList{ true };
std::string mDisplayName;
std::string mID;
void MakeSlider();
};
std::vector<ParameterSlider> mParameterSliders;
int mChangeGestureParameterIndex{ -1 };
int mChannel{ 1 };
bool mUseVoiceAsChannel{ false };
float mPitchBendRange{ 2 };
int mModwheelCC{ 1 }; //or 74 in Multidimensional Polyphonic Expression (MPE) spec
std::string mOldVstPath{ "" }; //for loading save files that predate pluginId-style saving
int mParameterVersion{ 1 };
struct ChannelModulations
{
ModulationParameters mModulation;
float mLastPitchBend{ 0 };
float mLastModWheel{ 0 };
float mLastPressure{ 0 };
};
std::vector<ChannelModulations> mChannelModulations;
ofMutex mVSTMutex;
VSTPlayhead mPlayhead;
//NSWindowOverlay* mWindowOverlay{ nullptr };
enum DisplayMode
{
kDisplayMode_Sliders,
kDisplayMode_PluginOverlay
};
DisplayMode mDisplayMode{ DisplayMode::kDisplayMode_Sliders };
int mShowParameterIndex{ -1 };
DropdownList* mShowParameterDropdown{ nullptr };
static constexpr int kMaxParametersInDropdown{ 30 };
int mTemporarilyDisplayedParamIndex{ -1 };
/*
* Midi and MultiOut support
*/
AdditionalNoteCable* mMidiOutCable{ nullptr };
bool mWantOpenVstWindow{ false };
};
``` | /content/code_sandbox/Source/VSTPlugin.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,774 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NoteSorter.cpp
Created: 2 Aug 2021 10:32:39pm
Author: Ryan Challinor
==============================================================================
*/
#include "NoteSorter.h"
#include "OpenFrameworksPort.h"
#include "Scale.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
NoteSorter::NoteSorter()
{
std::fill(mPitch.begin(), mPitch.end(), -1);
}
void NoteSorter::CreateUIControls()
{
IDrawableModule::CreateUIControls();
}
void NoteSorter::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
for (int i = 0; i < (int)mDestinationCables.size(); ++i)
{
mPitchEntry[i]->Draw();
ofRectangle rect = mPitchEntry[i]->GetRect(true);
mDestinationCables[i]->GetPatchCableSource()->SetManualPosition(rect.getMaxX() + 15, rect.y + rect.height / 2);
}
}
void NoteSorter::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
bool foundPitch = false;
for (int i = 0; i < mDestinationCables.size(); ++i)
{
if (pitch == mPitch[i])
{
mDestinationCables[i]->PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
foundPitch = true;
}
}
if (!foundPitch)
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
}
void NoteSorter::SendCC(int control, int value, int voiceIdx)
{
SendCCOutput(control, value, voiceIdx);
}
void NoteSorter::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadInt("num_items", moduleInfo, 5, 1, 99, K(isTextField));
SetUpFromSaveData();
}
void NoteSorter::TextEntryComplete(TextEntry* entry)
{
mNoteOutput.Flush(NextBufferTime(false));
for (int i = 0; i < mDestinationCables.size(); ++i)
mDestinationCables[i]->Flush(NextBufferTime(false));
}
void NoteSorter::GetModuleDimensions(float& width, float& height)
{
width = 80;
height = 12 + (mDestinationCables.size() * 19);
}
void NoteSorter::SetUpFromSaveData()
{
int numItems = mModuleSaveData.GetInt("num_items");
int oldNumItems = (int)mDestinationCables.size();
if (numItems > oldNumItems)
{
for (int i = oldNumItems; i < numItems; ++i)
{
mPitchEntry.push_back(new TextEntry(this, ("pitch " + ofToString(i)).c_str(), 8, 8 + i * 19, 5, &mPitch[i], -1, 127));
auto* additionalCable = new AdditionalNoteCable();
additionalCable->SetPatchCableSource(new PatchCableSource(this, kConnectionType_Note));
AddPatchCableSource(additionalCable->GetPatchCableSource());
mDestinationCables.push_back(additionalCable);
}
}
else if (numItems < oldNumItems)
{
for (int i = oldNumItems - 1; i >= numItems; --i)
{
RemoveUIControl(mPitchEntry[i]);
RemovePatchCableSource(mDestinationCables[i]->GetPatchCableSource());
}
mPitchEntry.resize(numItems);
mDestinationCables.resize(numItems);
}
}
void NoteSorter::SaveLayout(ofxJSONElement& moduleInfo)
{
moduleInfo["num_items"] = (int)mDestinationCables.size();
}
``` | /content/code_sandbox/Source/NoteSorter.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 929 |
```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
**/
//
// KeyboardDisplay.h
// Bespoke
//
// Created by Ryan Challinor on 5/12/16.
// Tweaked by ArkyonVeil on April/2024
//
#pragma once
#include "IDrawableModule.h"
#include "NoteEffectBase.h"
#include <unordered_map>
class KeyboardDisplay : public IDrawableModule, public NoteEffectBase, public IKeyboardFocusListener
{
public:
KeyboardDisplay();
static IDrawableModule* Create() { return new KeyboardDisplay(); }
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;
void KeyReleased(int key) override;
//IKeyboardFocusListener
void OnKeyPressed(int key, bool isRepeat) override;
bool ShouldConsumeKey(int key) override;
bool CanTakeFocus() override { return mAllowHoverTypingInput; }
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:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void OnClicked(float x, float y, bool right) override;
bool IsResizable() const override { return true; }
void Resize(float w, float h) override;
void RefreshOctaveCount();
void DrawKeyboard(int x, int y, int w, int h);
void SetPitchColor(int pitch);
ofRectangle GetKeyboardKeyRect(int pitch, int w, int h, bool& isBlackKey) const;
int RootKey() const;
int NumKeys() const;
float mWidth{ 500 };
float mHeight{ 110 };
int mRootOctave{ 3 };
int mNumOctaves{ 3 };
int mForceNumOctaves{ 0 };
int mPlayingMousePitch{ -1 };
bool mAllowHoverTypingInput{ true };
bool mLatch{ false };
bool mShowScale{ false };
bool mGetVelocityFromClickHeight{ false };
bool mHideLabels{ false };
std::array<float, 128> mLastOnTime{};
std::array<float, 128> mLastOffTime{};
std::unordered_map<int, int> mKeyPressRegister{};
};
``` | /content/code_sandbox/Source/KeyboardDisplay.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 761 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Beats.cpp
// modularSynth
//
// Created by Ryan Challinor on 2/2/14.
//
//
#include "Beats.h"
#include "IAudioReceiver.h"
#include "Sample.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "FillSaveDropdown.h"
#include "PatchCableSource.h"
Beats::Beats()
: mWriteBuffer(gBufferSize)
{
mBeatColumns.resize(1);
for (size_t i = 0; i < mBeatColumns.size(); ++i)
mBeatColumns[i] = new BeatColumn(this, (int)i);
}
void Beats::Init()
{
IDrawableModule::Init();
TheTransport->AddListener(this, kInterval_1n, OffsetInfo(0, true), false);
}
void Beats::CreateUIControls()
{
IDrawableModule::CreateUIControls();
for (size_t i = 0; i < mBeatColumns.size(); ++i)
mBeatColumns[i]->CreateUIControls();
}
Beats::~Beats()
{
TheTransport->RemoveListener(this);
}
void Beats::Process(double time)
{
PROFILER(Beats);
IAudioReceiver* target = GetTarget();
if (!mEnabled || target == nullptr)
return;
int numChannels = 2;
ComputeSliders(0);
SyncOutputBuffer(numChannels);
mWriteBuffer.SetNumActiveChannels(numChannels);
int bufferSize = target->GetBuffer()->BufferSize();
assert(bufferSize == gBufferSize);
mWriteBuffer.Clear();
for (BeatColumn* column : mBeatColumns)
column->Process(time, &mWriteBuffer, bufferSize);
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 Beats::DropdownClicked(DropdownList* list)
{
}
void Beats::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void Beats::RadioButtonUpdated(RadioButton* list, int oldVal, double time)
{
for (BeatColumn* column : mBeatColumns)
column->RadioButtonUpdated(list, oldVal, time);
}
void Beats::OnTimeEvent(double time)
{
}
void Beats::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
int i = 0;
for (BeatColumn* column : mBeatColumns)
{
if (i == mHighlightColumn)
{
ofPushStyle();
ofFill();
ofSetColor(255, 255, 255, 40);
float width, height;
GetModuleDimensions(width, height);
ofRect(i * BEAT_COLUMN_WIDTH + 1, 3, BEAT_COLUMN_WIDTH - 2, height - 6);
ofPopStyle();
}
column->Draw(i * BEAT_COLUMN_WIDTH + 3, 5);
++i;
}
}
void Beats::FilesDropped(std::vector<std::string> files, int x, int y)
{
for (auto file : files)
{
Sample* sample = new Sample();
sample->Read(file.c_str());
SampleDropped(x, y, sample);
}
mHighlightColumn = -1;
}
void Beats::SampleDropped(int x, int y, Sample* sample)
{
assert(sample);
int numSamples = sample->LengthInSamples();
if (numSamples <= 0)
return;
int column = x / BEAT_COLUMN_WIDTH;
if (column < (int)mBeatColumns.size())
mBeatColumns[column]->AddBeat(sample);
mHighlightColumn = -1;
}
bool Beats::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
int column = x / BEAT_COLUMN_WIDTH;
if (TheSynth->GetHeldSample() != nullptr && column >= 0 && column < (int)mBeatColumns.size())
mHighlightColumn = column;
else
mHighlightColumn = -1;
return false;
}
void Beats::ButtonClicked(ClickButton* button, double time)
{
for (BeatColumn* column : mBeatColumns)
column->ButtonClicked(button, time);
}
void Beats::CheckboxUpdated(Checkbox* checkbox, double time)
{
}
void Beats::GetModuleDimensions(float& width, float& height)
{
width = BEAT_COLUMN_WIDTH * (int)mBeatColumns.size();
height = 0;
for (size_t i = 0; i < mBeatColumns.size(); ++i)
height = MAX(height, 132 + 15 * (mBeatColumns[i]->GetNumSamples() + 1));
}
void Beats::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void Beats::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void Beats::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void Beats::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void Beats::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
void Beats::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out << (int)mBeatColumns.size();
for (size_t i = 0; i < mBeatColumns.size(); ++i)
mBeatColumns[i]->SaveState(out);
}
void Beats::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
int numColumns;
in >> numColumns;
if (numColumns != (int)mBeatColumns.size())
{
mBeatColumns.resize(numColumns);
for (size_t i = 0; i < mBeatColumns.size(); ++i)
{
mBeatColumns[i] = new BeatColumn(this, (int)i);
mBeatColumns[i]->CreateUIControls();
}
}
for (size_t i = 0; i < mBeatColumns.size(); ++i)
mBeatColumns[i]->LoadState(in);
}
void BeatData::LoadBeat(Sample* sample)
{
mBeat = sample;
}
void BeatData::RecalcPos(double time, bool doubleTime, int numBars)
{
float measurePos = TheTransport->GetMeasure(time) % numBars + TheTransport->GetMeasurePos(time);
float pos = ofMap(measurePos / numBars, 0, 1, 0, mBeat->LengthInSamples(), true);
if (doubleTime)
{
pos *= 2;
if (pos >= mBeat->LengthInSamples())
pos -= mBeat->LengthInSamples();
}
mBeat->SetPlayPosition(pos);
}
BeatColumn::BeatColumn(Beats* owner, int index)
: mOwner(owner)
, mIndex(index)
{
for (size_t i = 0; i < mLowpass.size(); ++i)
mLowpass[i].SetFilterType(kFilterType_Lowpass);
for (size_t i = 0; i < mHighpass.size(); ++i)
mHighpass[i].SetFilterType(kFilterType_Highpass);
}
BeatColumn::~BeatColumn()
{
mSelector->Delete();
mVolumeSlider->Delete();
for (size_t i = 0; i < mSamples.size(); ++i)
delete mSamples[i];
}
void BeatColumn::Process(double time, ChannelBuffer* buffer, int bufferSize)
{
Sample* beat = mBeatData.mBeat;
if (beat && mSampleIndex != -1)
{
float volSq = mVolume * mVolume * .25f;
float speed = (beat->LengthInSamples() / beat->GetSampleRateRatio()) * gInvSampleRateMs / TheTransport->MsPerBar() / mNumBars;
if (mDoubleTime)
speed *= 2;
mBeatData.RecalcPos(time, mDoubleTime, mNumBars);
beat->SetRate(speed);
int numChannels = 2;
gWorkChannelBuffer.SetNumActiveChannels(numChannels);
if (beat->ConsumeData(time, &gWorkChannelBuffer, bufferSize, true))
{
mFilterRamp.Start(time, mFilter, time + 10);
for (int ch = 0; ch < numChannels; ++ch)
{
float panGain = ch == 0 ? GetLeftPanGain(mPan) : GetRightPanGain(mPan);
double channelTime = time;
for (int i = 0; i < bufferSize; ++i)
{
float filter = mFilterRamp.Value(channelTime);
mLowpass[ch].SetFilterParams(ofMap(sqrtf(ofClamp(-filter, 0, 1)), 0, 1, 6000, 80), sqrt(2) / 2);
mHighpass[ch].SetFilterParams(ofMap(ofClamp(filter, 0, 1), 0, 1, 10, 6000), sqrt(2) / 2);
const float crossfade = .1f;
float normalAmount = ofClamp(1 - fabsf(filter / crossfade), 0, 1);
float lowAmount = ofClamp(-filter / crossfade, 0, 1);
float highAmount = ofClamp(filter / crossfade, 0, 1);
int sampleChannel = ch;
if (beat->NumChannels() == 1)
sampleChannel = 0;
float normal = gWorkChannelBuffer.GetChannel(sampleChannel)[i];
float lowPassed = mLowpass[ch].Filter(normal);
float highPassed = mHighpass[ch].Filter(normal);
float sample = normal * normalAmount + lowPassed * lowAmount + highPassed * highAmount;
sample *= volSq * panGain;
buffer->GetChannel(ch)[i] += sample;
channelTime += gInvSampleRateMs;
}
}
}
}
}
void BeatColumn::Draw(int x, int y)
{
if (mBeatData.mBeat && mSampleIndex != -1)
{
int w = BEAT_COLUMN_WIDTH - 6;
int h = 35;
ofPushMatrix();
ofTranslate(x, y);
DrawAudioBuffer(w, h, mBeatData.mBeat->Data(), 0, mBeatData.mBeat->LengthInSamples(), mBeatData.mBeat->GetPlayPosition());
/*//frequency response
ofSetColor(52, 204, 235);
ofSetLineWidth(3);
ofBeginShape();
const int kPixelStep = 2;
bool updateFrequencyResponseGraph = false;
if (mNeedToUpdateFrequencyResponseGraph)
{
updateFrequencyResponseGraph = true;
mNeedToUpdateFrequencyResponseGraph = false;
}
for (int x = 0; x < w + kPixelStep; x += kPixelStep)
{
float response = 1;
float freq = FreqForPos(x / w);
if (freq < gSampleRate / 2)
{
int responseGraphIndex = x / kPixelStep;
if (updateFrequencyResponseGraph || responseGraphIndex >= mFrequencyResponse.size())
{
for (auto& filter : mFilters)
{
if (filter.mEnabled)
response *= filter.mFilter[0].GetMagnitudeResponseAt(freq);
}
if (responseGraphIndex < mFrequencyResponse.size())
mFrequencyResponse[responseGraphIndex] = response;
}
else
{
response = mFrequencyResponse[responseGraphIndex];
}
ofVertex(x, (.5f - .666f * log10(response)) * h);
}
}
ofEndShape(false);*/
ofPopMatrix();
}
mVolumeSlider->SetPosition(x, y + 40);
mVolumeSlider->Draw();
mFilterSlider->SetPosition(x, y + 56);
mFilterSlider->Draw();
mPanSlider->SetPosition(x, y + 72);
mPanSlider->Draw();
mDoubleTimeCheckbox->SetPosition(x, y + 88);
mDoubleTimeCheckbox->Draw();
mNumBarsSlider->SetPosition(x, y + 104);
mNumBarsSlider->Draw();
mSelector->SetPosition(x, y + 120);
mSelector->Draw();
mDeleteButton->SetPosition(x + 80, y + 88);
mDeleteButton->SetShowing(mSampleIndex != -1);
mDeleteButton->Draw();
}
void BeatColumn::CreateUIControls()
{
std::string suffix = "";
if (mOwner->GetNumColumns() > 1)
suffix = ofToString(mIndex);
int controlWidth = BEAT_COLUMN_WIDTH - 6;
mVolumeSlider = new FloatSlider(mOwner, ("volume" + suffix).c_str(), 0, 0, controlWidth, 15, &mVolume, 0, 1.5f, 2);
mFilterSlider = new FloatSlider(mOwner, ("filter" + suffix).c_str(), 0, 0, controlWidth, 15, &mFilter, -1, 1, 2);
mPanSlider = new FloatSlider(mOwner, ("pan" + suffix).c_str(), 0, 0, controlWidth, 15, &mPan, -1, 1, 2);
mDoubleTimeCheckbox = new Checkbox(mOwner, ("double" + suffix).c_str(), 0, 0, &mDoubleTime);
mNumBarsSlider = new IntSlider(mOwner, ("bars" + suffix).c_str(), 0, 0, controlWidth, 15, &mNumBars, 1, 8);
mSelector = new RadioButton(mOwner, ("selector" + suffix).c_str(), 0, 0, &mSampleIndex);
mDeleteButton = new ClickButton(mOwner, ("delete " + suffix).c_str(), 0, 0);
mSelector->SetForcedWidth(controlWidth);
mSelector->AddLabel("none", -1);
}
void BeatColumn::AddBeat(Sample* sample)
{
mSelector->AddLabel(sample->Name().c_str(), mSelector->GetNumValues() - 1);
Sample* newSample = new Sample();
newSample->CopyFrom(sample);
mSamples.push_back(newSample);
}
void BeatColumn::RadioButtonUpdated(RadioButton* list, int oldVal, double time)
{
if (list == mSelector)
{
if (mSampleIndex != -1 && mSampleIndex < (int)mSamples.size())
mBeatData.LoadBeat(mSamples[mSampleIndex]);
}
}
void BeatColumn::ButtonClicked(ClickButton* button, double time)
{
if (button == mDeleteButton)
{
if (mSampleIndex >= 0 && mSampleIndex < (int)mSamples.size())
{
mSamples.erase(mSamples.begin() + mSampleIndex);
mSelector->RemoveLabel(mSampleIndex);
mSampleIndex = -1;
mSelector->Clear();
mSelector->AddLabel("none", -1);
for (int i = 0; i < (int)mSamples.size(); ++i)
mSelector->AddLabel(mSamples[i]->Name().c_str(), i);
}
}
}
void BeatColumn::SaveState(FileStreamOut& out)
{
out << (int)mSamples.size();
for (size_t i = 0; i < mSamples.size(); ++i)
mSamples[i]->SaveState(out);
out << mSampleIndex;
}
void BeatColumn::LoadState(FileStreamIn& in)
{
int numSamples;
in >> numSamples;
mSamples.resize(numSamples);
if (numSamples > 0)
{
mSelector->Clear();
mSelector->AddLabel("none", -1);
}
for (size_t i = 0; i < mSamples.size(); ++i)
{
mSamples[i] = new Sample();
mSamples[i]->LoadState(in);
mSelector->AddLabel(mSamples[i]->Name().c_str(), mSelector->GetNumValues() - 1);
}
in >> mSampleIndex;
if (mSampleIndex >= 0 && mSampleIndex < (int)mSamples.size())
mBeatData.LoadBeat(mSamples[mSampleIndex]);
}
``` | /content/code_sandbox/Source/Beats.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 3,751 |
```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
**/
//
// NoteCanvas.h
// Bespoke
//
// Created by Ryan Challinor on 12/30/14.
//
//
#pragma once
#include "IDrawableModule.h"
#include "INoteSource.h"
#include "Transport.h"
#include "Checkbox.h"
#include "Canvas.h"
#include "Slider.h"
#include "INoteReceiver.h"
#include "ClickButton.h"
#include "DropdownList.h"
#include "TextEntry.h"
class CanvasControls;
class CanvasTimeline;
class CanvasScrollbar;
class NoteCanvas : public IDrawableModule, public INoteSource, public ICanvasListener, public IFloatSliderListener, public IAudioPoller, public IIntSliderListener, public INoteReceiver, public IButtonListener, public IDropdownListener, public ITextEntryListener
{
public:
NoteCanvas();
~NoteCanvas();
static IDrawableModule* Create() { return new NoteCanvas(); }
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;
void KeyPressed(int key, bool isRepeat) 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 {}
void Clear(double time);
NoteCanvasElement* AddNote(double measurePos, int pitch, int velocity, double length, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters());
/**
* @brief FitNotes adapt measures to fit all added notes
*/
void FitNotes();
void OnTransportAdvanced(float amount) override;
void CanvasUpdated(Canvas* canvas) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
void ButtonClicked(ClickButton* button, double time) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void TextEntryComplete(TextEntry* entry) override {}
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
void SaveLayout(ofxJSONElement& moduleInfo) 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;
double GetCurPos(double time) const;
void UpdateNumColumns();
void SetRecording(bool rec);
void SetNumMeasures(int numMeasures);
bool FreeRecordParityMatched();
void ClipNotes();
void QuantizeNotes();
void LoadMidi();
void SaveMidi();
Canvas* mCanvas{ nullptr };
CanvasControls* mCanvasControls{ nullptr };
CanvasTimeline* mCanvasTimeline{ nullptr };
CanvasScrollbar* mCanvasScrollbarHorizontal{ nullptr };
CanvasScrollbar* mCanvasScrollbarVertical{ nullptr };
std::vector<CanvasElement*> mNoteChecker{ 128 };
std::vector<NoteCanvasElement*> mInputNotes{ 128 };
std::vector<NoteCanvasElement*> mCurrentNotes{ 128 };
IntSlider* mNumMeasuresSlider{ nullptr };
int mNumMeasures{ 1 };
ClickButton* mQuantizeButton{ nullptr };
ClickButton* mSaveMidiButton{ nullptr };
ClickButton* mLoadMidiButton{ nullptr };
TextEntry* mLoadMidiTrackEntry{ nullptr };
int mLoadMidiTrack{ 1 };
ClickButton* mClipButton{ nullptr };
bool mPlay{ true };
Checkbox* mPlayCheckbox{ nullptr };
bool mRecord{ false };
Checkbox* mRecordCheckbox{ nullptr };
bool mStopQueued{ false };
NoteInterval mInterval{ NoteInterval::kInterval_8n };
DropdownList* mIntervalSelector{ nullptr };
bool mFreeRecord{ false };
Checkbox* mFreeRecordCheckbox{ nullptr };
int mFreeRecordStartMeasure{ 0 };
bool mShowIntervals{ false };
Checkbox* mShowIntervalsCheckbox{ nullptr };
std::vector<ModulationParameters> mVoiceModulations;
};
``` | /content/code_sandbox/Source/NoteCanvas.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,131 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Chorder.h
// modularSynth
//
// Created by Ryan Challinor on 12/2/12.
//
//
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Checkbox.h"
#include "UIGrid.h"
#include "DropdownList.h"
#include "Scale.h"
#define TOTAL_NUM_NOTES 128
class Chorder : public NoteEffectBase, public IDrawableModule, public UIGridListener, public IDropdownListener, public IScaleListener
{
public:
Chorder();
virtual ~Chorder();
static IDrawableModule* Create() { return new Chorder(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void AddTone(int tone, float velocity = 1);
void RemoveTone(int tone);
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void DropdownUpdated(DropdownList* dropdown, int oldVal, double time) override;
void OnScaleChanged() override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
virtual bool IsEnabled() const override { return mEnabled; }
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
{
width = 135;
height = 75;
}
void OnClicked(float x, float y, bool right) override;
void MouseReleased() override;
bool MouseMoved(float x, float y) override;
void PlayChorderNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation);
void CheckLeftovers();
UIGrid* mChordGrid{ nullptr };
int mVelocity{ 0 };
bool mInputNotes[TOTAL_NUM_NOTES]{};
int mHeldCount[TOTAL_NUM_NOTES]{};
bool mDiatonic{ false };
int mChordIndex{ 0 };
int mInversion{ 0 };
Checkbox* mDiatonicCheckbox{ nullptr };
DropdownList* mChordDropdown{ nullptr };
DropdownList* mInversionDropdown{ nullptr };
};
``` | /content/code_sandbox/Source/Chorder.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 721 |
```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
**/
//
// ModulationVisualizer.h
// Bespoke
//
// Created by Ryan Challinor on 12/27/15.
//
//
#pragma once
#include "IDrawableModule.h"
#include "NoteEffectBase.h"
struct ModulationParameters;
class ModulationVisualizer : public NoteEffectBase, public IDrawableModule
{
public:
ModulationVisualizer();
static IDrawableModule* Create() { return new ModulationVisualizer(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
//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 IsResizable() const override { return true; }
void Resize(float w, float h) override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
struct VizVoice
{
std::string GetInfoString();
bool mActive{ false };
ModulationParameters mModulators;
};
float mWidth{ 350 };
float mHeight{ 100 };
VizVoice mGlobalModulation;
std::vector<VizVoice> mVoices;
};
``` | /content/code_sandbox/Source/ModulationVisualizer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 446 |
```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
**/
/*
==============================================================================
PitchToCV.h
Created: 28 Nov 2017 9:44:14pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "INoteReceiver.h"
#include "IModulator.h"
#include "Slider.h"
class PatchCableSource;
class PitchToCV : public IDrawableModule, public INoteReceiver, public IModulator, public IFloatSliderListener
{
public:
PitchToCV();
virtual ~PitchToCV();
static IDrawableModule* Create() { return new PitchToCV(); }
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;
}
float mPitch{ 0 };
ModulationChain* mPitchBend{ nullptr };
};
``` | /content/code_sandbox/Source/PitchToCV.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 549 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// SeaOfGrain.cpp
// Bespoke
//
// Created by Ryan Challinor on 11/8/14.
//
//
#include "SeaOfGrain.h"
#include "IAudioReceiver.h"
#include "Sample.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "ModulationChain.h"
#include "juce_audio_formats/juce_audio_formats.h"
#include "juce_gui_basics/juce_gui_basics.h"
const float mBufferX = 5;
const float mBufferY = 100;
const float mBufferW = 800;
const float mBufferH = 200;
SeaOfGrain::SeaOfGrain()
: IAudioProcessor(gBufferSize)
, mRecordBuffer(10 * gSampleRate)
{
mSample = new Sample();
for (int i = 0; i < kNumMPEVoices; ++i)
mMPEVoices[i].mOwner = this;
for (int i = 0; i < kNumManualVoices; ++i)
mManualVoices[i].mOwner = this;
}
void SeaOfGrain::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mLoadButton = new ClickButton(this, "load", 5, 3);
mRecordInputCheckbox = new Checkbox(this, "record", 50, 3, &mRecordInput);
mVolumeSlider = new FloatSlider(this, "volume", 5, 20, 150, 15, &mVolume, 0, 2);
mDisplayOffsetSlider = new FloatSlider(this, "offset", 5, 40, 150, 15, &mDisplayOffset, 0, 10);
mDisplayLengthSlider = new FloatSlider(this, "display length", 5, 60, 150, 15, &mDisplayLength, 1, 10);
mKeyboardBasePitchSelector = new DropdownList(this, "keyboard base pitch", 5, 80, &mKeyboardBasePitch, 60);
mKeyboardNumPitchesSelector = new DropdownList(this, "keyboard num pitches", mKeyboardBasePitchSelector, kAnchor_Right, &mKeyboardNumPitches);
mKeyboardBasePitchSelector->AddLabel("0", 0);
mKeyboardBasePitchSelector->AddLabel("12", 12);
mKeyboardBasePitchSelector->AddLabel("24", 24);
mKeyboardBasePitchSelector->AddLabel("36", 36);
mKeyboardBasePitchSelector->AddLabel("48", 48);
mKeyboardBasePitchSelector->AddLabel("60", 60);
mKeyboardNumPitchesSelector->AddLabel("12", 12);
mKeyboardNumPitchesSelector->AddLabel("24", 24);
mKeyboardNumPitchesSelector->AddLabel("36", 36);
mKeyboardNumPitchesSelector->AddLabel("48", 48);
mKeyboardNumPitchesSelector->AddLabel("60", 60);
for (int i = 0; i < kNumManualVoices; ++i)
{
float x = 10 + i * 130;
mManualVoices[i].mGainSlider = new FloatSlider(this, ("gain " + ofToString(i + 1)).c_str(), x, mBufferY + mBufferH + 12, 120, 15, &mManualVoices[i].mGain, 0, 1);
mManualVoices[i].mPositionSlider = new FloatSlider(this, ("pos " + ofToString(i + 1)).c_str(), mManualVoices[i].mGainSlider, kAnchor_Below, 120, 15, &mManualVoices[i].mPosition, 0, 1);
mManualVoices[i].mOverlapSlider = new FloatSlider(this, ("overlap " + ofToString(i + 1)).c_str(), mManualVoices[i].mPositionSlider, kAnchor_Below, 120, 15, &mManualVoices[i].mGranulator.mGrainOverlap, .25, MAX_GRAINS);
mManualVoices[i].mSpeedSlider = new FloatSlider(this, ("speed " + ofToString(i + 1)).c_str(), mManualVoices[i].mOverlapSlider, kAnchor_Below, 120, 15, &mManualVoices[i].mGranulator.mSpeed, -3, 3);
mManualVoices[i].mLengthMsSlider = new FloatSlider(this, ("len ms " + ofToString(i + 1)).c_str(), mManualVoices[i].mSpeedSlider, kAnchor_Below, 120, 15, &mManualVoices[i].mGranulator.mGrainLengthMs, 1, 1000);
mManualVoices[i].mPosRandomizeSlider = new FloatSlider(this, ("pos r " + ofToString(i + 1)).c_str(), mManualVoices[i].mLengthMsSlider, kAnchor_Below, 120, 15, &mManualVoices[i].mGranulator.mPosRandomizeMs, 0, 200);
mManualVoices[i].mSpeedRandomizeSlider = new FloatSlider(this, ("speed r " + ofToString(i + 1)).c_str(), mManualVoices[i].mPosRandomizeSlider, kAnchor_Below, 120, 15, &mManualVoices[i].mGranulator.mSpeedRandomize, 0, .3f);
mManualVoices[i].mSpacingRandomizeSlider = new FloatSlider(this, ("spacing r " + ofToString(i + 1)).c_str(), mManualVoices[i].mSpeedRandomizeSlider, kAnchor_Below, 120, 15, &mManualVoices[i].mGranulator.mSpacingRandomize, 0, 1);
mManualVoices[i].mOctaveCheckbox = new Checkbox(this, ("octaves " + ofToString(i + 1)).c_str(), mManualVoices[i].mSpacingRandomizeSlider, kAnchor_Below, &mManualVoices[i].mGranulator.mOctaves);
mManualVoices[i].mWidthSlider = new FloatSlider(this, ("width " + ofToString(i + 1)).c_str(), mManualVoices[i].mOctaveCheckbox, kAnchor_Below, 120, 15, &mManualVoices[i].mGranulator.mWidth, 0, 1);
mManualVoices[i].mPanSlider = new FloatSlider(this, ("pan " + ofToString(i + 1)).c_str(), mManualVoices[i].mWidthSlider, kAnchor_Below, 120, 15, &mManualVoices[i].mPan, -1, 1);
}
}
SeaOfGrain::~SeaOfGrain()
{
delete mSample;
}
void SeaOfGrain::Poll()
{
}
void SeaOfGrain::Process(double time)
{
PROFILER(SeaOfGrain);
IAudioReceiver* target = GetTarget();
if (target == nullptr || (mSample == nullptr && !mHasRecordedInput) || mLoading)
return;
if (!mEnabled)
{
SyncBuffers();
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
{
Add(target->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize());
GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize(), ch);
}
GetBuffer()->Reset();
return;
}
ComputeSliders(0);
int numChannels = 2;
SyncBuffers(numChannels);
mRecordBuffer.SetNumChannels(GetBuffer()->NumActiveChannels());
int bufferSize = target->GetBuffer()->BufferSize();
ChannelBuffer* out = target->GetBuffer();
assert(bufferSize == gBufferSize);
if (mRecordInput)
{
for (int ch = 0; ch < numChannels; ++ch)
mRecordBuffer.WriteChunk(GetBuffer()->GetChannel(ch), bufferSize, ch);
}
gWorkChannelBuffer.SetNumActiveChannels(numChannels);
gWorkChannelBuffer.Clear();
for (int i = 0; i < kNumMPEVoices; ++i)
mMPEVoices[i].Process(&gWorkChannelBuffer, bufferSize);
for (int i = 0; i < kNumManualVoices; ++i)
mManualVoices[i].Process(&gWorkChannelBuffer, bufferSize);
for (int ch = 0; ch < numChannels; ++ch)
{
Mult(gWorkChannelBuffer.GetChannel(ch), mVolume, bufferSize);
GetVizBuffer()->WriteChunk(gWorkChannelBuffer.GetChannel(ch), bufferSize, ch);
Add(out->GetChannel(ch), gWorkChannelBuffer.GetChannel(ch), bufferSize);
}
GetBuffer()->Reset();
}
void SeaOfGrain::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mLoadButton->Draw();
mRecordInputCheckbox->Draw();
mVolumeSlider->Draw();
mDisplayOffsetSlider->Draw();
mDisplayLengthSlider->Draw();
mKeyboardBasePitchSelector->Draw();
mKeyboardNumPitchesSelector->Draw();
for (int i = 0; i < kNumManualVoices; ++i)
{
mManualVoices[i].mGainSlider->Draw();
mManualVoices[i].mPositionSlider->Draw();
mManualVoices[i].mOverlapSlider->Draw();
mManualVoices[i].mSpeedSlider->Draw();
mManualVoices[i].mLengthMsSlider->Draw();
mManualVoices[i].mPosRandomizeSlider->Draw();
mManualVoices[i].mSpeedRandomizeSlider->Draw();
mManualVoices[i].mSpacingRandomizeSlider->Draw();
mManualVoices[i].mOctaveCheckbox->Draw();
mManualVoices[i].mWidthSlider->Draw();
mManualVoices[i].mPanSlider->Draw();
}
if (mSample || mHasRecordedInput)
{
ofPushMatrix();
ofTranslate(mBufferX, mBufferY);
ofPushStyle();
if (mHasRecordedInput)
{
mRecordBuffer.Draw(0, 0, mBufferW, mBufferH, mDisplayLength * gSampleRate);
}
else
{
mSample->LockDataMutex(true);
DrawAudioBuffer(mBufferW, mBufferH, mSample->Data(), mDisplayStartSamples, mDisplayEndSamples, 0);
DrawTextNormal(std::string(mSample->Name()), 5, 10);
mSample->LockDataMutex(false);
}
ofPushStyle();
ofFill();
for (int i = 0; i < mKeyboardNumPitches; ++i)
{
ofSetColor(i % 2 * 200, 200, 0);
ofRect(mBufferW * float(i) / mKeyboardNumPitches, mBufferH, mBufferW / mKeyboardNumPitches, 10);
}
ofPopStyle();
for (int i = 0; i < kNumMPEVoices; ++i)
mMPEVoices[i].Draw(mBufferW, mBufferH);
for (int i = 0; i < kNumManualVoices; ++i)
mManualVoices[i].Draw(mBufferW, mBufferH);
ofPopStyle();
ofPopMatrix();
}
}
ChannelBuffer* SeaOfGrain::GetSourceBuffer()
{
if (mHasRecordedInput)
return mRecordBuffer.GetRawBuffer();
else
return mSample->Data();
}
float SeaOfGrain::GetSourceStartSample()
{
if (mHasRecordedInput)
return -mDisplayLength * gSampleRate;
else
return mDisplayStartSamples;
}
float SeaOfGrain::GetSourceEndSample()
{
if (mHasRecordedInput)
return 0;
else
return mDisplayEndSamples;
}
float SeaOfGrain::GetSourceBufferOffset()
{
if (mHasRecordedInput)
return mRecordBuffer.GetRawBufferOffset(0);
else
return 0;
}
void SeaOfGrain::FilesDropped(std::vector<std::string> files, int x, int y)
{
mLoading = true;
mSample->Reset();
mSample->Read(files[0].c_str());
UpdateSample();
mRecordInput = false;
mHasRecordedInput = false;
mLoading = false;
}
void SeaOfGrain::SampleDropped(int x, int y, Sample* sample)
{
mLoading = true;
mSample->CopyFrom(sample);
UpdateSample();
mRecordInput = false;
mHasRecordedInput = false;
mLoading = false;
}
void SeaOfGrain::DropdownClicked(DropdownList* list)
{
}
void SeaOfGrain::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void SeaOfGrain::UpdateSample()
{
float sampleLengthSeconds = mSample->LengthInSamples() / mSample->GetSampleRateRatio() / gSampleRate;
mDisplayLength = MIN(mDisplayLength, MIN(10, sampleLengthSeconds));
mDisplayLengthSlider->SetExtents(0, sampleLengthSeconds);
UpdateDisplaySamples();
}
void SeaOfGrain::UpdateDisplaySamples()
{
float ratio = 1;
if (!mHasRecordedInput)
ratio = mSample->GetSampleRateRatio();
mDisplayStartSamples = mDisplayOffset * gSampleRate * ratio;
mDisplayEndSamples = mDisplayLength * gSampleRate * ratio + mDisplayStartSamples;
}
void SeaOfGrain::LoadFile()
{
using namespace juce;
auto file_pattern = TheSynth->GetAudioFormatManager().getWildcardForAllFormats();
if (File::areFileNamesCaseSensitive())
file_pattern += ";" + file_pattern.toUpperCase();
FileChooser chooser("Load sample", File(ofToDataPath("samples")),
file_pattern, true, false, TheSynth->GetFileChooserParent());
if (chooser.browseForFileToOpen())
{
auto file = chooser.getResult();
std::vector<std::string> fileArray;
fileArray.push_back(file.getFullPathName().toStdString());
FilesDropped(fileArray, 0, 0);
}
}
void SeaOfGrain::ButtonClicked(ClickButton* button, double time)
{
if (button == mLoadButton)
LoadFile();
}
void SeaOfGrain::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
}
void SeaOfGrain::MouseReleased()
{
IDrawableModule::MouseReleased();
}
bool SeaOfGrain::MouseMoved(float x, float y)
{
return IDrawableModule::MouseMoved(x, y);
}
void SeaOfGrain::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mRecordInputCheckbox)
{
if (mRecordInput)
{
mHasRecordedInput = true;
mDisplayLength = mRecordBuffer.Size() / gSampleRate;
}
}
}
void SeaOfGrain::GetModuleDimensions(float& width, float& height)
{
width = mBufferW + 10;
height = mBufferY + mBufferH + 202;
}
void SeaOfGrain::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mDisplayOffsetSlider || slider == mDisplayLengthSlider)
UpdateDisplaySamples();
}
void SeaOfGrain::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void SeaOfGrain::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (voiceIdx == -1 || voiceIdx >= kNumMPEVoices)
return;
if (velocity > 0)
mMPEVoices[voiceIdx].mADSR.Start(time, 1);
else
mMPEVoices[voiceIdx].mADSR.Stop(time);
mMPEVoices[voiceIdx].mPitch = pitch;
mMPEVoices[voiceIdx].mPlay = 0;
mMPEVoices[voiceIdx].mPitchBend = modulation.pitchBend;
mMPEVoices[voiceIdx].mPressure = modulation.pressure;
mMPEVoices[voiceIdx].mModWheel = modulation.modWheel;
}
void SeaOfGrain::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void SeaOfGrain::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
}
void SeaOfGrain::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
out << mHasRecordedInput;
if (mHasRecordedInput)
mRecordBuffer.SaveState(out);
else
mSample->SaveState(out);
}
void SeaOfGrain::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
mHasRecordedInput = false;
if (rev > 0)
in >> mHasRecordedInput;
if (mHasRecordedInput)
{
mRecordBuffer.LoadState(in);
}
else
{
mSample->LoadState(in);
UpdateSample();
}
}
SeaOfGrain::GrainMPEVoice::GrainMPEVoice()
{
mGranulator.mGrainLengthMs = 150;
}
void SeaOfGrain::GrainMPEVoice::Process(ChannelBuffer* output, int bufferSize)
{
if (!mADSR.IsDone(gTime) && mOwner->GetSourceBuffer()->BufferSize() > 0)
{
double time = gTime;
for (int i = 0; i < bufferSize; ++i)
{
float pitchBend = mPitchBend ? mPitchBend->GetValue(i) : ModulationParameters::kDefaultPitchBend;
float pressure = mPressure ? mPressure->GetValue(i) : ModulationParameters::kDefaultPressure;
float modwheel = mModWheel ? mModWheel->GetValue(i) : ModulationParameters::kDefaultModWheel;
if (pressure > 0)
{
mGranulator.mGrainOverlap = ofMap(pressure * pressure, 0, 1, 3, MAX_GRAINS);
mGranulator.mPosRandomizeMs = ofMap(pressure * pressure, 0, 1, 100, .03f);
}
mGranulator.mGrainLengthMs = ofMap(modwheel, -1, 1, 10, 700);
float blend = .0005f;
mGain = mGain * (1 - blend) + pressure * blend;
float outSample[ChannelBuffer::kMaxNumChannels];
Clear(outSample, ChannelBuffer::kMaxNumChannels);
float pos = (mPitch + pitchBend + MIN(.125f, mPlay) - mOwner->mKeyboardBasePitch) / mOwner->mKeyboardNumPitches;
mGranulator.ProcessFrame(time, mOwner->GetSourceBuffer(), mOwner->GetSourceBuffer()->BufferSize(), ofLerp(mOwner->GetSourceStartSample(), mOwner->GetSourceEndSample(), pos) + mOwner->GetSourceBufferOffset(), outSample);
for (int ch = 0; ch < output->NumActiveChannels(); ++ch)
output->GetChannel(ch)[i] += outSample[ch] * sqrtf(mGain) * mADSR.Value(time);
time += gInvSampleRateMs;
mPlay += .001f;
}
}
else
{
mGranulator.ClearGrains();
}
}
void SeaOfGrain::GrainMPEVoice::Draw(float w, float h)
{
if (!mADSR.IsDone(gTime))
{
if (mPitch - mOwner->mKeyboardBasePitch >= 0 && mPitch - mOwner->mKeyboardBasePitch < mOwner->mKeyboardNumPitches)
{
float pitchBend = mPitchBend ? mPitchBend->GetValue(0) : 0;
float pressure = mPressure ? mPressure->GetValue(0) : 0;
ofPushStyle();
ofFill();
float keyX = (mPitch - mOwner->mKeyboardBasePitch) / mOwner->mKeyboardNumPitches * w;
float keyXTop = keyX + pitchBend * w / mOwner->mKeyboardNumPitches;
ofBeginShape();
ofVertex(keyX, h);
ofVertex(keyXTop, h - pressure * h);
ofVertex(keyXTop + 10, h - pressure * h);
ofVertex(keyX + 10, h);
ofEndShape();
ofPopStyle();
}
mGranulator.Draw(0, 0, w, h, mOwner->GetSourceStartSample() + mOwner->GetSourceBufferOffset(), mOwner->GetSourceEndSample() - mOwner->GetSourceStartSample(), mOwner->GetSourceBuffer()->BufferSize());
}
}
SeaOfGrain::GrainManualVoice::GrainManualVoice()
{
mGranulator.mGrainLengthMs = 150;
}
void SeaOfGrain::GrainManualVoice::Process(ChannelBuffer* output, int bufferSize)
{
if (mGain > 0 && mOwner->GetSourceBuffer()->BufferSize() > 0)
{
double time = gTime;
float panLeft = GetLeftPanGain(mPan);
float panRight = GetRightPanGain(mPan);
for (int i = 0; i < bufferSize; ++i)
{
float outSample[ChannelBuffer::kMaxNumChannels];
Clear(outSample, ChannelBuffer::kMaxNumChannels);
mGranulator.ProcessFrame(time, mOwner->GetSourceBuffer(), mOwner->GetSourceBuffer()->BufferSize(), ofLerp(mOwner->GetSourceStartSample(), mOwner->GetSourceEndSample(), mPosition) + mOwner->GetSourceBufferOffset(), outSample);
for (int ch = 0; ch < output->NumActiveChannels(); ++ch)
output->GetChannel(ch)[i] += outSample[ch] * mGain * (ch == 0 ? panLeft : panRight);
time += gInvSampleRateMs;
}
}
else
{
mGranulator.ClearGrains();
}
}
void SeaOfGrain::GrainManualVoice::Draw(float w, float h)
{
if (mGain > 0)
{
ofPushStyle();
ofFill();
float x = mPosition * w;
float y = h - mGain * h;
ofLine(x, y, x, h);
ofRect(x - 5, y - 5, 10, 10);
ofPopStyle();
mGranulator.Draw(0, 0, w, h, mOwner->GetSourceStartSample() + mOwner->GetSourceBufferOffset(), mOwner->GetSourceEndSample() - mOwner->GetSourceStartSample(), mOwner->GetSourceBuffer()->BufferSize());
}
}
``` | /content/code_sandbox/Source/SeaOfGrain.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 5,251 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// EQEffect.cpp
// Bespoke
//
// Created by Ryan Challinor on 12/26/14.
//
//
#include "EQEffect.h"
#include "SynthGlobals.h"
#include "FloatSliderLFOControl.h"
#include "Profiler.h"
#include "ModularSynth.h"
EQEffect::EQEffect()
{
for (int ch = 0; ch < ChannelBuffer::kMaxNumChannels; ++ch)
{
for (int i = 0; i < NUM_EQ_FILTERS; ++i)
{
mBanks[ch].mBiquad[i].SetFilterType(kFilterType_Peak);
mBanks[ch].mBiquad[i].SetFilterParams(40 * powf(2.2f, i), .1f);
}
}
}
void EQEffect::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mMultiSlider = new UIGrid("uigrid", 5, 25, 80, 50, NUM_EQ_FILTERS, 1, this);
mEvenButton = new ClickButton(this, "even", 5, 5);
mMultiSlider->SetGridMode(UIGrid::kMultislider);
for (int i = 0; i < NUM_EQ_FILTERS; ++i)
mMultiSlider->SetVal(i, 0, .5f);
mMultiSlider->SetListener(this);
}
EQEffect::~EQEffect()
{
}
void EQEffect::Init()
{
IDrawableModule::Init();
}
void EQEffect::ProcessAudio(double time, ChannelBuffer* buffer)
{
PROFILER(EQEffect);
if (!mEnabled)
return;
float bufferSize = buffer->BufferSize();
ComputeSliders(0);
for (int ch = 0; ch < buffer->NumActiveChannels(); ++ch)
{
for (int i = 0; i < mNumFilters; ++i)
mBanks[ch].mBiquad[i].Filter(buffer->GetChannel(ch), bufferSize);
}
}
void EQEffect::DrawModule()
{
mMultiSlider->Draw();
mEvenButton->Draw();
}
void EQEffect::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
mMultiSlider->TestClick(x, y, right);
}
void EQEffect::MouseReleased()
{
IDrawableModule::MouseReleased();
mMultiSlider->MouseReleased();
}
bool EQEffect::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
mMultiSlider->NotifyMouseMoved(x, y);
return false;
}
float EQEffect::GetEffectAmount()
{
if (mEnabled)
{
float amount = 0;
for (int i = 0; i < mNumFilters; ++i)
{
amount += fabsf(mMultiSlider->GetVal(i, 0) - .5f);
}
return amount;
}
return 0;
}
void EQEffect::GetModuleDimensions(float& width, float& height)
{
width = 90;
height = 80;
}
void EQEffect::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void EQEffect::RadioButtonUpdated(RadioButton* list, int oldVal, double time)
{
}
void EQEffect::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
for (int ch = 0; ch < ChannelBuffer::kMaxNumChannels; ++ch)
{
for (int i = 0; i < NUM_EQ_FILTERS; ++i)
mBanks[ch].mBiquad[i].Clear();
}
}
}
void EQEffect::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
}
void EQEffect::ButtonClicked(ClickButton* button, double time)
{
if (button == mEvenButton)
{
for (int ch = 0; ch < ChannelBuffer::kMaxNumChannels; ++ch)
{
for (int i = 0; i < NUM_EQ_FILTERS; ++i)
{
mMultiSlider->SetVal(i, 0, .5f);
mBanks[ch].mBiquad[i].mDbGain = 0;
if (ch == 0)
mBanks[0].mBiquad[i].UpdateFilterCoeff();
else
mBanks[ch].mBiquad[i].CopyCoeffFrom(mBanks[0].mBiquad[i]);
}
}
}
}
void EQEffect::GridUpdated(UIGrid* grid, int col, int row, float value, float oldValue)
{
for (int ch = 0; ch < ChannelBuffer::kMaxNumChannels; ++ch)
{
for (int i = 0; i < mNumFilters; ++i)
{
mBanks[ch].mBiquad[i].mDbGain = ofMap(mMultiSlider->GetVal(i, 0), 0, 1, -12, 12);
if (ch == 0)
mBanks[0].mBiquad[i].UpdateFilterCoeff();
else
mBanks[ch].mBiquad[i].CopyCoeffFrom(mBanks[0].mBiquad[i]);
}
}
}
void EQEffect::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
mMultiSlider->SaveState(out);
}
void EQEffect::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 426)
return; //this was saved before we added versioning, bail out
LoadStateValidate(rev <= GetModuleSaveStateRev());
mMultiSlider->LoadState(in);
}
``` | /content/code_sandbox/Source/EQEffect.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,400 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
IModulator.cpp
Created: 16 Nov 2017 9:59:15pm
Author: Ryan Challinor
==============================================================================
*/
#include "IModulator.h"
#include "Slider.h"
#include "PatchCableSource.h"
#include "ModularSynth.h"
IModulator::IModulator()
{
}
IModulator::~IModulator()
{
TheSynth->RemoveExtraPoller(this);
}
void IModulator::OnModulatorRepatch()
{
bool wasEmpty = (mTargets[0].mUIControlTarget == nullptr);
for (size_t i = 0; i < mTargets.size(); ++i)
{
IUIControl* newTarget = nullptr;
if (mTargetCable != nullptr && i < mTargetCable->GetPatchCables().size())
newTarget = dynamic_cast<IUIControl*>(mTargetCable->GetPatchCables()[i]->GetTarget());
if (newTarget != mTargets[i].mUIControlTarget)
{
if (mTargets[i].mSliderTarget != nullptr && mTargets[i].mSliderTarget->GetModulator() == this)
mTargets[i].mSliderTarget->SetModulator(nullptr); //clear old target's pointer to this
if (i + 1 < mTargets.size() && newTarget == mTargets[i + 1].mUIControlTarget) //one got deleted, shift the rest down
{
for (; i < mTargets.size(); ++i)
{
if (i + 1 < mTargets.size())
{
mTargets[i].mUIControlTarget = mTargets[i + 1].mUIControlTarget;
mTargets[i].mSliderTarget = mTargets[i + 1].mSliderTarget;
}
else
{
mTargets[i].mUIControlTarget = nullptr;
mTargets[i].mSliderTarget = nullptr;
}
}
break;
}
mTargets[i].mUIControlTarget = newTarget;
mTargets[i].mSliderTarget = dynamic_cast<FloatSlider*>(mTargets[i].mUIControlTarget);
if (newTarget != nullptr)
{
if (mTargets[i].mSliderTarget != nullptr)
{
mTargets[i].mSliderTarget->SetModulator(this);
if (wasEmpty)
InitializeRange(mTargets[i].mSliderTarget->GetValue(), mTargets[i].mUIControlTarget->GetModulationRangeMin(), mTargets[i].mUIControlTarget->GetModulationRangeMax(), mTargets[i].mSliderTarget->GetMode());
}
else
{
if (wasEmpty)
InitializeRange(mTargets[i].mUIControlTarget->GetValue(), mTargets[i].mUIControlTarget->GetModulationRangeMin(), mTargets[i].mUIControlTarget->GetModulationRangeMax(), FloatSlider::kNormal);
}
}
else
{
if (i == 0)
{
if (mMinSlider)
mMinSlider->SetVar(&mDummyMin);
if (mMaxSlider)
mMaxSlider->SetVar(&mDummyMax);
}
}
}
}
TheSynth->RemoveExtraPoller(this);
//if (RequiresManualPolling())
TheSynth->AddExtraPoller(this);
}
void IModulator::Poll()
{
if (Active())
{
mLastPollValue = Value();
const float kBlendRate = -9.65784f;
float blend = exp2(kBlendRate / ofGetFrameRate()); //framerate-independent blend
mSmoothedValue = mSmoothedValue * blend + mLastPollValue * (1 - blend);
for (int i = 0; i < (int)mTargets.size(); ++i)
{
if (mTargets[i].RequiresManualPolling())
{
if (mTargets[i].mUIControlTarget->ModulatorUsesLiteralValue())
mTargets[i].mUIControlTarget->SetValue(mLastPollValue, NextBufferTime(false));
else
mTargets[i].mUIControlTarget->SetFromMidiCC(mLastPollValue, NextBufferTime(false), true);
}
}
}
}
float IModulator::GetRecentChange() const
{
return mLastPollValue - mSmoothedValue;
}
void IModulator::OnRemovedFrom(IUIControl* control)
{
if (mTargetCable)
{
auto& cables = mTargetCable->GetPatchCables();
for (size_t i = 0; i < mTargets.size(); ++i)
{
for (auto& cable : cables)
{
if (cable->GetTarget() == control && cable->GetTarget() == mTargets[i].mUIControlTarget)
{
mTargetCable->RemovePatchCable(cable);
break;
}
}
}
}
OnModulatorRepatch();
}
void IModulator::InitializeRange(float currentValue, float min, float max, FloatSlider::Mode sliderMode)
{
if (!TheSynth->IsLoadingState())
{
if (!TheSynth->IsLoadingModule())
{
if (InitializeWithZeroRange())
{
GetMin() = currentValue;
GetMax() = currentValue;
}
else
{
GetMin() = min;
GetMax() = max;
}
if (mMinSlider)
{
mMinSlider->SetExtents(min, max);
mMinSlider->SetMode(sliderMode);
}
if (mMaxSlider)
{
mMaxSlider->SetExtents(min, max);
mMaxSlider->SetMode(sliderMode);
}
}
}
if (mMinSlider)
mMinSlider->SetVar(&GetMin());
if (mMaxSlider)
mMaxSlider->SetVar(&GetMax());
}
int IModulator::GetNumTargets() const
{
int ret = 0;
for (int i = 0; i < (int)mTargets.size(); ++i)
{
if (mTargets[i].mUIControlTarget != nullptr)
++ret;
}
return ret;
}
``` | /content/code_sandbox/Source/IModulator.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,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
**/
//
// SeaOfGrain.h
// Bespoke
//
// Created by Ryan Challinor on 11/8/14.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "EnvOscillator.h"
#include "IDrawableModule.h"
#include "Checkbox.h"
#include "Slider.h"
#include "DropdownList.h"
#include "ClickButton.h"
#include "INoteReceiver.h"
#include "Granulator.h"
#include "ADSR.h"
class Sample;
class SeaOfGrain : public IAudioProcessor, public IDrawableModule, public IFloatSliderListener, public IIntSliderListener, public IDropdownListener, public IButtonListener, public INoteReceiver
{
public:
SeaOfGrain();
~SeaOfGrain();
static IDrawableModule* Create() { return new SeaOfGrain(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void SendCC(int control, int value, int voiceIdx = -1) override {}
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
//IDrawableModule
void FilesDropped(std::vector<std::string> files, int x, int y) override;
void SampleDropped(int x, int y, Sample* sample) override;
bool CanDropSample() const override { return true; }
void Poll() override;
//IClickable
void MouseReleased() override;
bool MouseMoved(float x, float y) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
//IFloatSliderListener
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
//IFloatSliderListener
void IntSliderUpdated(IntSlider* slider, int oldVal, double time) override;
//IDropdownListener
void DropdownClicked(DropdownList* list) override;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
//IButtonListener
void ButtonClicked(ClickButton* button, double time) override;
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 1; }
bool IsEnabled() const override { return mEnabled; }
private:
void UpdateSample();
void UpdateDisplaySamples();
void LoadFile();
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
void OnClicked(float x, float y, bool right) override;
ChannelBuffer* GetSourceBuffer();
float GetSourceStartSample();
float GetSourceEndSample();
float GetSourceBufferOffset();
struct GrainMPEVoice
{
GrainMPEVoice();
void Process(ChannelBuffer* output, int bufferSize);
void Draw(float w, float h);
float mPlay{ 0 };
float mPitch{ 0 };
ModulationChain* mPitchBend{ nullptr };
ModulationChain* mPressure{ nullptr };
ModulationChain* mModWheel{ nullptr };
float mGain{ 0 };
::ADSR mADSR{ 100, 0, 1, 100 };
Granulator mGranulator;
SeaOfGrain* mOwner{ nullptr };
};
struct GrainManualVoice
{
GrainManualVoice();
void Process(ChannelBuffer* output, int bufferSize);
void Draw(float w, float h);
float mGain{ 0 };
float mPosition{ 0 };
float mPan{ 0 };
Granulator mGranulator;
SeaOfGrain* mOwner{ nullptr };
FloatSlider* mGainSlider{ nullptr };
FloatSlider* mPositionSlider{ nullptr };
FloatSlider* mOverlapSlider{ nullptr };
FloatSlider* mSpeedSlider{ nullptr };
FloatSlider* mLengthMsSlider{ nullptr };
FloatSlider* mPosRandomizeSlider{ nullptr };
FloatSlider* mSpeedRandomizeSlider{ nullptr };
FloatSlider* mSpacingRandomizeSlider{ nullptr };
Checkbox* mOctaveCheckbox{ nullptr };
FloatSlider* mWidthSlider{ nullptr };
FloatSlider* mPanSlider{ nullptr };
};
static const int kNumMPEVoices = 16;
GrainMPEVoice mMPEVoices[kNumMPEVoices];
static const int kNumManualVoices = 6;
GrainManualVoice mManualVoices[kNumManualVoices];
Sample* mSample{ nullptr };
RollingBuffer mRecordBuffer;
ClickButton* mLoadButton{ nullptr };
bool mRecordInput{ false };
Checkbox* mRecordInputCheckbox{ nullptr };
bool mHasRecordedInput{ false };
float mVolume{ .6 };
FloatSlider* mVolumeSlider{ nullptr };
bool mLoading{ false };
FloatSlider* mDisplayOffsetSlider{ nullptr };
float mDisplayOffset{ 0 };
FloatSlider* mDisplayLengthSlider{ nullptr };
float mDisplayLength{ 10 };
int mDisplayStartSamples{ 0 };
int mDisplayEndSamples{ 0 };
DropdownList* mKeyboardBasePitchSelector{ nullptr };
int mKeyboardBasePitch{ 36 };
DropdownList* mKeyboardNumPitchesSelector{ nullptr };
int mKeyboardNumPitches{ 24 };
};
``` | /content/code_sandbox/Source/SeaOfGrain.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,365 |
```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
**/
//
// Monophonify.h
// modularSynth
//
// Created by Ryan Challinor on 12/12/12.
//
//
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Slider.h"
#include "ModulationChain.h"
#include "DropdownList.h"
class Monophonify : public NoteEffectBase, public IDrawableModule, public IFloatSliderListener, public IDropdownListener
{
public:
Monophonify();
static IDrawableModule* Create() { return new Monophonify(); }
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;
void DropdownUpdated(DropdownList* list, int oldVal, double time) override {}
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
int GetMostRecentCurrentlyHeldPitch() const;
double mHeldNotes[128];
int mInitialPitch{ -1 };
int mLastPlayedPitch{ -1 };
int mLastVelocity{ 0 };
float mWidth{ 200 };
float mHeight{ 20 };
int mVoiceIdx{ 0 };
enum class PortamentoMode
{
kAlways,
kRetriggerHeld,
kBendHeld
};
PortamentoMode mPortamentoMode{ PortamentoMode::kAlways };
DropdownList* mPortamentoModeSelector{ nullptr };
float mGlideTime{ 0 };
FloatSlider* mGlideSlider{ nullptr };
ModulationChain mPitchBend{ ModulationParameters::kDefaultPitchBend };
};
``` | /content/code_sandbox/Source/Monophonify.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 627 |
```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
**/
//
// Kicker.h
// modularSynth
//
// Created by Ryan Challinor on 3/7/13.
//
//
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Checkbox.h"
class DrumPlayer;
class Kicker : public NoteEffectBase, public IDrawableModule
{
public:
Kicker();
static IDrawableModule* Create() { return new Kicker(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void SetDrumPlayer(DrumPlayer* drumPlayer) { mDrumPlayer = drumPlayer; }
//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;
}
DrumPlayer* mDrumPlayer{ nullptr };
};
``` | /content/code_sandbox/Source/Kicker.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 420 |
```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
**/
//
// InputChannel.h
// modularSynth
//
// Created by Ryan Challinor on 12/16/12.
//
//
#pragma once
#include <iostream>
#include "IAudioProcessor.h"
#include "IDrawableModule.h"
#include "DropdownList.h"
class InputChannel : public IAudioProcessor, public IDrawableModule, public IDropdownListener
{
public:
InputChannel();
virtual ~InputChannel();
static IDrawableModule* Create() { return new InputChannel(); }
static bool AcceptsAudio() { return true; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//IAudioReceiver
InputMode GetInputMode() override { return mChannelSelectionIndex < mStereoSelectionOffset ? kInputMode_Mono : kInputMode_Multichannel; }
//IAudioSource
void Process(double time) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
void DropdownUpdated(DropdownList* list, int oldVal, double time) override {}
virtual void LoadLayout(const ofxJSONElement& moduleInfo) override;
virtual void SetUpFromSaveData() override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 64;
height = 20;
}
DropdownList* mChannelSelector{ nullptr };
int mChannelSelectionIndex{ 0 };
int mStereoSelectionOffset{ 0 };
};
``` | /content/code_sandbox/Source/InputChannel.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 456 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// Lissajous.cpp
// Bespoke
//
// Created by Ryan Challinor on 6/26/14.
//
//
#include "Lissajous.h"
#include "ModularSynth.h"
#include "Profiler.h"
Lissajous::Lissajous()
: IAudioProcessor(gBufferSize)
{
for (int i = 0; i < NUM_LISSAJOUS_POINTS; ++i)
mLissajousPoints[i].set(0, 0);
}
Lissajous::~Lissajous()
{
}
void Lissajous::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mScaleSlider = new FloatSlider(this, "scale", 0, 0, 100, 15, &mScale, .5f, 4);
}
void Lissajous::Process(double time)
{
PROFILER(Lissajous);
SyncBuffers();
int bufferSize = GetBuffer()->BufferSize();
IAudioReceiver* target = GetTarget();
if (target)
{
for (int ch = 0; ch < GetBuffer()->NumActiveChannels(); ++ch)
{
Add(target->GetBuffer()->GetChannel(ch), GetBuffer()->GetChannel(ch), bufferSize);
GetVizBuffer()->WriteChunk(GetBuffer()->GetChannel(ch), GetBuffer()->BufferSize(), ch);
}
}
if (mEnabled)
{
mOnlyHasOneChannel = (GetBuffer()->NumActiveChannels() == 1);
int secondChannel = mOnlyHasOneChannel ? 0 : 1;
for (int i = 0; i < bufferSize; ++i)
mLissajousPoints[(mOffset + i) % NUM_LISSAJOUS_POINTS].set(GetBuffer()->GetChannel(0)[i], GetBuffer()->GetChannel(secondChannel)[i]);
mOffset += bufferSize;
mOffset %= NUM_LISSAJOUS_POINTS;
}
GetBuffer()->Reset();
}
void Lissajous::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mScaleSlider->Draw();
if (!mEnabled)
return;
ofPushStyle();
ofPushMatrix();
ofSetLineWidth(2);
float w, h;
GetDimensions(w, h);
ofBeginShape();
const int autocorrelationDelay = 90;
ofSetColor(0, 255, 0, 30);
for (int i = mOffset; i < NUM_LISSAJOUS_POINTS + mOffset - autocorrelationDelay; ++i)
{
float x = w / 2 + mLissajousPoints[i % NUM_LISSAJOUS_POINTS].x * w * mScale;
float y;
if (mAutocorrelationMode || mOnlyHasOneChannel)
y = h / 2 + mLissajousPoints[(i + autocorrelationDelay) % NUM_LISSAJOUS_POINTS].x * h * mScale;
else
y = h / 2 + mLissajousPoints[i % NUM_LISSAJOUS_POINTS].y * h * mScale;
//float alpha = (i-mOffset)/float(NUM_LISSAJOUS_POINTS-autocorrelationDelay);
ofVertex(x, y);
}
ofEndShape();
ofPopMatrix();
ofPopStyle();
}
void Lissajous::Resize(float w, float h)
{
mWidth = w;
mHeight = h;
}
void Lissajous::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadFloat("width", moduleInfo, 500);
mModuleSaveData.LoadFloat("height", moduleInfo, 500);
mModuleSaveData.LoadBool("autocorrelation", moduleInfo, true);
SetUpFromSaveData();
}
void Lissajous::SaveLayout(ofxJSONElement& moduleInfo)
{
moduleInfo["width"] = mWidth;
moduleInfo["height"] = mHeight;
moduleInfo["autocorrelation"] = mAutocorrelationMode;
}
void Lissajous::SetUpFromSaveData()
{
SetTarget(TheSynth->FindModule(mModuleSaveData.GetString("target")));
mWidth = mModuleSaveData.GetFloat("width");
mHeight = mModuleSaveData.GetFloat("height");
mAutocorrelationMode = mModuleSaveData.GetBool("autocorrelation");
}
``` | /content/code_sandbox/Source/Lissajous.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,070 |
```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
**/
//
// TimerDisplay.h
// Bespoke
//
// Created by Ryan Challinor on 7/2/14.
//
//
#pragma once
#include <iostream>
#include "IDrawableModule.h"
#include "OpenFrameworksPort.h"
#include "ClickButton.h"
class TimerDisplay : public IDrawableModule, public IButtonListener
{
public:
TimerDisplay();
~TimerDisplay();
static IDrawableModule* Create() { return new TimerDisplay(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return false; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
void ButtonClicked(ClickButton* button, double time) override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override
{
width = 150;
height = 56;
}
double mStartTime{ 0 };
ClickButton* mResetButton{ nullptr };
};
``` | /content/code_sandbox/Source/TimerDisplay.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 334 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
Sequencer.cpp
Created: 17 Oct 2018 9:38:05pm
Author: Ryan Challinor
==============================================================================
*/
#include "Pulser.h"
#include "OpenFrameworksPort.h"
#include "SynthGlobals.h"
#include "ModularSynth.h"
#include "Profiler.h"
#include "PatchCableSource.h"
Pulser::Pulser()
{
}
void Pulser::Init()
{
IDrawableModule::Init();
mTransportListenerInfo = TheTransport->AddListener(this, mInterval, OffsetInfo(0, true), true);
TheTransport->AddAudioPoller(this);
}
void Pulser::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mIntervalSelector = new DropdownList(this, "interval", 75, 2, (int*)(&mInterval));
mTimeModeSelector = new DropdownList(this, "timemode", 5, 2, (int*)(&mTimeMode));
mFreeTimeSlider = new FloatSlider(this, "t", 75, 2, 44, 15, &mFreeTimeStep, 10, 1000, 0);
mOffsetSlider = new FloatSlider(this, "offset", mTimeModeSelector, kAnchor_Below, 113, 15, &mOffset, -1, 1);
mRandomStepCheckbox = new Checkbox(this, "random", mOffsetSlider, kAnchor_Below, &mRandomStep);
mResetLengthSlider = new IntSlider(this, "reset", mRandomStepCheckbox, kAnchor_Below, 113, 15, &mResetLength, 1, 16);
mCustomDivisorSlider = new IntSlider(this, "div", mRandomStepCheckbox, kAnchor_Right, 52, 15, &mCustomDivisor, 1, 32);
mRestartFreeTimeButton = new ClickButton(this, "restart", mRandomStepCheckbox, kAnchor_Right);
mIntervalSelector->AddLabel("16", kInterval_16);
mIntervalSelector->AddLabel("8", kInterval_8);
mIntervalSelector->AddLabel("4", kInterval_4);
mIntervalSelector->AddLabel("3", kInterval_3);
mIntervalSelector->AddLabel("2", kInterval_2);
mIntervalSelector->AddLabel("1n", kInterval_1n);
mIntervalSelector->AddLabel("2n", kInterval_2n);
mIntervalSelector->AddLabel("4n", kInterval_4n);
mIntervalSelector->AddLabel("4nt", kInterval_4nt);
mIntervalSelector->AddLabel("8n", kInterval_8n);
mIntervalSelector->AddLabel("8nt", kInterval_8nt);
mIntervalSelector->AddLabel("16n", kInterval_16n);
mIntervalSelector->AddLabel("16nt", kInterval_16nt);
mIntervalSelector->AddLabel("32n", kInterval_32n);
mIntervalSelector->AddLabel("64n", kInterval_64n);
mIntervalSelector->AddLabel("none", kInterval_None);
mIntervalSelector->AddLabel("div", kInterval_CustomDivisor);
mTimeModeSelector->AddLabel("step", kTimeMode_Step);
mTimeModeSelector->AddLabel("reset", kTimeMode_Reset);
mTimeModeSelector->AddLabel("sync", kTimeMode_Sync);
mTimeModeSelector->AddLabel("align", kTimeMode_Align);
mTimeModeSelector->AddLabel("downbeat", kTimeMode_Downbeat);
mTimeModeSelector->AddLabel("dnbeat2", kTimeMode_Downbeat2);
mTimeModeSelector->AddLabel("dnbeat4", kTimeMode_Downbeat4);
mTimeModeSelector->AddLabel("free", kTimeMode_Free);
mFreeTimeSlider->SetMode(FloatSlider::kSquare);
mFreeTimeSlider->SetShowing(mTimeMode == kTimeMode_Free);
mRestartFreeTimeButton->SetShowing(mTimeMode == kTimeMode_Free);
}
Pulser::~Pulser()
{
TheTransport->RemoveListener(this);
TheTransport->RemoveAudioPoller(this);
}
void Pulser::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
ofSetColor(255, 255, 255, gModuleDrawAlpha);
mTimeModeSelector->Draw();
mIntervalSelector->Draw();
mFreeTimeSlider->Draw();
mOffsetSlider->Draw();
mRandomStepCheckbox->Draw();
mResetLengthSlider->Draw();
mCustomDivisorSlider->SetShowing(mIntervalSelector->IsShowing() && mInterval == kInterval_CustomDivisor);
mCustomDivisorSlider->Draw();
mRestartFreeTimeButton->Draw();
}
void Pulser::CheckboxUpdated(Checkbox* checkbox, double time)
{
if (checkbox == mEnabledCheckbox)
{
if (mEnabled && (mTimeMode == kTimeMode_Downbeat || mTimeMode == kTimeMode_Downbeat2 || mTimeMode == kTimeMode_Downbeat4))
mWaitingForDownbeat = true;
mFreeTimeCounter = mFreeTimeStep;
}
}
void Pulser::OnTransportAdvanced(float amount)
{
PROFILER(Pulser);
ComputeSliders(0);
if (mTimeMode == kTimeMode_Free)
{
float ms = amount * TheTransport->MsPerBar();
mFreeTimeCounter += ms;
if (mFreeTimeCounter > mFreeTimeStep)
{
OnTimeEvent(NextBufferTime(true) + (mFreeTimeCounter - mFreeTimeStep));
mFreeTimeCounter -= mFreeTimeStep;
}
}
}
void Pulser::OnTimeEvent(double time)
{
if (!mEnabled)
return;
float offsetMs = GetOffset() * TheTransport->MsPerBar();
int flags = 0;
bool shouldReset = false;
if (mTimeMode == kTimeMode_Downbeat)
shouldReset = TheTransport->GetQuantized(time, mTransportListenerInfo) == 0;
if (mTimeMode == kTimeMode_Downbeat2)
shouldReset = TheTransport->GetQuantized(time, mTransportListenerInfo) == 0 && TheTransport->GetMeasure(time + offsetMs) % 2 == 0;
if (mTimeMode == kTimeMode_Downbeat4)
shouldReset = TheTransport->GetQuantized(time, mTransportListenerInfo) == 0 && TheTransport->GetMeasure(time + offsetMs) % 4 == 0;
if (mTimeMode == kTimeMode_Reset)
{
int step = 0;
if (TheTransport->GetMeasureFraction(mInterval) < 1)
{
step = TheTransport->GetSyncedStep(time, this, mTransportListenerInfo);
}
else
{
int measure = TheTransport->GetMeasure(time);
step = measure / TheTransport->GetMeasureFraction(mInterval);
}
if (step % mResetLength == 0)
shouldReset = true;
}
if (shouldReset)
flags |= kPulseFlag_Reset;
if (mRandomStep)
flags |= kPulseFlag_Random;
if (mTimeMode == kTimeMode_Sync)
flags |= kPulseFlag_SyncToTransport;
if (mTimeMode == kTimeMode_Align)
flags |= kPulseFlag_Align;
if (mWaitingForDownbeat && shouldReset)
mWaitingForDownbeat = false;
if (mWaitingForDownbeat && (mTimeMode == kTimeMode_Downbeat || mTimeMode == kTimeMode_Downbeat2 || mTimeMode == kTimeMode_Downbeat4))
return;
DispatchPulse(GetPatchCableSource(), time, 1, flags);
}
void Pulser::GetModuleDimensions(float& width, float& height)
{
width = 121;
height = 52;
if (mTimeMode == kTimeMode_Reset)
height += 18;
}
void Pulser::ButtonClicked(ClickButton* button, double time)
{
if (button == mRestartFreeTimeButton)
mFreeTimeCounter = mFreeTimeStep;
}
float Pulser::GetOffset()
{
if (mInterval == kInterval_None)
return 0;
if (mInterval == kInterval_2)
return -mOffset * 2;
if (mInterval == kInterval_3)
return -mOffset * 3;
if (mInterval == kInterval_4)
return -mOffset * 4;
if (mInterval == kInterval_8)
return -mOffset * 8;
if (mInterval == kInterval_16)
return -mOffset * 16;
if (mInterval == kInterval_CustomDivisor)
return -mOffset / mCustomDivisor;
return (-mOffset / TheTransport->CountInStandardMeasure(mInterval));
}
void Pulser::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
if (list == mIntervalSelector)
{
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
{
transportListenerInfo->mInterval = mInterval;
transportListenerInfo->mOffsetInfo = OffsetInfo(GetOffset(), false);
}
}
if (list == mTimeModeSelector)
{
mIntervalSelector->SetShowing(mTimeMode != kTimeMode_Free);
mFreeTimeSlider->SetShowing(mTimeMode == kTimeMode_Free);
mRestartFreeTimeButton->SetShowing(mTimeMode == kTimeMode_Free);
if (mTimeMode == kTimeMode_Free)
{
if (mInterval < kInterval_None)
mFreeTimeStep = TheTransport->GetDuration(mInterval);
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
transportListenerInfo->mInterval = kInterval_None;
}
else if (oldVal == kTimeMode_Free)
{
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
{
transportListenerInfo->mInterval = mInterval;
transportListenerInfo->mOffsetInfo = OffsetInfo(GetOffset(), false);
}
}
mResetLengthSlider->SetShowing(mTimeMode == kTimeMode_Reset);
}
}
void Pulser::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
if (slider == mOffsetSlider)
{
if (mTimeMode != kTimeMode_Free)
{
TransportListenerInfo* transportListenerInfo = TheTransport->GetListenerInfo(this);
if (transportListenerInfo != nullptr)
{
transportListenerInfo->mInterval = mInterval;
transportListenerInfo->mOffsetInfo = OffsetInfo(GetOffset(), false);
}
}
}
}
void Pulser::IntSliderUpdated(IntSlider* slider, int oldVal, double time)
{
if (slider == mCustomDivisorSlider)
mTransportListenerInfo->mCustomDivisor = mCustomDivisor;
}
void Pulser::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void Pulser::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void Pulser::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/Pulser.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,634 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NoteStreamDisplay.cpp
Created: 21 May 2020 11:13:12pm
Author: Ryan Challinor
==============================================================================
*/
#include "NoteStreamDisplay.h"
#include "ModularSynth.h"
#include "SynthGlobals.h"
#include "UIControlMacros.h"
NoteStreamDisplay::NoteStreamDisplay()
{
}
void NoteStreamDisplay::CreateUIControls()
{
IDrawableModule::CreateUIControls();
UIBLOCK0();
BUTTON(mResetButton, "reset");
ENDUIBLOCK0();
}
void NoteStreamDisplay::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
int barLines = int(ceil(mDurationMs / TheTransport->MsPerBar()));
ofSetColor(150, 150, 150);
for (int i = 0; i < barLines; ++i)
{
double measureStartTime = gTime - TheTransport->MsPerBar() * (TheTransport->GetMeasurePos(gTime) + i);
float x = ofMap(gTime - measureStartTime, mDurationMs, 0, 0, mWidth);
ofLine(x, 0, x, mHeight);
}
ofFill();
if (mPitchMin <= mPitchMax)
{
float noteHeight = mHeight / (mPitchMax - mPitchMin + 1);
for (int i = 0; i < kNoteStreamCapacity; ++i)
{
if (IsElementActive(i))
{
float xStart = ofMap(gTime - mNoteStream[i].timeOn, mDurationMs, 0, 0, mWidth);
float xEnd;
if (mNoteStream[i].timeOff == -1)
xEnd = mWidth;
else
xEnd = ofMap(gTime - mNoteStream[i].timeOff, mDurationMs, 0, 0, mWidth);
float yStart = GetYPos(mNoteStream[i].pitch, noteHeight);
ofSetColor(0, ofMap(mNoteStream[i].velocity, 0, 127.0f, 50, 200), 0);
ofRect(xStart, yStart, xEnd - xStart, noteHeight, L(cornerRadius, 2));
ofSetColor(mNoteStream[i].velocity / 127.0f * 255, mNoteStream[i].velocity / 127.0f * 255, mNoteStream[i].velocity / 127.0f * 255);
ofRect(xStart, yStart, 3, noteHeight, L(cornerRadius, 2));
ofSetColor(0, 0, 0);
ofRect(xEnd - 3, yStart, 3, noteHeight, L(cornerRadius, 2));
}
}
ofSetColor(100, 100, 255);
bool* notes = mNoteOutput.GetNotes();
for (int i = mPitchMin; i <= mPitchMax; ++i)
{
if (notes[i])
ofRect(mWidth - 3, GetYPos(i, noteHeight), 3, noteHeight, L(cornerRadius, 2));
}
}
mResetButton->Draw();
}
void NoteStreamDisplay::DrawModuleUnclipped()
{
if (mDrawDebug)
{
DrawTextNormal(mDebugDisplayText, mWidth + 10, 0);
}
}
float NoteStreamDisplay::GetYPos(int pitch, float noteHeight) const
{
return ofMap(pitch, mPitchMin, mPitchMax + 1, mHeight - noteHeight, -noteHeight);
}
void NoteStreamDisplay::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
if (velocity > 0)
{
bool inserted = false;
double oldest = -1;
int oldestIndex = -1;
for (int i = 0; i < kNoteStreamCapacity; ++i)
{
if (!IsElementActive(i))
{
mNoteStream[i].pitch = pitch;
mNoteStream[i].velocity = velocity;
mNoteStream[i].timeOn = time;
mNoteStream[i].timeOff = -1;
inserted = true;
break;
}
else
{
if (mNoteStream[i].timeOn < oldest)
{
oldest = mNoteStream[i].timeOn;
oldestIndex = i;
}
}
}
if (!inserted && oldestIndex != -1)
{
mNoteStream[oldestIndex].pitch = pitch;
mNoteStream[oldestIndex].velocity = velocity;
mNoteStream[oldestIndex].timeOn = time;
mNoteStream[oldestIndex].timeOff = -1;
}
if (pitch < mPitchMin)
mPitchMin = pitch;
if (pitch > mPitchMax)
mPitchMax = pitch;
}
else
{
for (int i = 0; i < kNoteStreamCapacity; ++i)
{
if (mNoteStream[i].pitch == pitch &&
mNoteStream[i].timeOff == -1 &&
mNoteStream[i].timeOn < time)
mNoteStream[i].timeOff = time;
}
}
if (mDrawDebug)
AddDebugLine("PlayNote(" + ofToString(time / 1000) + ", " + ofToString(pitch) + ", " + ofToString(velocity) + ", " + ofToString(voiceIdx) + ")", 35);
}
bool NoteStreamDisplay::IsElementActive(int index) const
{
return mNoteStream[index].timeOn != -1 && (mNoteStream[index].timeOff == -1 || gTime - mNoteStream[index].timeOff < mDurationMs);
}
void NoteStreamDisplay::ButtonClicked(ClickButton* button, double time)
{
if (button == mResetButton)
{
mPitchMin = 127;
mPitchMax = 0;
for (int i = 0; i < kNoteStreamCapacity; ++i)
{
if (IsElementActive(i))
{
if (mNoteStream[i].pitch < mPitchMin)
mPitchMin = mNoteStream[i].pitch;
if (mNoteStream[i].pitch > mPitchMax)
mPitchMax = mNoteStream[i].pitch;
}
}
}
}
void NoteStreamDisplay::Resize(float w, float h)
{
mWidth = w;
mHeight = h;
}
void NoteStreamDisplay::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
mModuleSaveData.LoadFloat("duration_ms", moduleInfo, 2000, 0, 999999, K(isTextField));
mModuleSaveData.LoadInt("width", moduleInfo, 400, 50, 999999, K(isTextField));
mModuleSaveData.LoadInt("height", moduleInfo, 200, 50, 999999, K(isTextField));
SetUpFromSaveData();
}
void NoteStreamDisplay::SaveLayout(ofxJSONElement& moduleInfo)
{
moduleInfo["width"] = mWidth;
moduleInfo["height"] = mHeight;
}
void NoteStreamDisplay::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
mDurationMs = mModuleSaveData.GetFloat("duration_ms");
mWidth = mModuleSaveData.GetInt("width");
mHeight = mModuleSaveData.GetInt("height");
}
``` | /content/code_sandbox/Source/NoteStreamDisplay.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,763 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without 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.cpp
// Bespoke
//
// Created by Ryan Challinor on 5/19/16.
//
//
#include "FilterButterworth24db.h"
#include "SynthGlobals.h"
#include <math.h>
#define BUDDA_Q_SCALE 6.f
CFilterButterworth24db::CFilterButterworth24db(void)
{
SetSampleRate(gSampleRate);
Set(gSampleRate / 2, 0.0);
Clear();
}
CFilterButterworth24db::~CFilterButterworth24db(void)
{
}
void CFilterButterworth24db::Clear()
{
history1 = 0.f;
history2 = 0.f;
history3 = 0.f;
history4 = 0.f;
}
void CFilterButterworth24db::SetSampleRate(float fs)
{
float pi = 4.f * atanf(1.f);
t0 = 4.f * fs * fs;
t1 = 8.f * fs * fs;
t2 = 2.f * fs;
t3 = pi / fs;
min_cutoff = fs * 0.01f;
max_cutoff = fs * 0.45f;
}
void CFilterButterworth24db::Set(float cutoff, float q)
{
if (cutoff < min_cutoff)
cutoff = min_cutoff;
else if (cutoff > max_cutoff)
cutoff = max_cutoff;
if (q < 0.f)
q = 0.f;
else if (q > 1.f)
q = 1.f;
float wp = t2 * tanf(t3 * cutoff);
float bd, bd_tmp, b1, b2;
q *= BUDDA_Q_SCALE;
q += 1.f;
b1 = (0.765367f / q) / wp;
b2 = 1.f / (wp * wp);
bd_tmp = t0 * b2 + 1.f;
bd = 1.f / (bd_tmp + t2 * b1);
gain = bd * 0.5f;
coef2 = (2.f - t1 * b2);
coef0 = coef2 * bd;
coef1 = (bd_tmp - t2 * b1) * bd;
b1 = (1.847759f / q) / wp;
bd = 1.f / (bd_tmp + t2 * b1);
gain *= bd;
coef2 *= bd;
coef3 = (bd_tmp - t2 * b1) * bd;
}
float CFilterButterworth24db::Run(float input)
{
float output = input * gain;
float new_hist;
output -= history1 * coef0;
new_hist = output - history2 * coef1;
output = new_hist + history1 * 2.f;
output += history2;
history2 = history1;
history1 = new_hist;
output -= history3 * coef2;
new_hist = output - history4 * coef3;
output = new_hist + history3 * 2.f;
output += history4;
history4 = history3;
history3 = new_hist;
return output;
}
void CFilterButterworth24db::CopyCoeffFrom(CFilterButterworth24db& other)
{
coef0 = other.coef0;
coef1 = other.coef1;
coef2 = other.coef2;
coef3 = other.coef3;
gain = other.gain;
}
``` | /content/code_sandbox/Source/FilterButterworth24db.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 870 |
```objective-c
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// TextEntry.h
// modularSynth
//
// Created by Ryan Challinor on 12/5/12.
//
//
#pragma once
#include <iostream>
#include <climits>
#include "IUIControl.h"
#include "SynthGlobals.h"
class TextEntry;
class ITextEntryListener
{
public:
virtual ~ITextEntryListener() {}
virtual void TextEntryComplete(TextEntry* entry) = 0;
virtual void TextEntryCancelled(TextEntry* entry) {}
virtual void TextEntryActivated(TextEntry* entry) {}
};
enum TextEntryType
{
kTextEntry_Text,
kTextEntry_Int,
kTextEntry_Float
};
class TextEntry : public IUIControl, public IKeyboardFocusListener
{
public:
TextEntry(ITextEntryListener* owner, const char* name, int x, int y, int charWidth, char* var);
TextEntry(ITextEntryListener* owner, const char* name, int x, int y, int charWidth, std::string* var);
TextEntry(ITextEntryListener* owner, const char* name, int x, int y, int charWidth, int* var, int min, int max);
TextEntry(ITextEntryListener* owner, const char* name, int x, int y, int charWidth, float* var, float min, float max);
void OnKeyPressed(int key, bool isRepeat) override;
void Render() override;
void Delete() override;
void MakeActiveTextEntry(bool setCaretToEnd);
void RemoveSelectedText();
void SetNextTextEntry(TextEntry* entry);
void UpdateDisplayString();
void SetInErrorMode(bool error) { mInErrorMode = error; }
void DrawLabel(bool draw) { mDrawLabel = draw; }
void SetRequireEnter(bool require) { mRequireEnterToAccept = require; }
void SetFlexibleWidth(bool flex) { mFlexibleWidth = flex; }
void ClearInput();
const char* GetText() const { return mString; }
TextEntryType GetTextEntryType() const { return mType; }
void SetText(std::string text);
void GetDimensions(float& width, float& height) override;
//IUIControl
void SetFromMidiCC(float slider, double time, bool setViaModulator) override;
float GetValueForMidiCC(float slider) const override;
float GetMidiValue() const override;
void GetRange(float& min, float& max) override;
void SetValue(float value, double time, bool forceUpdate = false) override;
float GetValue() const override;
int GetNumValues() override;
std::string GetDisplayValue(float val) const override;
void Increment(float amount) 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 IsTextEntry() const override { return true; }
bool ModulatorUsesLiteralValue() const override { return true; }
protected:
~TextEntry(); //protected so that it can't be created on the stack
private:
void Construct(ITextEntryListener* owner, const char* name, int x, int y, int charWidth); //shared constructor
void AddCharacter(char c);
bool AllowCharacter(char c);
void AcceptEntry(bool pressedEnter) override;
void CancelEntry() override;
void MoveCaret(int pos, bool allowSelection = true);
void SelectAll();
void OnClicked(float x, float y, bool right) override;
bool MouseMoved(float x, float y) override;
int mCharWidth{ 3 };
ITextEntryListener* mListener{ nullptr };
char mString[MAX_TEXTENTRY_LENGTH]{};
char* mVarCString{ nullptr };
std::string* mVarString{ nullptr };
int* mVarInt{ nullptr };
float* mVarFloat{ nullptr };
int mIntMin{ 0 };
int mIntMax{ 0 };
float mFloatMin{ 0 };
float mFloatMax{ 0 };
int mCaretPosition{ 0 };
int mCaretPosition2{ 0 };
float mCaretBlinkTimer{ 0 };
bool mCaretBlink{ true };
TextEntryType mType{ TextEntryType::kTextEntry_Text };
TextEntry* mNextTextEntry{ nullptr };
TextEntry* mPreviousTextEntry{ nullptr };
bool mInErrorMode{ false };
bool mDrawLabel{ false };
float mLabelSize{ 0 };
bool mFlexibleWidth{ false };
bool mHovered{ false };
bool mRequireEnterToAccept{ false };
};
``` | /content/code_sandbox/Source/TextEntry.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,135 |
```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
**/
//
// NoteTransformer.h
// modularSynth
//
// Created by Ryan Challinor on 3/13/14.
//
//
#pragma once
#include <iostream>
#include "NoteEffectBase.h"
#include "IDrawableModule.h"
#include "Slider.h"
class NoteTransformer : public NoteEffectBase, public IDrawableModule, public IIntSliderListener
{
public:
NoteTransformer();
~NoteTransformer();
static IDrawableModule* Create() { return new NoteTransformer(); }
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;
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& width, float& height) override
{
width = 120;
height = 135;
}
int mToneMod[7]{};
IntSlider* mToneModSlider[7];
double mLastTimeTonePlayed[7]{};
int mLastNoteOnForPitch[128];
};
``` | /content/code_sandbox/Source/NoteTransformer.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 457 |
```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
**/
/*
==============================================================================
ChordDisplayer.h
Created: 27 Mar 2018 9:23:27pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include "IDrawableModule.h"
#include "NoteEffectBase.h"
class ChordDisplayer : public NoteEffectBase, public IDrawableModule
{
public:
ChordDisplayer();
static IDrawableModule* Create() { return new ChordDisplayer(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
//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;
void SaveState(FileStreamOut& out) override;
void LoadState(FileStreamIn& in, int rev) override;
int GetModuleSaveStateRev() const override { return 1; }
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
bool mAdvancedDetection{ false };
bool mUseScaleDegrees{ false };
bool mShowIntervals{ false };
};
``` | /content/code_sandbox/Source/ChordDisplayer.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
**/
//
// PatchCable.h
// Bespoke
//
// Created by Ryan Challinor on 12/12/15.
//
//
#pragma once
#include "IClickable.h"
class RollingBuffer;
class PatchCableSource;
class IAudioReceiver;
class RadioButton;
class UIControlConnection;
struct PatchCablePos
{
ofVec2f start;
ofVec2f end;
ofVec2f plug;
ofVec2f startDirection;
};
enum ConnectionType
{
kConnectionType_Note,
kConnectionType_Audio,
kConnectionType_UIControl,
kConnectionType_Grid,
kConnectionType_Special,
kConnectionType_Pulse,
kConnectionType_Modulator,
kConnectionType_ValueSetter //for modulator-type that don't have a continuous connection to the control, and just set values as one-offs
};
enum class CableDropBehavior
{
ShowQuickspawn,
DoNothing,
DisconnectCable
};
class PatchCable : public IClickable
{
friend class PatchCableSource;
public:
PatchCable(PatchCableSource* owner);
virtual ~PatchCable();
void Render() override;
bool TestClick(float x, float y, bool right, bool testOnly = false) override;
bool MouseMoved(float x, float y) override;
void MouseReleased() override;
void GetDimensions(float& width, float& height) override
{
width = 10;
height = 10;
}
IDrawableModule* GetOwningModule() const;
IClickable* GetTarget() const { return mTarget; }
ConnectionType GetConnectionType() const;
bool IsDragging() const { return mDragging; }
void SetHoveringOnSource(bool hovering) { mHoveringOnSource = hovering; }
void SetSourceIndex(int index) { mSourceIndex = index; }
PatchCableSource* GetOwner() const { return mOwner; }
void Grab();
void Release();
bool IsValidTarget(IClickable* target) const;
void Destroy(bool fromUserClick);
void SetTempDrawTarget(IClickable* target) { mTempDrawTarget = target; }
void ShowQuickspawnForCable();
IClickable* GetDropTarget();
void SetUIControlConnection(UIControlConnection* conn) { mUIControlConnection = conn; }
static PatchCable* sActivePatchCable;
protected:
void OnClicked(float x, float y, bool right) override;
private:
void SetCableTarget(IClickable* target);
PatchCablePos GetPatchCablePos();
ofVec2f FindClosestSide(float x, float y, float w, float h, ofVec2f start, ofVec2f startDirection, ofVec2f& endDirection);
PatchCableSource* mOwner{ nullptr };
IClickable* mTarget{ nullptr };
IClickable* mTempDrawTarget{ nullptr };
RadioButton* mTargetRadioButton{ nullptr };
UIControlConnection* mUIControlConnection{ nullptr };
IAudioReceiver* mAudioReceiverTarget{ nullptr };
bool mHovered{ false };
bool mDragging{ false };
ofVec2f mGrabPos;
bool mHoveringOnSource{ false };
int mSourceIndex{ 0 };
};
``` | /content/code_sandbox/Source/PatchCable.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 807 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
NoteStrummer.cpp
Created: 2 Apr 2018 9:27:16pm
Author: Ryan Challinor
==============================================================================
*/
#include "NoteStrummer.h"
#include "SynthGlobals.h"
#include "Scale.h"
NoteStrummer::NoteStrummer()
{
}
void NoteStrummer::Init()
{
IDrawableModule::Init();
TheTransport->AddAudioPoller(this);
}
NoteStrummer::~NoteStrummer()
{
TheTransport->RemoveAudioPoller(this);
}
void NoteStrummer::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mStrumSlider = new FloatSlider(this, "strum", 4, 4, 192, 15, &mStrum, 0, 1);
}
void NoteStrummer::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mStrumSlider->Draw();
int numNotes = (int)mNotes.size();
int i = 0;
for (auto pitch : mNotes)
{
float pos = float(i + .5f) / numNotes;
DrawTextNormal(NoteName(pitch), mStrumSlider->GetPosition(true).x + pos * mStrumSlider->IClickable::GetDimensions().x, mStrumSlider->GetPosition(true).y + mStrumSlider->IClickable::GetDimensions().y + 12);
++i;
}
}
void NoteStrummer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
if (velocity > 0)
{
mNotes.push_back(pitch);
}
else
{
PlayNoteOutput(time, pitch, 0, voiceIdx, modulation);
mNotes.remove(pitch);
}
}
void NoteStrummer::OnTransportAdvanced(float amount)
{
int numNotes = (int)mNotes.size();
for (int i = 0; i < gBufferSize; ++i)
{
ComputeSliders(i);
int index = 0;
for (auto pitch : mNotes)
{
float pos = float(index + .5f) / numNotes;
float change = mStrum - mLastStrumPos;
float offset = pos - mLastStrumPos;
bool wraparound = fabsf(change) > .99f;
if (change * offset > 0 && //same direction
fabsf(offset) <= fabsf(change) &&
!wraparound)
PlayNoteOutput(gTime + i * gInvSampleRateMs, pitch, 127);
++index;
}
mLastStrumPos = mStrum;
}
}
void NoteStrummer::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void NoteStrummer::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void NoteStrummer::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
``` | /content/code_sandbox/Source/NoteStrummer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 768 |
```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
**/
/*
==============================================================================
UserPrefs.h
Created: 24 Oct 2021 10:29:53pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
#include <string>
#include <vector>
#include "ofxJSONElement.h"
class IDrawableModule;
class IUIControl;
class DropdownList;
class TextEntry;
class Checkbox;
class FloatSlider;
enum class UserPrefCategory
{
General,
Graphics,
Paths
};
class UserPref
{
public:
virtual void Init() = 0;
virtual IUIControl* GetControl() = 0;
virtual void SetUpControl(IDrawableModule* owner) = 0;
virtual void Save(int index, ofxJSONElement& prefsJson) = 0;
virtual bool DiffersFromSavedValue() const = 0;
UserPrefCategory mCategory{ UserPrefCategory::General };
std::string mName;
};
void RegisterUserPref(UserPref* pref);
class UserPrefString : public UserPref
{
public:
UserPrefString(std::string name, std::string defaultValue, int charWidth, UserPrefCategory category)
: mValue(defaultValue)
, mDefault(defaultValue)
, mCharWidth(charWidth)
{
RegisterUserPref(this);
mName = name;
mCategory = category;
}
void Init() override;
void SetUpControl(IDrawableModule* owner) override;
IUIControl* GetControl() override;
TextEntry* GetTextEntry() { return mTextEntry; }
std::string& Get() { return mValue; }
std::string GetDefault() { return mDefault; }
void Save(int index, ofxJSONElement& prefsJson) override;
bool DiffersFromSavedValue() const override;
private:
std::string mValue;
std::string mDefault;
TextEntry* mTextEntry{ nullptr };
int mCharWidth{ 0 };
};
class UserPrefDropdownInt : public UserPref
{
public:
UserPrefDropdownInt(std::string name, int defaultValue, int width, UserPrefCategory category)
: mValue(defaultValue)
, mDefault(defaultValue)
, mWidth(width)
{
RegisterUserPref(this);
mName = name;
mCategory = category;
}
void Init() override;
void SetUpControl(IDrawableModule* owner) override;
IUIControl* GetControl() override;
DropdownList* GetDropdown() { return mDropdown; }
int& Get() { return mValue; }
int GetDefault() { return mDefault; }
int& GetIndex() { return mIndex; }
void Save(int index, ofxJSONElement& prefsJson) override;
bool DiffersFromSavedValue() const override;
private:
int mValue{ 0 };
int mDefault{ 0 };
int mIndex{ -1 };
DropdownList* mDropdown{ nullptr };
float mWidth{ 100 };
};
class UserPrefDropdownString : public UserPref
{
public:
UserPrefDropdownString(std::string name, std::string defaultValue, int width, UserPrefCategory category)
: mValue(defaultValue)
, mDefault(defaultValue)
, mWidth(width)
{
RegisterUserPref(this);
mName = name;
mCategory = category;
}
void Init() override;
void SetUpControl(IDrawableModule* owner) override;
IUIControl* GetControl() override;
DropdownList* GetDropdown() { return mDropdown; }
std::string& Get() { return mValue; }
std::string GetDefault() { return mDefault; }
int& GetIndex() { return mIndex; }
void Save(int index, ofxJSONElement& prefsJson) override;
bool DiffersFromSavedValue() const override;
private:
std::string mValue;
std::string mDefault;
int mIndex{ -1 };
DropdownList* mDropdown{ nullptr };
float mWidth{ 100 };
};
class UserPrefTextEntryInt : public UserPref
{
public:
UserPrefTextEntryInt(std::string name, int defaultValue, int min, int max, int digits, UserPrefCategory category)
: mValue(defaultValue)
, mDefault(defaultValue)
, mMin(min)
, mMax(max)
, mDigits(digits)
{
RegisterUserPref(this);
mName = name;
mCategory = category;
}
void Init() override;
void SetUpControl(IDrawableModule* owner) override;
IUIControl* GetControl() override;
TextEntry* GetTextEntry() { return mTextEntry; }
int& Get() { return mValue; }
int GetDefault() { return mDefault; }
void Save(int index, ofxJSONElement& prefsJson) override;
bool DiffersFromSavedValue() const override;
private:
int mValue{ 0 };
int mDefault{ 0 };
TextEntry* mTextEntry{ nullptr };
int mMin{ 0 };
int mMax{ 1 };
int mDigits{ 5 };
};
class UserPrefTextEntryFloat : public UserPref
{
public:
UserPrefTextEntryFloat(std::string name, float defaultValue, float min, float max, int digits, UserPrefCategory category)
: mValue(defaultValue)
, mDefault(defaultValue)
, mMin(min)
, mMax(max)
, mDigits(digits)
{
RegisterUserPref(this);
mName = name;
mCategory = category;
}
void Init() override;
void SetUpControl(IDrawableModule* owner) override;
IUIControl* GetControl() override;
TextEntry* GetTextEntry() { return mTextEntry; }
float& Get() { return mValue; }
float GetDefault() { return mDefault; }
void Save(int index, ofxJSONElement& prefsJson) override;
bool DiffersFromSavedValue() const override;
private:
float mValue{ 0 };
float mDefault{ 0 };
TextEntry* mTextEntry{ nullptr };
float mMin{ 0 };
float mMax{ 1 };
int mDigits{ 5 };
};
class UserPrefBool : public UserPref
{
public:
UserPrefBool(std::string name, bool defaultValue, UserPrefCategory category)
: mValue(defaultValue)
{
RegisterUserPref(this);
mName = name;
mCategory = category;
}
void Init() override;
void SetUpControl(IDrawableModule* owner) override;
IUIControl* GetControl() override;
Checkbox* GetCheckbox() { return mCheckbox; }
bool& Get() { return mValue; }
bool GetDefault() { return mDefault; }
void Save(int index, ofxJSONElement& prefsJson) override;
bool DiffersFromSavedValue() const override;
private:
bool mValue{ 0 };
bool mDefault{ 0 };
Checkbox* mCheckbox{ nullptr };
};
class UserPrefFloat : public UserPref
{
public:
UserPrefFloat(std::string name, float defaultValue, float min, float max, UserPrefCategory category)
: mValue(defaultValue)
, mDefault(defaultValue)
, mMin(min)
, mMax(max)
{
RegisterUserPref(this);
mName = name;
mCategory = category;
}
void Init() override;
void SetUpControl(IDrawableModule* owner) override;
IUIControl* GetControl() override;
FloatSlider* GetSlider() { return mSlider; }
float& Get() { return mValue; }
float GetDefault() { return mDefault; }
void Save(int index, ofxJSONElement& prefsJson) override;
bool DiffersFromSavedValue() const override;
private:
float mValue{ 0 };
float mDefault{ 0 };
FloatSlider* mSlider{ nullptr };
float mMin{ 0 };
float mMax{ 1 };
};
namespace
{
#if BESPOKE_MAC
const char* kDefaultYoutubeDlPath = "/opt/local/bin/youtube-dl";
const char* kDefaultFfmpegPath = "/opt/local/bin/ffmpeg";
#elif BESPOKE_LINUX
const char* kDefaultYoutubeDlPath = "/usr/bin/youtube-dl";
const char* kDefaultFfmpegPath = "/usr/bin/ffmpeg";
#else
const char* kDefaultYoutubeDlPath = "c:/youtube-dl/bin/youtube-dl.exe";
const char* kDefaultFfmpegPath = "c:/ffmpeg/bin/ffmpeg.exe";
#endif
}
class UserPrefsHolder
{
public:
void Init();
static std::string ToStringLeadingZeroes(int number);
float LastTargetFramerate;
ofxJSONElement mUserPrefsFile;
std::vector<UserPref*> mUserPrefs;
UserPrefDropdownString devicetype{ "devicetype", "auto", 200, UserPrefCategory::General };
UserPrefDropdownString audio_output_device{ "audio_output_device", "auto", 350, UserPrefCategory::General };
UserPrefDropdownString audio_input_device{ "audio_input_device", "none", 350, UserPrefCategory::General };
UserPrefDropdownInt samplerate{ "samplerate", 48000, 100, UserPrefCategory::General };
UserPrefDropdownInt buffersize{ "buffersize", 256, 100, UserPrefCategory::General };
UserPrefDropdownInt oversampling{ "oversampling", 1, 100, UserPrefCategory::General };
UserPrefTextEntryInt width{ "width", 1700, 100, 10000, 5, UserPrefCategory::General };
UserPrefTextEntryInt height{ "height", 1100, 100, 10000, 5, UserPrefCategory::General };
UserPrefBool set_manual_window_position{ "set_manual_window_position", false, UserPrefCategory::General };
UserPrefTextEntryInt position_x{ "position_x", 200, -10000, 10000, 5, UserPrefCategory::General };
UserPrefTextEntryInt position_y{ "position_y", 200, -10000, 10000, 5, UserPrefCategory::General };
UserPrefFloat zoom{ "zoom", 1.3f, .25f, 2, UserPrefCategory::General };
UserPrefFloat ui_scale{ "ui_scale", 1.3f, .25f, 2, UserPrefCategory::General };
UserPrefDropdownString cable_drop_behavior{ "cable_drop_behavior", "show quickspawn", 150, UserPrefCategory::General };
UserPrefDropdownString qwerty_to_pitch_mode{ "qwerty_to_pitch_mode", "Ableton", 150, UserPrefCategory::General };
UserPrefFloat grid_snap_size{ "grid_snap_size", 30, 5, 150, UserPrefCategory::General };
UserPrefFloat scroll_multiplier_vertical{ "scroll_multiplier_vertical", 1, -2, 2, UserPrefCategory::General };
UserPrefFloat scroll_multiplier_horizontal{ "scroll_multiplier_horizontal", 1, -2, 2, UserPrefCategory::General };
UserPrefBool wrap_mouse_on_pan{ "wrap_mouse_on_pan", true, UserPrefCategory::General };
UserPrefBool autosave{ "autosave", false, UserPrefCategory::General };
UserPrefBool show_tooltips_on_load{ "show_tooltips_on_load", true, UserPrefCategory::General };
UserPrefBool show_minimap{ "show_minimap", false, UserPrefCategory::General };
UserPrefBool immediate_paste{ "immediate_paste", false, UserPrefCategory::General };
UserPrefTextEntryFloat record_buffer_length_minutes{ "record_buffer_length_minutes", 30, 1, 120, 5, UserPrefCategory::General };
#if !BESPOKE_LINUX
UserPrefBool vst_always_on_top{ "vst_always_on_top", true, UserPrefCategory::General };
#endif
UserPrefTextEntryInt max_output_channels{ "max_output_channels", 16, 1, 1024, 5, UserPrefCategory::General };
UserPrefTextEntryInt max_input_channels{ "max_input_channels", 16, 1, 1024, 5, UserPrefCategory::General };
UserPrefString plugin_preference_order{ "plugin_preference_order", "VST3;VST;AudioUnit;LV2", 70, UserPrefCategory::General };
UserPrefBool draw_background_lissajous{ "draw_background_lissajous", true, UserPrefCategory::Graphics };
UserPrefFloat cable_alpha{ "cable_alpha", 1, 0.05f, 1, UserPrefCategory::Graphics };
UserPrefBool fade_cable_middle{ "fade_cable_middle", true, UserPrefCategory::Graphics };
UserPrefFloat cable_quality{ "cable_quality", 1, .1f, 3, UserPrefCategory::Graphics };
UserPrefFloat lissajous_r{ "lissajous_r", 0.408f, 0, 1, UserPrefCategory::Graphics };
UserPrefFloat lissajous_g{ "lissajous_g", 0.245f, 0, 1, UserPrefCategory::Graphics };
UserPrefFloat lissajous_b{ "lissajous_b", 0.418f, 0, 1, UserPrefCategory::Graphics };
UserPrefFloat background_r{ "background_r", 0.09f, 0, 1, UserPrefCategory::Graphics };
UserPrefFloat background_g{ "background_g", 0.09f, 0, 1, UserPrefCategory::Graphics };
UserPrefFloat background_b{ "background_b", 0.09f, 0, 1, UserPrefCategory::Graphics };
UserPrefFloat target_framerate{ "target_framerate", 60, 30, 144, UserPrefCategory::Graphics };
UserPrefFloat motion_trails{ "motion_trails", 1, 0, 2, UserPrefCategory::Graphics };
UserPrefBool draw_module_highlights{ "draw_module_highlights", true, UserPrefCategory::Graphics };
UserPrefTextEntryFloat mouse_offset_x{ "mouse_offset_x", 0, -100, 100, 5, UserPrefCategory::Graphics };
UserPrefTextEntryFloat mouse_offset_y
{
"mouse_offset_y",
#if BESPOKE_MAC
-4,
#else
0,
#endif
-100, 100, 5, UserPrefCategory::Graphics
};
UserPrefString recordings_path{ "recordings_path", "recordings/", 70, UserPrefCategory::Paths };
UserPrefString tooltips{ "tooltips", "tooltips_eng.txt", 70, UserPrefCategory::Paths };
UserPrefString layout{ "layout", "layouts/blank.json", 70, UserPrefCategory::Paths };
UserPrefString youtube_dl_path{ "youtube_dl_path", kDefaultYoutubeDlPath, 70, UserPrefCategory::Paths };
UserPrefString ffmpeg_path{ "ffmpeg_path", kDefaultFfmpegPath, 70, UserPrefCategory::Paths };
};
extern UserPrefsHolder UserPrefs;
``` | /content/code_sandbox/Source/UserPrefs.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 3,429 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
/*
==============================================================================
ModulatorCurve.cpp
Created: 29 Nov 2017 8:56:48pm
Author: Ryan Challinor
==============================================================================
*/
#include "ModulatorCurve.h"
#include "Profiler.h"
#include "ModularSynth.h"
#include "PatchCableSource.h"
namespace
{
const int kAdsrTime = 10000;
}
ModulatorCurve::ModulatorCurve()
{
mEnvelopeControl.SetADSR(&mAdsr);
mEnvelopeControl.SetViewLength(kAdsrTime);
mEnvelopeControl.SetFixedLengthMode(true);
mAdsr.GetFreeReleaseLevel() = true;
mAdsr.SetNumStages(2);
mAdsr.GetHasSustainStage() = false;
mAdsr.GetStageData(0).target = 0;
mAdsr.GetStageData(0).time = 0.01f;
mAdsr.GetStageData(1).target = 1;
mAdsr.GetStageData(1).time = kAdsrTime - .02f;
}
void ModulatorCurve::CreateUIControls()
{
IDrawableModule::CreateUIControls();
mInputSlider = new FloatSlider(this, "input", 3, 2, 100, 15, &mInput, 0, 1);
mTargetCable = new PatchCableSource(this, kConnectionType_Modulator);
mTargetCable->SetModulatorOwner(this);
AddPatchCableSource(mTargetCable);
}
ModulatorCurve::~ModulatorCurve()
{
}
void ModulatorCurve::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
mInputSlider->Draw();
mEnvelopeControl.Draw();
}
void ModulatorCurve::PostRepatch(PatchCableSource* cableSource, bool fromUserClick)
{
OnModulatorRepatch();
if (GetSliderTarget() && fromUserClick)
mInput = GetSliderTarget()->GetValue();
}
float ModulatorCurve::Value(int samplesIn)
{
ComputeSliders(samplesIn);
ADSR::EventInfo adsrEvent(0, kAdsrTime);
float val = ofClamp(mAdsr.Value(mInput * kAdsrTime, &adsrEvent), 0, 1);
if (std::isnan(val))
val = 0;
return ofLerp(GetMin(), GetMax(), val);
}
void ModulatorCurve::OnClicked(float x, float y, bool right)
{
IDrawableModule::OnClicked(x, y, right);
mEnvelopeControl.OnClicked(x, y, right);
}
void ModulatorCurve::MouseReleased()
{
IDrawableModule::MouseReleased();
mEnvelopeControl.MouseReleased();
}
bool ModulatorCurve::MouseMoved(float x, float y)
{
IDrawableModule::MouseMoved(x, y);
mEnvelopeControl.MouseMoved(x, y);
return false;
}
void ModulatorCurve::SaveLayout(ofxJSONElement& moduleInfo)
{
}
void ModulatorCurve::LoadLayout(const ofxJSONElement& moduleInfo)
{
SetUpFromSaveData();
}
void ModulatorCurve::SetUpFromSaveData()
{
}
void ModulatorCurve::SaveState(FileStreamOut& out)
{
out << GetModuleSaveStateRev();
IDrawableModule::SaveState(out);
mAdsr.SaveState(out);
}
void ModulatorCurve::LoadState(FileStreamIn& in, int rev)
{
IDrawableModule::LoadState(in, rev);
if (ModularSynth::sLoadingFileSaveStateRev < 423)
in >> rev;
LoadStateValidate(rev <= GetModuleSaveStateRev());
mAdsr.LoadState(in);
}
``` | /content/code_sandbox/Source/ModulatorCurve.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 901 |
```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
**/
//
// NoteGate.h
// Bespoke
//
// Created by Ryan Challinor on 5/22/16.
//
//
#pragma once
#include "IDrawableModule.h"
#include "NoteEffectBase.h"
class NoteGate : public NoteEffectBase, public IDrawableModule
{
public:
NoteGate();
virtual ~NoteGate();
static IDrawableModule* Create() { return new NoteGate(); }
static bool AcceptsAudio() { return false; }
static bool AcceptsNotes() { return true; }
static bool AcceptsPulses() { return false; }
void CreateUIControls() override;
//INoteReceiver
void PlayNote(double time, int pitch, int velocity, int voiceIdx = -1, ModulationParameters modulation = ModulationParameters()) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void LoadLayout(const ofxJSONElement& moduleInfo) override;
void SetUpFromSaveData() override;
bool IsEnabled() const override { return true; }
private:
//IDrawableModule
void DrawModule() override;
void GetModuleDimensions(float& width, float& height) override;
bool mGate{ true };
Checkbox* mGateCheckbox{ nullptr };
std::array<NoteInputElement, 128> mActiveNotes{ false };
};
``` | /content/code_sandbox/Source/NoteGate.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 385 |
```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
**/
//
// FormantFilterEffect.h
// Bespoke
//
// Created by Ryan Challinor on 4/21/16.
//
//
#pragma once
#include "IAudioEffect.h"
#include "DropdownList.h"
#include "Checkbox.h"
#include "Slider.h"
#include "BiquadFilter.h"
#include "RadioButton.h"
class FormantFilterEffect : public IAudioEffect, public IDropdownListener, public IFloatSliderListener, public IRadioButtonListener
{
public:
FormantFilterEffect();
~FormantFilterEffect();
static IAudioEffect* Create() { return new FormantFilterEffect(); }
void CreateUIControls() override;
void Init() override;
//IAudioEffect
void ProcessAudio(double time, ChannelBuffer* buffer) override;
void SetEnabled(bool enabled) override { mEnabled = enabled; }
float GetEffectAmount() override;
std::string GetType() override { return "formant"; }
void DropdownUpdated(DropdownList* list, int oldVal, double time) override;
void CheckboxUpdated(Checkbox* checkbox, double time) override;
void FloatSliderUpdated(FloatSlider* slider, float oldVal, double time) override;
void RadioButtonUpdated(RadioButton* list, int oldVal, double time) override;
void LoadLayout(const ofxJSONElement& info) override;
void SetUpFromSaveData() override;
void SaveLayout(ofxJSONElement& info) override;
bool IsEnabled() const override { return mEnabled; }
private:
//IDrawableModule
void GetModuleDimensions(float& width, float& height) override
{
width = mWidth;
height = mHeight;
}
void DrawModule() override;
void ResetFilters();
void UpdateFilters();
#define NUM_FORMANT_BANDS 3
BiquadFilter mBiquads[NUM_FORMANT_BANDS];
float* mDryBuffer{ nullptr };
float mEE{ 1 };
float mOO{ 0 };
float mI{ 0 };
float mE{ 0 };
float mU{ 0 };
float mA{ 0 };
FloatSlider* mEESlider{ nullptr };
FloatSlider* mOOSlider{ nullptr };
FloatSlider* mISlider{ nullptr };
FloatSlider* mESlider{ nullptr };
FloatSlider* mUSlider{ nullptr };
FloatSlider* mASlider{ nullptr };
std::vector<FloatSlider*> mSliders{};
bool mRescaling{ false };
float mWidth{ 200 };
float mHeight{ 20 };
struct Formants
{
Formants(float f1, float g1, float f2, float g2, float f3, float g3)
{
assert(NUM_FORMANT_BANDS == 3);
mFreqs[0] = f1;
mGains[0] = g1;
mFreqs[1] = f2;
mGains[1] = g2;
mFreqs[2] = f3;
mGains[2] = g3;
}
float mFreqs[NUM_FORMANT_BANDS]{};
float mGains[NUM_FORMANT_BANDS]{};
};
std::vector<Formants> mFormants;
float* mOutputBuffer{ nullptr };
};
``` | /content/code_sandbox/Source/FormantFilterEffect.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 813 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// SingleOscillatorVoice.cpp
// modularSynth
//
// Created by Ryan Challinor on 12/4/13.
//
//
#include "SingleOscillatorVoice.h"
#include "EnvOscillator.h"
#include "SynthGlobals.h"
#include "Scale.h"
#include "Profiler.h"
#include "ChannelBuffer.h"
SingleOscillatorVoice::SingleOscillatorVoice(IDrawableModule* owner)
: mOwner(owner)
{
}
SingleOscillatorVoice::~SingleOscillatorVoice()
{
}
bool SingleOscillatorVoice::IsDone(double time)
{
return mAdsr.IsDone(time);
}
bool SingleOscillatorVoice::Process(double time, ChannelBuffer* out, int oversampling)
{
PROFILER(SingleOscillatorVoice);
if (IsDone(time))
return false;
for (int u = 0; u < mVoiceParams->mUnison && u < kMaxUnison; ++u)
mOscData[u].mOsc.SetType(mVoiceParams->mOscType);
bool mono = (out->NumActiveChannels() == 1);
float pitch;
float freq;
float vol;
float syncPhaseInc;
if (mVoiceParams->mLiteCPUMode)
DoParameterUpdate(0, pitch, freq, vol, syncPhaseInc);
for (int pos = 0; pos < out->BufferSize(); ++pos)
{
if (!mVoiceParams->mLiteCPUMode)
DoParameterUpdate(pos, pitch, freq, vol, syncPhaseInc);
float adsrVal = mAdsr.Value(time);
float summedLeft = 0;
float summedRight = 0;
for (int u = 0; u < mVoiceParams->mUnison && u < kMaxUnison; ++u)
{
mOscData[u].mOsc.SetPulseWidth(mVoiceParams->mPulseWidth);
mOscData[u].mOsc.SetShuffle(mVoiceParams->mShuffle);
mOscData[u].mOsc.SetSoften(mVoiceParams->mSoften);
{
//PROFILER(SingleOscillatorVoice_UpdatePhase);
mOscData[u].mPhase += mOscData[u].mCurrentPhaseInc;
if (mOscData[u].mPhase == INFINITY)
{
ofLog() << "Infinite phase. phaseInc:" + ofToString(mOscData[u].mCurrentPhaseInc) + " detune:" + ofToString(mVoiceParams->mDetune) + " freq:" + ofToString(freq) + " pitch:" + ofToString(pitch) + " getpitch:" + ofToString(GetPitch(pos));
}
else
{
while (mOscData[u].mPhase > FTWO_PI * 2)
{
mOscData[u].mPhase -= FTWO_PI * 2;
mOscData[u].mSyncPhase = 0;
}
}
mOscData[u].mSyncPhase += syncPhaseInc;
}
float sample;
{
//PROFILER(SingleOscillatorVoice_GetOscValue);
if (mVoiceParams->mSyncMode != Oscillator::SyncMode::None)
sample = mOscData[u].mOsc.Value(mOscData[u].mSyncPhase) * adsrVal * vol;
else
sample = mOscData[u].mOsc.Value(mOscData[u].mPhase + mVoiceParams->mPhaseOffset * (1 + (float(u) / mVoiceParams->mUnison))) * adsrVal * vol;
}
if (u >= 2)
sample *= 1 - (mOscData[u].mDetuneFactor * .5f);
if (mono)
{
summedLeft += sample;
}
else
{
//PROFILER(SingleOscillatorVoice_pan);
float unisonPan;
if (mVoiceParams->mUnison == 1)
unisonPan = 0;
else if (u == 0)
unisonPan = -1;
else if (u == 1)
unisonPan = 1;
else
unisonPan = mOscData[u].mDetuneFactor;
float pan = GetPan() + unisonPan * mVoiceParams->mUnisonWidth;
summedLeft += sample * GetLeftPanGain(pan);
summedRight += sample * GetRightPanGain(pan);
}
}
if (mUseFilter)
{
//PROFILER(SingleOscillatorVoice_filter);
float f = ofLerp(mVoiceParams->mFilterCutoffMin, mVoiceParams->mFilterCutoffMax, mFilterAdsr.Value(time)) * (1 - GetModWheel(pos) * .9f);
float q = mVoiceParams->mFilterQ;
if (f != mFilterLeft.mF || q != mFilterLeft.mQ)
mFilterLeft.SetFilterParams(f, q);
summedLeft = mFilterLeft.Filter(summedLeft);
if (!mono)
{
mFilterRight.CopyCoeffFrom(mFilterLeft);
summedRight = mFilterRight.Filter(summedRight);
}
}
{
//PROFILER(SingleOscillatorVoice_output);
if (mono)
{
out->GetChannel(0)[pos] += summedLeft;
}
else
{
out->GetChannel(0)[pos] += summedLeft;
out->GetChannel(1)[pos] += summedRight;
}
}
time += gInvSampleRateMs;
}
return true;
}
void SingleOscillatorVoice::DoParameterUpdate(int samplesIn,
float& pitch,
float& freq,
float& vol,
float& syncPhaseInc)
{
if (mOwner)
mOwner->ComputeSliders(samplesIn);
pitch = GetPitch(samplesIn);
freq = TheScale->PitchToFreq(pitch) * mVoiceParams->mMult;
vol = mVoiceParams->mVol * .4f / mVoiceParams->mUnison;
if (mVoiceParams->mSyncMode == Oscillator::SyncMode::Frequency)
syncPhaseInc = GetPhaseInc(mVoiceParams->mSyncFreq);
else if (mVoiceParams->mSyncMode == Oscillator::SyncMode::Ratio)
syncPhaseInc = GetPhaseInc(freq * mVoiceParams->mSyncRatio);
else
syncPhaseInc = 0;
for (int u = 0; u < mVoiceParams->mUnison && u < kMaxUnison; ++u)
{
float detune = exp2(mVoiceParams->mDetune * mOscData[u].mDetuneFactor * (1 - GetPressure(samplesIn)));
mOscData[u].mCurrentPhaseInc = GetPhaseInc(freq * detune);
}
}
//static
float SingleOscillatorVoice::GetADSRScale(float velocity, float velToEnvelope)
{
if (velToEnvelope > 0)
return ofLerp((1 - velToEnvelope), 1, velocity);
return ofClamp(ofLerp(1, 1 + velToEnvelope, velocity), 0.001f, 1);
}
void SingleOscillatorVoice::Start(double time, float target)
{
float volume = ofLerp((1 - mVoiceParams->mVelToVolume), 1, target);
float adsrScale = GetADSRScale(target, mVoiceParams->mVelToEnvelope);
mAdsr.Start(time, volume, mVoiceParams->mAdsr, adsrScale);
if (mVoiceParams->mFilterCutoffMax != SINGLEOSCILLATOR_NO_CUTOFF)
{
mUseFilter = true;
mFilterLeft.SetFilterType(kFilterType_Lowpass);
mFilterRight.SetFilterType(kFilterType_Lowpass);
mFilterAdsr.Start(time, 1, mVoiceParams->mFilterAdsr, adsrScale);
}
else
{
mUseFilter = false;
}
}
void SingleOscillatorVoice::Stop(double time)
{
mAdsr.Stop(time);
mFilterAdsr.Stop(time);
}
void SingleOscillatorVoice::ClearVoice()
{
mAdsr.Clear();
mFilterAdsr.Clear();
for (int u = 0; u < kMaxUnison; ++u)
{
mOscData[u].mPhase = 0;
mOscData[u].mSyncPhase = 0;
}
//set this up so it's different with each fresh voice, but doesn't reset when voice is retriggered
mOscData[0].mDetuneFactor = 1;
mOscData[1].mDetuneFactor = 0;
for (int u = 2; u < kMaxUnison; ++u)
mOscData[u].mDetuneFactor = ofRandom(-1, 1);
}
void SingleOscillatorVoice::SetVoiceParams(IVoiceParams* params)
{
mVoiceParams = dynamic_cast<OscillatorVoiceParams*>(params);
}
``` | /content/code_sandbox/Source/SingleOscillatorVoice.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 2,109 |
```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
**/
/*
==============================================================================
IAudioPoller.h
Created: 12 Apr 2018 10:30:11pm
Author: Ryan Challinor
==============================================================================
*/
#pragma once
class IAudioPoller
{
public:
virtual ~IAudioPoller() {}
virtual void OnTransportAdvanced(float amount) = 0;
};
``` | /content/code_sandbox/Source/IAudioPoller.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 171 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// ArrangementController.cpp
// Bespoke
//
// Created by Ryan Challinor on 8/26/14.
//
//
#include "ArrangementController.h"
int ArrangementController::mPlayhead = 0;
bool ArrangementController::mPlay = false;
int ArrangementController::mSampleLength = 0;
``` | /content/code_sandbox/Source/ArrangementController.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 167 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// FilterViz.cpp
// Bespoke
//
// Created by Ryan Challinor on 12/24/14.
//
//
#include "FilterViz.h"
#include "ModularSynth.h"
#include "SynthGlobals.h"
#include "FFT.h"
#include "EffectFactory.h"
FilterViz::FilterViz()
{
mImpulseBuffer = new float[FILTER_VIZ_BINS];
mFFTOutReal = new float[FILTER_VIZ_BINS];
mFFTOutImag = new float[FILTER_VIZ_BINS];
Clear(mFFTOutReal, FILTER_VIZ_BINS);
Clear(mFFTOutImag, FILTER_VIZ_BINS);
for (int i = 0; i < 1; ++i)
{
IAudioEffect* filter = TheSynth->GetEffectFactory()->MakeEffect("eq");
AddChild(filter);
filter->SetPosition(4 + 100 * i, 20);
filter->SetName(("filter " + ofToString(i)).c_str());
mFilters.push_back(filter);
}
}
void FilterViz::CreateUIControls()
{
IDrawableModule::CreateUIControls();
for (int i = 0; i < mFilters.size(); ++i)
mFilters[i]->CreateUIControls();
}
FilterViz::~FilterViz()
{
for (int i = 0; i < mFilters.size(); ++i)
delete mFilters[i];
delete mImpulseBuffer;
delete mFFTOutReal;
delete mFFTOutImag;
}
void FilterViz::Poll()
{
mNeedUpdate = true;
if (mNeedUpdate)
{
GraphFilter();
mNeedUpdate = false;
}
}
void FilterViz::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
for (int i = 0; i < mFilters.size(); ++i)
mFilters[i]->Draw();
float w, h;
GetDimensions(w, h);
ofPushStyle();
{
ofSetColor(255, 255, 255);
ofPoint lastPoint(0, 0);
for (int i = 0; i < FILTER_VIZ_BINS / 2 - 1; ++i)
{
float a = float(i) / (FILTER_VIZ_BINS / 2 - 1);
a = sqrtf(a);
ofPoint point(a * w, h - (mFFTOutReal[i] / 12 * h));
if (i != 0)
ofLine(lastPoint, point);
lastPoint = point;
}
}
{
ofSetColor(255, 0, 255);
ofPoint lastPoint(0, 0);
for (int i = 0; i < FILTER_VIZ_BINS / 2 - 1; ++i)
{
float a = float(i) / (FILTER_VIZ_BINS / 2 - 1);
a = sqrtf(a);
ofPoint point(a * w, h / 2 - (mFFTOutImag[i] / (PI * 2) * h));
if (i != 0)
ofLine(lastPoint, point);
lastPoint = point;
}
}
ofPopStyle();
}
void FilterViz::GraphFilter()
{
Clear(mImpulseBuffer, FILTER_VIZ_BINS);
mImpulseBuffer[0] = 1;
ChannelBuffer temp(mImpulseBuffer, FILTER_VIZ_BINS);
for (int i = 0; i < mFilters.size(); ++i)
mFilters[i]->ProcessAudio(gTime, &temp);
::FFT fft(FILTER_VIZ_BINS);
fft.Forward(mImpulseBuffer, mFFTOutReal, mFFTOutImag);
for (int j = 0; j < FILTER_VIZ_BINS / 2 + 1; ++j)
{
float real = mFFTOutReal[j];
float imag = mFFTOutImag[j];
//cartesian to polar
float amp = 2. * sqrtf(real * real + imag * imag);
float phase = atan2(imag, real);
mFFTOutReal[j] = amp;
mFFTOutImag[j] = phase;
}
}
void FilterViz::DropdownUpdated(DropdownList* list, int oldVal, double time)
{
}
void FilterViz::FloatSliderUpdated(FloatSlider* slider, float oldVal, double time)
{
}
void FilterViz::ButtonClicked(ClickButton* button, double time)
{
}
``` | /content/code_sandbox/Source/FilterViz.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 1,092 |
```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
**/
//
// IVoiceParams.h
// modularSynth
//
// Created by Ryan Challinor on 11/22/12.
//
//
#pragma once
class IVoiceParams
{
public:
virtual ~IVoiceParams() {}
};
``` | /content/code_sandbox/Source/IVoiceParams.h | objective-c | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 147 |
```c++
/**
bespoke synth, a software modular synthesizer
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see <path_to_url
**/
//
// NoteDisplayer.cpp
// Bespoke
//
// Created by Ryan Challinor on 6/17/15.
//
//
#include "NoteDisplayer.h"
#include "SynthGlobals.h"
void NoteDisplayer::DrawModule()
{
if (Minimized() || IsVisible() == false)
return;
bool* notes = mNoteOutput.GetNotes();
float y = 14;
for (int i = 0; i < 128; ++i)
{
if (notes[i])
{
DrawNoteName(i, y);
y += 13;
}
}
}
void NoteDisplayer::DrawNoteName(int pitch, float y) const
{
DrawTextNormal(NoteName(pitch) + ofToString(pitch / 12 - 2) + " (" + ofToString(pitch) + ")" +
" vel:" + ofToString(mVelocities[pitch]) +
" voiceId:" + ofToString(mVoiceIds[pitch]),
4, y);
}
void NoteDisplayer::PlayNote(double time, int pitch, int velocity, int voiceIdx, ModulationParameters modulation)
{
PlayNoteOutput(time, pitch, velocity, voiceIdx, modulation);
mVelocities[pitch] = velocity;
mVoiceIds[pitch] = voiceIdx;
}
void NoteDisplayer::LoadLayout(const ofxJSONElement& moduleInfo)
{
mModuleSaveData.LoadString("target", moduleInfo);
SetUpFromSaveData();
}
void NoteDisplayer::SetUpFromSaveData()
{
SetUpPatchCables(mModuleSaveData.GetString("target"));
}
void NoteDisplayer::Resize(float w, float h)
{
mWidth = w;
mHeight = h;
}
``` | /content/code_sandbox/Source/NoteDisplayer.cpp | c++ | 2016-08-14T14:36:36 | 2024-08-16T18:55:21 | BespokeSynth | BespokeSynth/BespokeSynth | 4,019 | 465 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.