diff --git a/.gitignore b/.gitignore index 23ac7f1..b81bb8a 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ /plugin.dylib /plugin.dll /plugin.so -.DS_Store \ No newline at end of file +.DS_Store +/.vscode \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 8400b3b..0142fca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Change Log + +## v2.7.0 + * Midi Thing 2 + * Initial release + * Octaves + * Better default oversampling setting (x4) + + +## v2.6.0 + * Octaves + * Initial release + * Misc + * Better default values for ADSR and Burst + + +## v2.5.0 + * Burst + * Initial release + * Voltio + * Initial release + * PonyVCO + * Now polyphonic + * Misc + * Fix trigger inputs to follow Rack voltage standards (Kickall, Muxlicer, Rampage) + ## v2.4.1 * Rampage * Fix SIMD bug diff --git a/README.md b/README.md index b14a75c..2caa49b 100644 --- a/README.md +++ b/README.md @@ -28,4 +28,6 @@ We have tried to make the VCV implementations as authentic as possible, however * to limit the pulsewidth from 5% to 95% (hardware is full range) * to remove DC from the pulse waveform output (hardware contains DC for non-50% duty cycles) -* MotionMTR optionally doesn't use the 10V normalling on inputs if in audio mode to avoid acidentally adding unwanted DC to audio signals, see context menu. E.g. if you temporarily unpatch an audio source whilst using it it mixer mode, you get 10V DC suddenly and a nasty pop. \ No newline at end of file +* MotionMTR optionally doesn't use the 10V normalling on inputs if in audio mode to avoid acidentally adding unwanted DC to audio signals, see context menu. E.g. if you temporarily unpatch an audio source whilst using it it mixer mode, you get 10V DC suddenly and a nasty pop. + +* Burst hardware version version can also set the tempo by tapping the encoder, this is not possible in the VCV version. \ No newline at end of file diff --git a/docs/MIDIThingV2.md b/docs/MIDIThingV2.md new file mode 100644 index 0000000..b61132e --- /dev/null +++ b/docs/MIDIThingV2.md @@ -0,0 +1,28 @@ +# MIDI Thing v2 + +The original MIDI Thing v2 hardware unit is described as follows: + +> Midi Thing v2 is a flexible MIDI to CV converter. Allowing polyphonic notes handling, envelope and LFO generation as well as all available MIDI messages to be converted into CV. This is a huge upgrade from our previous beloved MIDI Thing, which adds a screen for easy configuration,12 assignable ports, TRS, USB Host and Device, MIDI merge OUT, a web configuration tool, and a VCV rack Bridge counterpart. + +The VCV counterpart is designed to allow users to quickly get up and running with their hardware, i.e. sending CV from VCV to the hardware unit. + +## Setup + +To use, first ensure the MIDI Thing v2 is plugged into your computer, and visible as a MIDI device. Then select it, either from the top of the module, or the right click context menu. Then click "SYNC" - this puts the MIDI Thing into a preset designed to work with VCV Rack, and syncronises settings/voltage ranges etc. Note that for now, sync is one-way (VCV to hardware). + +![MIDI Thing Config](img/MidiThingV2.png "MIDI Thing v2 Setup") + +## Usage + +To use, simply wire CV which you wish to send to the hardware to the matching input on the VCV module. Note that you will need to select the range, which can be done by right-clicking on the matching box (see below). Options are 0/10v, -5/5v, -10/0v, 0/8v, 0/5v. Note that the module is **not** designed to work with audio rate signals, just CV. + +![MIDI Thing Voltage Range](img/VoltageRange.png "MIDI Thing v2 Voltage Range") + +## Update Rate + +Midi Thing v2 VCV allows the user to configure the update rate at which data is sent over MIDI. This must be shared between the channels, so if we set the hardware to update at 1 kHz, 1 active channel will update at 1 kHz, 2 active channels will update at 500 Hz, 4 active channels at 250 Hz and so on. The total update rate (to be shared between channels) is set from the context menu, noting that higher update rates will use more CPU. The effect of the update rate on a 90 Hz saw (blue trace) can be seen in the bottom image, specifically that the temporal resolution of the reconstructed signal (red traces) improves as the update rate is increased from 500 Hz to 1000 Hz to 2000 Hz. + +![MIDI Thing Update Rates](img/UpdateRate.png "MIDI Thing v2 Update Ranges Menu") +![MIDI Thing Update Rates](img/UpdateRatesScope.png "MIDI Thing v2 Update Ranges Menu") + + diff --git a/docs/img/MidiThingV2.png b/docs/img/MidiThingV2.png new file mode 100644 index 0000000..6d3dc95 Binary files /dev/null and b/docs/img/MidiThingV2.png differ diff --git a/docs/img/UpdateRate.png b/docs/img/UpdateRate.png new file mode 100644 index 0000000..5102823 Binary files /dev/null and b/docs/img/UpdateRate.png differ diff --git a/docs/img/UpdateRatesScope.png b/docs/img/UpdateRatesScope.png new file mode 100644 index 0000000..cdfe6fd Binary files /dev/null and b/docs/img/UpdateRatesScope.png differ diff --git a/docs/img/VoltageRange.png b/docs/img/VoltageRange.png new file mode 100644 index 0000000..2da5ec4 Binary files /dev/null and b/docs/img/VoltageRange.png differ diff --git a/plugin.json b/plugin.json index a001e22..7fd7088 100644 --- a/plugin.json +++ b/plugin.json @@ -1,6 +1,6 @@ { "slug": "Befaco", - "version": "2.4.1", + "version": "2.7.0", "license": "GPL-3.0-or-later", "name": "Befaco", "brand": "Befaco", @@ -267,6 +267,7 @@ "Hardware clone", "Low-frequency oscillator", "Oscillator", + "Polyphonic", "Waveshaper" ] }, @@ -282,6 +283,54 @@ "Mixer", "Visual" ] + }, + { + "slug": "Burst", + "name": "Burst", + "description": "Trigger processor and generator, designed to add an organic chain of events", + "manualUrl": "https://www.befaco.org/burst-2/", + "modularGridUrl": "https://www.modulargrid.net/e/befaco-burst-", + "tags": [ + "Clock generator", + "Clock modulator", + "Hardware clone" + ] + }, + { + "slug": "MidiThingV2", + "name": "MIDI Thing V2", + "description": "Hardware MIDI Thing v2 is a flexible MIDI to CV converter, this module acts as a bridge from VCV", + "manualUrl": "https://github.com/VCVRack/Befaco/blob/v2/docs/MIDIThingV2.md", + "modularGridUrl": "https://www.modulargrid.net/e/befaco-midi-thing-v2", + "tags": [ + "External", + "MIDI", + "Hardware clone" + ] + }, + { + "slug": "Voltio", + "name": "Voltio", + "description": "An accurate voltage source and precision adder.", + "manualUrl": "https://www.befaco.org/voltio/", + "modularGridUrl": "https://www.modulargrid.net/e/befaco-voltio", + "tags": [ + "Hardware clone", + "Polyphonic", + "Utility" + ] + }, + { + "slug": "Octaves", + "name": "Octaves", + "description": "A harsh and funky take of an additive Oscillator.", + "manualUrl": "https://www.befaco.org/octaves-vco/", + "modularGridUrl": "https://www.modulargrid.net/e/befaco-octaves-vco", + "tags": [ + "Hardware clone", + "Oscillator", + "Polyphonic" + ] } ] -} \ No newline at end of file +} diff --git a/res/components/Davies1900hWhiteEndless.svg b/res/components/Davies1900hWhiteEndless.svg new file mode 100644 index 0000000..4eacfa0 --- /dev/null +++ b/res/components/Davies1900hWhiteEndless.svg @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + diff --git a/res/components/Davies1900hWhiteEndless_bg.svg b/res/components/Davies1900hWhiteEndless_bg.svg new file mode 100644 index 0000000..a8f37b6 --- /dev/null +++ b/res/components/Davies1900hWhiteEndless_bg.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/res/fonts/MISO-info.txt b/res/fonts/MISO-info.txt new file mode 100644 index 0000000..dffe47f --- /dev/null +++ b/res/fonts/MISO-info.txt @@ -0,0 +1,56 @@ + M M I SSS OOO + MM MM I S S O O + M M M M I S O O + M M M I S O O + M M I S O O + M M I S S O O + M M I SSS OOO + +--------------------------------------- +MISO is an architectural lettering font +completed in 2006 by Mårten Nettelbladt. +--------------------------------------- +MISO is available in three weights +(Light, Regular, Bold) +in TrueType and OpenType format. +--------------------------------------- + + L I C E N S E I N F O R M A T I O N +--------------------------------------- +MISO is a free typeface. However, +there is one important limitation: + +MISO MUST ALWAYS REMAIN COMPLETELY FREE + +You can use MISO for personal and commercial work. +You can share MISO with your friends +as long as you include this text file. + +You must not sell MISO. +You must not charge someone else for using MISO. +You must not bundle MISO with a sold product. + +Use it, share it, but keep it free. +--------------------------------------- + +Mårten Nettelbladt +Omkrets arkitektur +www.omkrets.se + +Stockholm, Sweden +July 9th 2009 + +--------------------------------------- +If you have any comments about MISO +please let me know: +miso (a) omkrets.se +--------------------------------------- + +November 27th 2008 +Converted to OpenType by Torin Hill. + +June 24th 2007 +Some small adjustments + +October 23rd 2006 +Released \ No newline at end of file diff --git a/res/fonts/miso.otf b/res/fonts/miso.otf new file mode 100644 index 0000000..2b0c62e Binary files /dev/null and b/res/fonts/miso.otf differ diff --git a/res/panels/Burst.svg b/res/panels/Burst.svg new file mode 100644 index 0000000..cf45e7b --- /dev/null +++ b/res/panels/Burst.svg @@ -0,0 +1,1131 @@ + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/panels/MidiThing.svg b/res/panels/MidiThing.svg new file mode 100644 index 0000000..a9a96b5 --- /dev/null +++ b/res/panels/MidiThing.svg @@ -0,0 +1,5595 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/panels/Octaves.svg b/res/panels/Octaves.svg new file mode 100644 index 0000000..2f99793 --- /dev/null +++ b/res/panels/Octaves.svg @@ -0,0 +1,2383 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + +    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +   + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/panels/Voltio.svg b/res/panels/Voltio.svg new file mode 100644 index 0000000..df367fb --- /dev/null +++ b/res/panels/Voltio.svg @@ -0,0 +1,1338 @@ + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +   + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ADSR.cpp b/src/ADSR.cpp index b65b756..5a12f5d 100644 --- a/src/ADSR.cpp +++ b/src/ADSR.cpp @@ -231,10 +231,10 @@ struct ADSR : Module { configButton(MANUAL_TRIGGER_PARAM, "Trigger envelope"); configParam(SHAPE_PARAM, 0.f, 1.f, 0.f, "Envelope shape"); - configParam(ATTACK_PARAM, 0.f, 1.f, 0.f, "Attack time", "s", maxStageTime / minStageTime, minStageTime); - configParam(DECAY_PARAM, 0.f, 1.f, 0.f, "Decay time", "s", maxStageTime / minStageTime, minStageTime); - configParam(SUSTAIN_PARAM, 0.f, 1.f, 0.f, "Sustain level", "%", 0.f, 100.f); - configParam(RELEASE_PARAM, 0.f, 1.f, 0.f, "Release time", "s", maxStageTime / minStageTime, minStageTime); + configParam(ATTACK_PARAM, 0.f, 1.f, 0.4f, "Attack time", "s", maxStageTime / minStageTime, minStageTime); + configParam(DECAY_PARAM, 0.f, 1.f, 0.4f, "Decay time", "s", maxStageTime / minStageTime, minStageTime); + configParam(SUSTAIN_PARAM, 0.f, 1.f, 0.5f, "Sustain level", "%", 0.f, 100.f); + configParam(RELEASE_PARAM, 0.f, 1.f, 0.4f, "Release time", "s", maxStageTime / minStageTime, minStageTime); configInput(TRIGGER_INPUT, "Trigger"); configInput(CV_ATTACK_INPUT, "Attack CV"); diff --git a/src/Burst.cpp b/src/Burst.cpp new file mode 100644 index 0000000..912609c --- /dev/null +++ b/src/Burst.cpp @@ -0,0 +1,349 @@ +#include "plugin.hpp" + +#define MAX_REPETITIONS 32 /// max number of repetitions +#define TRIGGER_TIME 0.001 + +// a tempo/clock calculator that responds to pings - this sets the base tempo, multiplication/division of +// this tempo occurs in the BurstEngine +struct PingableClock { + + dsp::Timer timer; // time the gap between pings + dsp::PulseGenerator clockTimer; // counts down from tempo length to zero + dsp::BooleanTrigger clockExpiry; // checks for when the clock timer runs out + + float pingDuration = 0.5f; // used for calculating and updating tempo (default 2Hz / 120 bpm) + float tempo = 0.5f; // actual current tempo of clock + + PingableClock() { + clockTimer.trigger(tempo); + } + + void process(bool pingRecieved, float sampleTime) { + timer.process(sampleTime); + + bool clockRestarted = false; + + if (pingRecieved) { + + bool tempoShouldBeUpdated = true; + float duration = timer.getTime(); + + // if the ping was unusually different to last time + bool outlier = duration > (pingDuration * 2) || duration < (pingDuration / 2); + // if there is a previous estimate of tempo, but it's an outlier + if ((pingDuration && outlier)) { + // don't calculate tempo from this; prime so future pings will update + tempoShouldBeUpdated = false; + pingDuration = 0; + } + else { + pingDuration = duration; + } + timer.reset(); + + if (tempoShouldBeUpdated) { + // if the tempo should be updated, do so + tempo = pingDuration; + clockRestarted = true; + } + } + + // we restart the clock if a) a new valid ping arrived OR b) the current clock expired + clockRestarted = clockExpiry.process(!clockTimer.process(sampleTime)) || clockRestarted; + if (clockRestarted) { + clockTimer.reset(); + clockTimer.trigger(tempo); + } + } + + bool isTempoOutHigh() { + // give a 1ms pulse as tempo out + return clockTimer.remaining > tempo - TRIGGER_TIME; + } +}; + +// engine that generates a burst when triggered +struct BurstEngine { + + dsp::PulseGenerator eocOutput; // for generating EOC trigger + dsp::PulseGenerator burstOutput; // for generating triggers for each occurance of the burst + dsp::Timer burstTimer; // for timing how far through the current burst we are + + float timings[MAX_REPETITIONS + 1] = {}; // store timings (calculated once on burst trigger) + + int triggersOccurred = 0; // how many triggers have been + int triggersRequested = 0; // how many bursts have been requested (fixed over course of burst) + bool active = true; // is there a burst active + bool wasInhibited = false; // was this burst inhibited (i.e. just the first trigger sent) + + std::tuple process(float sampleTime) { + + if (active) { + burstTimer.process(sampleTime); + } + + bool eocTriggered = false; + if (burstTimer.time > timings[triggersOccurred]) { + if (triggersOccurred < triggersRequested) { + burstOutput.reset(); + burstOutput.trigger(TRIGGER_TIME); + } + else if (triggersOccurred == triggersRequested) { + eocOutput.reset(); + eocOutput.trigger(TRIGGER_TIME); + active = false; + eocTriggered = true; + } + triggersOccurred++; + } + + const float burstOut = burstOutput.process(sampleTime); + // NOTE: we don't get EOC if the burst was inhibited + const float eocOut = eocOutput.process(sampleTime) * !wasInhibited; + return std::make_tuple(burstOut, eocOut, eocTriggered); + } + + void trigger(int numBursts, int multDiv, float baseTimeWindow, float distribution, bool inhibitBurst, bool includeOriginalTrigger) { + + active = true; + wasInhibited = inhibitBurst; + + // the window in which the burst fits is a multiple (or division) of the base tempo + int divisions = multDiv + (multDiv > 0 ? 1 : multDiv < 0 ? -1 : 0); // skip 2/-2 + float actualTimeWindow = baseTimeWindow; + if (divisions > 0) { + actualTimeWindow = baseTimeWindow * divisions; + } + else if (divisions < 0) { + actualTimeWindow = baseTimeWindow / (-divisions); + } + + // calculate the times at which triggers should fire, will be skewed by distribution + const float power = 1 + std::abs(distribution) * 2; + for (int i = 0; i <= numBursts; ++i) { + if (distribution >= 0) { + timings[i] = actualTimeWindow * std::pow((float)i / numBursts, power); + } + else { + timings[i] = actualTimeWindow * std::pow((float)i / numBursts, 1 / power); + } + } + + triggersOccurred = includeOriginalTrigger ? 0 : 1; + triggersRequested = inhibitBurst ? 1 : numBursts; + burstTimer.reset(); + } +}; + +struct Burst : Module { + enum ParamIds { + CYCLE_PARAM, + QUANTITY_PARAM, + TRIGGER_PARAM, + QUANTITY_CV_PARAM, + DISTRIBUTION_PARAM, + TIME_PARAM, + PROBABILITY_PARAM, + NUM_PARAMS + }; + enum InputIds { + QUANTITY_INPUT, + DISTRIBUTION_INPUT, + PING_INPUT, + TIME_INPUT, + PROBABILITY_INPUT, + TRIGGER_INPUT, + NUM_INPUTS + }; + enum OutputIds { + TEMPO_OUTPUT, + EOC_OUTPUT, + OUT_OUTPUT, + NUM_OUTPUTS + }; + enum LightIds { + ENUMS(QUANTITY_LIGHTS, 16), + TEMPO_LIGHT, + EOC_LIGHT, + OUT_LIGHT, + NUM_LIGHTS + }; + + + dsp::SchmittTrigger pingTrigger; // for detecting Ping in + dsp::SchmittTrigger triggTrigger; // for detecting Trigg in + dsp::BooleanTrigger buttonTrigger; // for detecting when the trigger button is pressed + dsp::ClockDivider ledUpdate; // for only updating LEDs every N samples + const int ledUpdateRate = 16; // LEDs updated every N = 16 samples + + PingableClock pingableClock; + BurstEngine burstEngine; + bool includeOriginalTrigger = true; + + Burst() { + config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS); + configSwitch(Burst::CYCLE_PARAM, 0.0, 1.0, 0.0, "Mode", {"One-shot", "Cycle"}); + auto quantityParam = configParam(Burst::QUANTITY_PARAM, 1, MAX_REPETITIONS, 4, "Number of bursts"); + quantityParam->snapEnabled = true; + configButton(Burst::TRIGGER_PARAM, "Manual Trigger"); + configParam(Burst::QUANTITY_CV_PARAM, 0.0, 1.0, 1.0, "Quantity CV"); + configParam(Burst::DISTRIBUTION_PARAM, -1.0, 1.0, 0.0, "Distribution"); + auto timeParam = configParam(Burst::TIME_PARAM, -4.0, 4.0, 0.0, "Time Division/Multiplication"); + timeParam->snapEnabled = true; + configParam(Burst::PROBABILITY_PARAM, 0.0, 1.0, 0.0, "Probability", "%", 0.f, -100, 100.); + + configInput(QUANTITY_INPUT, "Quantity CV"); + configInput(DISTRIBUTION_INPUT, "Distribution"); + configInput(PING_INPUT, "Ping"); + configInput(TIME_INPUT, "Time Division/Multiplication"); + configInput(PROBABILITY_INPUT, "Probability"); + configInput(TRIGGER_INPUT, "Trigger"); + + ledUpdate.setDivision(ledUpdateRate); + } + + void process(const ProcessArgs& args) override { + + const bool pingReceived = pingTrigger.process(inputs[PING_INPUT].getVoltage()); + pingableClock.process(pingReceived, args.sampleTime); + + if (ledUpdate.process()) { + updateLEDRing(args); + } + + const float quantityCV = params[QUANTITY_CV_PARAM].getValue() * clamp(inputs[QUANTITY_INPUT].getVoltage(), -5.0, +10.f) / 5.f; + const int quantity = clamp((int)(params[QUANTITY_PARAM].getValue() + std::round(16 * quantityCV)), 1, MAX_REPETITIONS); + + const bool loop = params[CYCLE_PARAM].getValue(); + + const float divMultCV = 4.0 * inputs[TIME_INPUT].getVoltage() / 10.f; + const int divMult = -clamp((int)(divMultCV + params[TIME_PARAM].getValue()), -4, +4); + + const float distributionCV = inputs[DISTRIBUTION_INPUT].getVoltage() / 10.f; + const float distribution = clamp(distributionCV + params[DISTRIBUTION_PARAM].getValue(), -1.f, +1.f); + + const bool triggerInputTriggered = triggTrigger.process(inputs[TRIGGER_INPUT].getVoltage()); + const bool triggerButtonTriggered = buttonTrigger.process(params[TRIGGER_PARAM].getValue()); + const bool startBurst = triggerInputTriggered || triggerButtonTriggered; + + if (startBurst) { + const float prob = clamp(params[PROBABILITY_PARAM].getValue() + inputs[PROBABILITY_INPUT].getVoltage() / 10.f, 0.f, 1.f); + const bool inhibitBurst = rack::random::uniform() < prob; + + // remember to do at current tempo + burstEngine.trigger(quantity, divMult, pingableClock.tempo, distribution, inhibitBurst, includeOriginalTrigger); + } + + float burstOut, eocOut; + bool eoc; + std::tie(burstOut, eocOut, eoc) = burstEngine.process(args.sampleTime); + + // if the burst has finished, we can also re-trigger + if (eoc && loop) { + const float prob = clamp(params[PROBABILITY_PARAM].getValue() + inputs[PROBABILITY_INPUT].getVoltage() / 10.f, 0.f, 1.f); + const bool inhibitBurst = rack::random::uniform() < prob; + + // remember to do at current tempo + burstEngine.trigger(quantity, divMult, pingableClock.tempo, distribution, inhibitBurst, includeOriginalTrigger); + } + + const bool tempoOutHigh = pingableClock.isTempoOutHigh(); + outputs[TEMPO_OUTPUT].setVoltage(10.f * tempoOutHigh); + lights[TEMPO_LIGHT].setBrightnessSmooth(tempoOutHigh, args.sampleTime); + + outputs[OUT_OUTPUT].setVoltage(10.f * burstOut); + lights[OUT_LIGHT].setBrightnessSmooth(burstOut, args.sampleTime); + + outputs[EOC_OUTPUT].setVoltage(10.f * eocOut); + lights[EOC_LIGHT].setBrightnessSmooth(eocOut, args.sampleTime); + } + + void updateLEDRing(const ProcessArgs& args) { + int activeLed; + if (burstEngine.active) { + activeLed = (burstEngine.triggersOccurred - 1) % 16; + } + else { + activeLed = (((int) params[QUANTITY_PARAM].getValue() - 1) % 16); + } + for (int i = 0; i < 16; ++i) { + lights[QUANTITY_LIGHTS + i].setBrightnessSmooth(i == activeLed, args.sampleTime * ledUpdateRate); + } + } + + json_t* dataToJson() override { + json_t* rootJ = json_object(); + json_object_set_new(rootJ, "includeOriginalTrigger", json_boolean(includeOriginalTrigger)); + + return rootJ; + } + + void dataFromJson(json_t* rootJ) override { + json_t* includeOriginalTriggerJ = json_object_get(rootJ, "includeOriginalTrigger"); + if (includeOriginalTriggerJ) { + includeOriginalTrigger = json_boolean_value(includeOriginalTriggerJ); + } + } +}; + + +struct BurstWidget : ModuleWidget { + BurstWidget(Burst* module) { + setModule(module); + setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/panels/Burst.svg"))); + + addChild(createWidget(Vec(15, 0))); + addChild(createWidget(Vec(15, 365))); + + addParam(createParam(mm2px(Vec(28.44228, 10.13642)), module, Burst::CYCLE_PARAM)); + addParam(createParam(mm2px(Vec(9.0322, 16.21467)), module, Burst::QUANTITY_PARAM)); + addParam(createParam(mm2px(Vec(28.43253, 29.6592)), module, Burst::TRIGGER_PARAM)); + addParam(createParam(mm2px(Vec(17.26197, 41.95461)), module, Burst::QUANTITY_CV_PARAM)); + addParam(createParam(mm2px(Vec(22.85243, 58.45676)), module, Burst::DISTRIBUTION_PARAM)); + addParam(createParam(mm2px(Vec(28.47229, 74.91607)), module, Burst::TIME_PARAM)); + addParam(createParam(mm2px(Vec(22.75115, 91.35201)), module, Burst::PROBABILITY_PARAM)); + + addInput(createInput(mm2px(Vec(2.02153, 42.27628)), module, Burst::QUANTITY_INPUT)); + addInput(createInput(mm2px(Vec(7.90118, 58.74959)), module, Burst::DISTRIBUTION_INPUT)); + addInput(createInput(mm2px(Vec(2.05023, 75.25163)), module, Burst::PING_INPUT)); + addInput(createInput(mm2px(Vec(13.7751, 75.23049)), module, Burst::TIME_INPUT)); + addInput(createInput(mm2px(Vec(7.89545, 91.66642)), module, Burst::PROBABILITY_INPUT)); + addInput(createInput(mm2px(Vec(1.11155, 109.30346)), module, Burst::TRIGGER_INPUT)); + + addOutput(createOutput(mm2px(Vec(11.07808, 109.30346)), module, Burst::TEMPO_OUTPUT)); + addOutput(createOutput(mm2px(Vec(21.08452, 109.32528)), module, Burst::EOC_OUTPUT)); + addOutput(createOutput(mm2px(Vec(31.01113, 109.30346)), module, Burst::OUT_OUTPUT)); + + addChild(createLight>(mm2px(Vec(14.03676, 9.98712)), module, Burst::QUANTITY_LIGHTS + 0)); + addChild(createLight>(mm2px(Vec(18.35846, 10.85879)), module, Burst::QUANTITY_LIGHTS + 1)); + addChild(createLight>(mm2px(Vec(22.05722, 13.31827)), module, Burst::QUANTITY_LIGHTS + 2)); + addChild(createLight>(mm2px(Vec(24.48707, 16.96393)), module, Burst::QUANTITY_LIGHTS + 3)); + addChild(createLight>(mm2px(Vec(25.38476, 21.2523)), module, Burst::QUANTITY_LIGHTS + 4)); + addChild(createLight>(mm2px(Vec(24.48707, 25.5354)), module, Burst::QUANTITY_LIGHTS + 5)); + addChild(createLight>(mm2px(Vec(22.05722, 29.16905)), module, Burst::QUANTITY_LIGHTS + 6)); + addChild(createLight>(mm2px(Vec(18.35846, 31.62236)), module, Burst::QUANTITY_LIGHTS + 7)); + addChild(createLight>(mm2px(Vec(14.03676, 32.48786)), module, Burst::QUANTITY_LIGHTS + 8)); + addChild(createLight>(mm2px(Vec(9.74323, 31.62236)), module, Burst::QUANTITY_LIGHTS + 9)); + addChild(createLight>(mm2px(Vec(6.10149, 29.16905)), module, Burst::QUANTITY_LIGHTS + 10)); + addChild(createLight>(mm2px(Vec(3.68523, 25.5354)), module, Burst::QUANTITY_LIGHTS + 11)); + addChild(createLight>(mm2px(Vec(2.85312, 21.2523)), module, Burst::QUANTITY_LIGHTS + 12)); + addChild(createLight>(mm2px(Vec(3.68523, 16.96393)), module, Burst::QUANTITY_LIGHTS + 13)); + addChild(createLight>(mm2px(Vec(6.10149, 13.31827)), module, Burst::QUANTITY_LIGHTS + 14)); + addChild(createLight>(mm2px(Vec(9.74323, 10.85879)), module, Burst::QUANTITY_LIGHTS + 15)); + addChild(createLight>(mm2px(Vec(14.18119, 104.2831)), module, Burst::TEMPO_LIGHT)); + addChild(createLight>(mm2px(Vec(24.14772, 104.2831)), module, Burst::EOC_LIGHT)); + addChild(createLight>(mm2px(Vec(34.11425, 104.2831)), module, Burst::OUT_LIGHT)); + } + + void appendContextMenu(Menu* menu) override { + Burst* module = dynamic_cast(this->module); + assert(module); + + menu->addChild(new MenuSeparator()); + menu->addChild(createBoolPtrMenuItem("Include original trigger in output", "", &module->includeOriginalTrigger)); + } +}; + + +Model* modelBurst = createModel("Burst"); + diff --git a/src/ChowDSP.hpp b/src/ChowDSP.hpp index 873a4d9..4d7cd6d 100644 --- a/src/ChowDSP.hpp +++ b/src/ChowDSP.hpp @@ -225,7 +225,7 @@ typedef TBiquadFilter<> BiquadFilter; Currently uses an 2*N-th order Butterworth filter. source: https://github.com/jatinchowdhury18/ChowDSP-VCV/blob/master/src/shared/AAFilter.hpp */ -template +template class AAFilter { public: AAFilter() = default; @@ -255,10 +255,10 @@ class AAFilter { auto Qs = calculateButterQs(2 * N); for (int i = 0; i < N; ++i) - filters[i].setParameters(BiquadFilter::Type::LOWPASS, fc / (osRatio * sampleRate), Qs[i], 1.0f); + filters[i].setParameters(TBiquadFilter::Type::LOWPASS, fc / (osRatio * sampleRate), Qs[i], 1.0f); } - inline float process(float x) noexcept { + inline T process(T x) noexcept { for (int i = 0; i < N; ++i) x = filters[i].process(x); @@ -266,14 +266,16 @@ class AAFilter { } private: - BiquadFilter filters[N]; + TBiquadFilter filters[N]; }; + /** * Base class for oversampling of any order * source: https://github.com/jatinchowdhury18/ChowDSP-VCV/blob/master/src/shared/oversampling.hpp */ +template class BaseOversampling { public: BaseOversampling() = default; @@ -283,13 +285,13 @@ class BaseOversampling { virtual void reset(float /*baseSampleRate*/) = 0; /** Upsample a single input sample and update the oversampled buffer */ - virtual void upsample(float) noexcept = 0; + virtual void upsample(T) noexcept = 0; /** Output a downsampled output sample from the current oversampled buffer */ - virtual float downsample() noexcept = 0; + virtual T downsample() noexcept = 0; /** Returns a pointer to the oversampled buffer */ - virtual float* getOSBuffer() noexcept = 0; + virtual T* getOSBuffer() noexcept = 0; }; @@ -305,8 +307,8 @@ class BaseOversampling { float y = oversample.downsample(); @endcode */ -template -class Oversampling : public BaseOversampling { +template +class Oversampling : public BaseOversampling { public: Oversampling() = default; virtual ~Oversampling() {} @@ -317,7 +319,7 @@ class Oversampling : public BaseOversampling { std::fill(osBuffer, &osBuffer[ratio], 0.0f); } - inline void upsample(float x) noexcept override { + inline void upsample(T x) noexcept override { osBuffer[0] = ratio * x; std::fill(&osBuffer[1], &osBuffer[ratio], 0.0f); @@ -325,25 +327,26 @@ class Oversampling : public BaseOversampling { osBuffer[k] = aiFilter.process(osBuffer[k]); } - inline float downsample() noexcept override { - float y = 0.0f; + inline T downsample() noexcept override { + T y = 0.0f; for (int k = 0; k < ratio; k++) y = aaFilter.process(osBuffer[k]); return y; } - inline float* getOSBuffer() noexcept override { + inline T* getOSBuffer() noexcept override { return osBuffer; } - float osBuffer[ratio]; + T osBuffer[ratio]; private: - AAFilter aaFilter; // anti-aliasing filter - AAFilter aiFilter; // anti-imaging filter + AAFilter aaFilter; // anti-aliasing filter + AAFilter aiFilter; // anti-imaging filter }; +typedef Oversampling<1, 4, simd::float_4> OversamplingSIMD; /** @@ -362,7 +365,7 @@ class Oversampling : public BaseOversampling { source (modified): https://github.com/jatinchowdhury18/ChowDSP-VCV/blob/master/src/shared/VariableOversampling.hpp */ -template +template class VariableOversampling { public: VariableOversampling() = default; @@ -384,17 +387,17 @@ class VariableOversampling { } /** Upsample a single input sample and update the oversampled buffer */ - inline void upsample(float x) noexcept { + inline void upsample(T x) noexcept { oss[osIdx]->upsample(x); } /** Output a downsampled output sample from the current oversampled buffer */ - inline float downsample() noexcept { + inline T downsample() noexcept { return oss[osIdx]->downsample(); } /** Returns a pointer to the oversampled buffer */ - inline float* getOSBuffer() noexcept { + inline T* getOSBuffer() noexcept { return oss[osIdx]->getOSBuffer(); } @@ -411,12 +414,12 @@ class VariableOversampling { int osIdx = 0; - Oversampling < 1 << 0, filtN > os0; // 1x - Oversampling < 1 << 1, filtN > os1; // 2x - Oversampling < 1 << 2, filtN > os2; // 4x - Oversampling < 1 << 3, filtN > os3; // 8x - Oversampling < 1 << 4, filtN > os4; // 16x - BaseOversampling* oss[NumOS] = { &os0, &os1, &os2, &os3, &os4 }; + Oversampling < 1 << 0, filtN, T > os0; // 1x + Oversampling < 1 << 1, filtN, T > os1; // 2x + Oversampling < 1 << 2, filtN, T > os2; // 4x + Oversampling < 1 << 3, filtN, T > os3; // 8x + Oversampling < 1 << 4, filtN, T > os4; // 16x + BaseOversampling* oss[NumOS] = { &os0, &os1, &os2, &os3, &os4 }; }; } // namespace chowdsp diff --git a/src/MidiThing.cpp b/src/MidiThing.cpp new file mode 100644 index 0000000..18340b5 --- /dev/null +++ b/src/MidiThing.cpp @@ -0,0 +1,804 @@ +#include "plugin.hpp" + + +/*! \brief Decode System Exclusive messages. + SysEx messages are encoded to guarantee transmission of data bytes higher than + 127 without breaking the MIDI protocol. Use this static method to reassemble + your received message. + \param inSysEx The SysEx data received from MIDI in. + \param outData The output buffer where to store the decrypted message. + \param inLength The length of the input buffer. + \param inFlipHeaderBits True for Korg and other who store MSB in reverse order + \return The length of the output buffer. + @see encodeSysEx @see getSysExArrayLength + Code inspired from Ruin & Wesen's SysEx encoder/decoder - http://ruinwesen.com + */ +unsigned decodeSysEx(const uint8_t* inSysEx, + uint8_t* outData, + unsigned inLength, + bool inFlipHeaderBits) { + unsigned count = 0; + uint8_t msbStorage = 0; + uint8_t byteIndex = 0; + + for (unsigned i = 0; i < inLength; ++i) { + if ((i % 8) == 0) { + msbStorage = inSysEx[i]; + byteIndex = 6; + } + else { + const uint8_t body = inSysEx[i]; + const uint8_t shift = inFlipHeaderBits ? 6 - byteIndex : byteIndex; + const uint8_t msb = uint8_t(((msbStorage >> shift) & 1) << 7); + byteIndex--; + outData[count++] = msb | body; + } + } + return count; +} + +struct RoundRobinProcessor { + // if a channel (0 - 11) should be updated, return it's index, otherwise return -1 + int process(float sampleTime, float period, int numActiveChannels) { + + if (numActiveChannels == 0 || period <= 0) { + return -1; + } + + time += sampleTime; + + if (time > period) { + time -= period; + + // special case: when there's only one channel, the below logic (which looks for when active channel changes) + // wont fire. as we've completed a period, return an "update channel 0" value + if (numActiveChannels == 1) { + return 0; + } + } + + int currentActiveChannel = numActiveChannels * time / period; + + if (currentActiveChannel != previousActiveChannel) { + previousActiveChannel = currentActiveChannel; + return currentActiveChannel; + } + + // if we've got this far, no updates needed (-1) + return -1; + } +private: + float time = 0.f; + int previousActiveChannel = -1; +}; + + +struct MidiThing : Module { + enum ParamId { + REFRESH_PARAM, + PARAMS_LEN + }; + enum InputId { + A1_INPUT, + B1_INPUT, + C1_INPUT, + A2_INPUT, + B2_INPUT, + C2_INPUT, + A3_INPUT, + B3_INPUT, + C3_INPUT, + A4_INPUT, + B4_INPUT, + C4_INPUT, + INPUTS_LEN + }; + enum OutputId { + OUTPUTS_LEN + }; + enum LightId { + LIGHTS_LEN + }; + /// Port mode + enum PORTMODE_t { + NOPORTMODE = 0, + MODE10V, + MODEPN5V, + MODENEG10V, + MODE8V, + MODE5V, + + LASTPORTMODE + }; + + const char* cfgPortModeNames[7] = { + "No Mode", + "0/10v", + "-5/5v", + "-10/0v", + "0/8v", + "0/5v", + "" + }; + + const std::vector updateRates = {250., 500., 1000., 2000., 4000., 8000.}; + const std::vector updateRateNames = {"250 Hz (fewest active channels, slowest, lowest-cpu)", "500 Hz", "1 kHz", "2 kHz", "4 kHz", + "8 kHz (most active channels, fast, highest-cpu)" + }; + int updateRateIdx = 2; + + // use Pre-def 4 for bridge mode + const static int VCV_BRIDGE_PREDEF = 4; + + midi::Output midiOut; + RoundRobinProcessor roundRobinProcessor; + + MidiThing() { + config(PARAMS_LEN, INPUTS_LEN, OUTPUTS_LEN, LIGHTS_LEN); + configButton(REFRESH_PARAM, ""); + + for (int i = 0; i < NUM_INPUTS; ++i) { + portModes[i] = MODE10V; + configInput(A1_INPUT + i, string::f("Port %d", i + 1)); + } + } + + void onReset() override { + midiOut.reset(); + + } + + void requestAllChannelsParamsOverSysex() { + for (int row = 0; row < 4; ++row) { + for (int col = 0; col < 3; ++col) { + const int PORT_CONFIG = 2; + requestParamOverSysex(row, col, PORT_CONFIG); + } + } + } + + // request that MidiThing loads a pre-defined template, 1-4 + void setPredef(uint8_t predef) { + predef = clamp(predef, 1, 4); + midi::Message msg; + msg.bytes.resize(8); + // Midi spec is zeroo indexed + uint8_t predefToSend = predef - 1; + msg.bytes = {0xF0, 0x7D, 0x17, 0x00, 0x00, 0x02, 0x00, predefToSend, 0xF7}; + midiOut.setChannel(0); + midiOut.sendMessage(msg); + // DEBUG("Predef %d msg request sent: %s", predef, msg.toString().c_str()); + } + + void setMidiMergeViaSysEx(bool mergeOn) { + midi::Message msg; + msg.bytes.resize(8); + + msg.bytes = {0xF0, 0x7D, 0x19, 0x00, 0x05, 0x02, 0x00, (uint8_t) mergeOn, 0xF7}; + midiOut.setChannel(0); + midiOut.sendMessage(msg); + // DEBUG("Predef %d msg request sent: %s", mergeOn, msg.toString().c_str()); + } + + + void setVoltageModeOnHardware(uint8_t row, uint8_t col, PORTMODE_t outputMode_) { + uint8_t port = 3 * row + col; + portModes[port] = outputMode_; + + midi::Message msg; + msg.bytes.resize(8); + // F0 7D 17 2n 02 02 00 0m F7 + // Where n = 0 based port number + // and m is the volt output mode to select from: + msg.bytes = {0xF0, 0x7D, 0x17, static_cast(32 + port), 0x02, 0x02, 0x00, (uint8_t) portModes[port], 0xF7}; + midiOut.sendMessage(msg); + // DEBUG("Voltage mode msg sent: port %d (%d), mode %d", port, static_cast(32 + port), portModes[port]); + } + + void setVoltageModeOnHardware(uint8_t row, uint8_t col) { + setVoltageModeOnHardware(row, col, portModes[3 * row + col]); + } + + void syncVcvStateToHardware() { + for (int row = 0; row < 4; ++row) { + for (int col = 0; col < 3; ++col) { + setVoltageModeOnHardware(row, col); + } + } + } + + + midi::InputQueue inputQueue; + void requestParamOverSysex(uint8_t row, uint8_t col, uint8_t mode) { + + midi::Message msg; + msg.bytes.resize(8); + // F0 7D 17 00 01 03 00 nm pp F7 + uint8_t port = 3 * row + col; + //Where n is: + // 0 = Full configuration request. The module will send only pre def, port functions and modified parameters + // 2 = Send Port configuration + // 4 = Send MIDI Channel configuration + // 6 = Send Voice Configuration + + uint8_t n = mode * 16; + uint8_t m = port; // element number: 0-11 port number, 1-16 channel or voice number + uint8_t pp = 2; + msg.bytes = {0xF0, 0x7D, 0x17, 0x00, 0x01, 0x03, 0x00, static_cast(n + m), pp, 0xF7}; + midiOut.sendMessage(msg); + // DEBUG("API request mode msg sent: port %d, pp %s", port, msg.toString().c_str()); + } + + int getVoltageMode(uint8_t row, uint8_t col) { + // -1 because menu is zero indexed but enum is not + int channel = clamp(3 * row + col, 0, NUM_INPUTS - 1); + return portModes[channel] - 1; + } + + const static int NUM_INPUTS = 12; + bool isClipping[NUM_INPUTS] = {}; + + bool checkIsVoltageWithinRange(uint8_t channel, float voltage) { + const float tol = 0.001; + switch (portModes[channel]) { + case MODE10V: return 0 - tol < voltage && voltage < 10 + tol; + case MODEPN5V: return -5 - tol < voltage && voltage < 5 + tol; + case MODENEG10V: return -10 - tol < voltage && voltage < 0 + tol; + case MODE8V: return 0 - tol < voltage && voltage < 8 + tol; + case MODE5V: return 0 - tol < voltage && voltage < 5 + tol; + default: return false; + } + } + + uint16_t rescaleVoltageForChannel(uint8_t channel, float voltage) { + switch (portModes[channel]) { + case MODE10V: return rescale(clamp(voltage, 0.f, 10.f), 0.f, +10.f, 0, 16383); + case MODEPN5V: return rescale(clamp(voltage, -5.f, 5.f), -5.f, +5.f, 0, 16383); + case MODENEG10V: return rescale(clamp(voltage, -10.f, 0.f), -10.f, +0.f, 0, 16383); + case MODE8V: return rescale(clamp(voltage, 0.f, 8.f), 0.f, +8.f, 0, 16383); + case MODE5V: return rescale(clamp(voltage, 0.f, 5.f), 0.f, +5.f, 0, 16383); + default: return 0; + } + } + + // one way sync (VCV -> hardware) for now + void doSync() { + // switch to VCV template (predef 4) + setPredef(4); + + // disable MIDI merge (otherwise large sample rates will not work) + setMidiMergeViaSysEx(false); + + // send full VCV config + syncVcvStateToHardware(); + + // disabled for now, but this would request what state the hardware is in + if (parseSysExMessagesFromHardware) { + requestAllChannelsParamsOverSysex(); + } + } + + // debug only + bool parseSysExMessagesFromHardware = false; + int numActiveChannels = 0; + dsp::BooleanTrigger buttonTrigger; + dsp::Timer rateLimiterTimer; + PORTMODE_t portModes[NUM_INPUTS] = {}; + void process(const ProcessArgs& args) override { + + if (buttonTrigger.process(params[REFRESH_PARAM].getValue())) { + doSync(); + } + + // disabled for now, but this is how VCV would read SysEx coming from the hardware (if requested above) + if (parseSysExMessagesFromHardware) { + midi::Message msg; + uint8_t outData[32] = {}; + while (inputQueue.tryPop(&msg, args.frame)) { + + uint8_t outLen = decodeSysEx(&msg.bytes[0], outData, msg.bytes.size(), false); + if (outLen > 3) { + + int channel = (outData[2] & 0x0f) >> 0; + + if (channel >= 0 && channel < NUM_INPUTS) { + if (outData[outLen - 1] < LASTPORTMODE) { + portModes[channel] = (PORTMODE_t) outData[outLen - 1]; + } + } + } + } + } + + std::vector activeChannels; + for (int c = 0; c < NUM_INPUTS; ++c) { + if (inputs[A1_INPUT + c].isConnected()) { + activeChannels.push_back(c); + } + } + numActiveChannels = activeChannels.size(); + // we're done if no channels are active + if (numActiveChannels == 0) { + return; + } + + //DEBUG("updateRateIdx: %d", updateRateIdx); + const float updateRateHz = updateRates[updateRateIdx]; + //DEBUG("updateRateHz: %f", updateRateHz); + const int maxCCMessagesPerSecondPerChannel = updateRateHz / numActiveChannels; + + // MIDI baud rate is 31250 b/s, or 3125 B/s. + // CC messages are 3 bytes, so we can send a maximum of 1041 CC messages per second. + // The refresh rate period (i.e. how often we can send X channels of data is: + const float rateLimiterPeriod = 1.f / maxCCMessagesPerSecondPerChannel; + + // this returns -1 if no channel should be updated, or the index of the channel that should be updated + // it distributes update times in a round robin fashion + int channelIdxToUpdate = roundRobinProcessor.process(args.sampleTime, rateLimiterPeriod, numActiveChannels); + + if (channelIdxToUpdate >= 0 && channelIdxToUpdate < numActiveChannels) { + int c = activeChannels[channelIdxToUpdate]; + + const float channelVoltage = inputs[A1_INPUT + c].getVoltage(); + uint16_t pw = rescaleVoltageForChannel(c, channelVoltage); + isClipping[c] = !checkIsVoltageWithinRange(c, channelVoltage); + midi::Message m; + m.setStatus(0xe); + m.setNote(pw & 0x7f); + m.setValue((pw >> 7) & 0x7f); + m.setFrame(args.frame); + + midiOut.setChannel(c); + midiOut.sendMessage(m); + } + } + + + json_t* dataToJson() override { + json_t* rootJ = json_object(); + json_object_set_new(rootJ, "midiOutput", midiOut.toJson()); + json_object_set_new(rootJ, "inputQueue", inputQueue.toJson()); + json_object_set_new(rootJ, "updateRateIdx", json_integer(updateRateIdx)); + + for (int c = 0; c < NUM_INPUTS; ++c) { + json_object_set_new(rootJ, string::f("portMode%d", c).c_str(), json_integer(portModes[c])); + } + + return rootJ; + } + + void dataFromJson(json_t* rootJ) override { + json_t* midiOutputJ = json_object_get(rootJ, "midiOutput"); + if (midiOutputJ) { + midiOut.fromJson(midiOutputJ); + } + + json_t* midiInputQueueJ = json_object_get(rootJ, "inputQueue"); + if (midiInputQueueJ) { + inputQueue.fromJson(midiInputQueueJ); + } + + json_t* updateRateIdxJ = json_object_get(rootJ, "updateRateIdx"); + if (updateRateIdxJ) { + updateRateIdx = json_integer_value(updateRateIdxJ); + } + + for (int c = 0; c < NUM_INPUTS; ++c) { + json_t* portModeJ = json_object_get(rootJ, string::f("portMode%d", c).c_str()); + if (portModeJ) { + portModes[c] = (PORTMODE_t)json_integer_value(portModeJ); + } + } + + // requestAllChannelsParamsOverSysex(); + syncVcvStateToHardware(); + } +}; + +struct MidiThingPort : BefacoInputPort { + int row = 0, col = 0; + MidiThing* module; + + void appendContextMenu(Menu* menu) override { + + menu->addChild(new MenuSeparator()); + std::string label = string::f("Voltage Mode Port %d", 3 * row + col + 1); + + menu->addChild(createIndexSubmenuItem(label, + {"0 to 10v", "-5 to 5v", "-10 to 0v", "0 to 8v", "0 to 5v"}, + [ = ]() { + return module->getVoltageMode(row, col); + }, + [ = ](int modeIdx) { + MidiThing::PORTMODE_t mode = (MidiThing::PORTMODE_t)(modeIdx + 1); + module->setVoltageModeOnHardware(row, col, mode); + } + )); + + /* + menu->addChild(createIndexSubmenuItem("Get Port Info", + {"Full", "Port", "MIDI", "Voice"}, + [ = ]() { + return -1; + }, + [ = ](int mode) { + module->requestParamOverSysex(row, col, 2 * mode); + } + )); + */ + } +}; + +// dervied from https://github.com/countmodula/VCVRackPlugins/blob/v2.0.0/src/components/CountModulaLEDDisplay.hpp +struct LEDDisplay : LightWidget { + float fontSize = 9; + Vec textPos = Vec(1, 13); + int numChars = 7; + int row = 0, col = 0; + MidiThing* module; + + LEDDisplay() { + box.size = mm2px(Vec(9.298, 5.116)); + } + + void setCentredPos(Vec pos) { + box.pos.x = pos.x - box.size.x / 2; + box.pos.y = pos.y - box.size.y / 2; + } + + void drawBackground(const DrawArgs& args) override { + // Background + NVGcolor backgroundColor = nvgRGB(0x20, 0x20, 0x20); + NVGcolor borderColor = nvgRGB(0x10, 0x10, 0x10); + nvgBeginPath(args.vg); + nvgRoundedRect(args.vg, 0.0, 0.0, box.size.x, box.size.y, 2.0); + nvgFillColor(args.vg, backgroundColor); + nvgFill(args.vg); + nvgStrokeWidth(args.vg, 1.0); + nvgStrokeColor(args.vg, borderColor); + nvgStroke(args.vg); + } + + void drawLight(const DrawArgs& args) override { + // Background + NVGcolor backgroundColor = nvgRGB(0x20, 0x20, 0x20); + NVGcolor borderColor = nvgRGB(0x10, 0x10, 0x10); + NVGcolor textColor = nvgRGB(0xff, 0x10, 0x10); + + nvgBeginPath(args.vg); + nvgRoundedRect(args.vg, 0.0, 0.0, box.size.x, box.size.y, 2.0); + nvgFillColor(args.vg, backgroundColor); + nvgFill(args.vg); + nvgStrokeWidth(args.vg, 1.0); + + if (module) { + const bool isClipping = module->isClipping[col + row * 3]; + if (isClipping) { + borderColor = nvgRGB(0xff, 0x20, 0x20); + } + } + + nvgStrokeColor(args.vg, borderColor); + nvgStroke(args.vg); + + std::shared_ptr font = APP->window->loadFont(asset::plugin(pluginInstance, "res/fonts/miso.otf")); + + if (font && font->handle >= 0) { + + std::string text = "?-?v"; // fallback if module not yet defined + if (module) { + text = module->cfgPortModeNames[module->getVoltageMode(row, col) + 1]; + } + char buffer[numChars + 1]; + int l = text.size(); + if (l > numChars) + l = numChars; + + nvgGlobalTint(args.vg, color::WHITE); + + text.copy(buffer, l); + buffer[l] = '\0'; + + nvgFontSize(args.vg, fontSize); + nvgFontFaceId(args.vg, font->handle); + nvgFillColor(args.vg, textColor); + nvgTextAlign(args.vg, NVG_ALIGN_CENTER | NVG_ALIGN_BOTTOM); + NVGtextRow textRow; + nvgTextBreakLines(args.vg, text.c_str(), NULL, box.size.x, &textRow, 1); + nvgTextBox(args.vg, textPos.x, textPos.y, box.size.x, textRow.start, textRow.end); + } + } + + void onButton(const ButtonEvent& e) override { + if (e.button == GLFW_MOUSE_BUTTON_RIGHT && e.action == GLFW_PRESS) { + ui::Menu* menu = createMenu(); + + menu->addChild(createMenuLabel(string::f("Voltage mode port %d:", col + 3 * row + 1))); + + const std::string labels[5] = {"0 to 10v", "-5 to 5v", "-10 to 0v", "0 to 8v", "0 to 5v"}; + + for (int i = 0; i < 5; ++i) { + menu->addChild(createCheckMenuItem(labels[i], "", + [ = ]() { + return module->getVoltageMode(row, col) == i; + }, + [ = ]() { + MidiThing::PORTMODE_t mode = (MidiThing::PORTMODE_t)(i + 1); + module->setVoltageModeOnHardware(row, col, mode); + } + )); + } + + e.consume(this); + return; + } + + LightWidget::onButton(e); + } + +}; + + +struct MidiThingWidget : ModuleWidget { + + struct LedDisplayCenterChoiceEx : LedDisplayChoice { + LedDisplayCenterChoiceEx() { + box.size = mm2px(math::Vec(0, 8.0)); + color = nvgRGB(0xf0, 0xf0, 0xf0); + bgColor = nvgRGBAf(0, 0, 0, 0); + textOffset = math::Vec(0, 16); + } + + void drawLayer(const DrawArgs& args, int layer) override { + nvgScissor(args.vg, RECT_ARGS(args.clipBox)); + if (layer == 1) { + if (bgColor.a > 0.0) { + nvgBeginPath(args.vg); + nvgRect(args.vg, 0, 0, box.size.x, box.size.y); + nvgFillColor(args.vg, bgColor); + nvgFill(args.vg); + } + + std::shared_ptr font = APP->window->loadFont(asset::plugin(pluginInstance, "res/fonts/miso.otf")); + + if (font && font->handle >= 0 && !text.empty()) { + nvgFillColor(args.vg, color); + nvgFontFaceId(args.vg, font->handle); + nvgTextLetterSpacing(args.vg, -0.6f); + nvgFontSize(args.vg, 10); + nvgTextAlign(args.vg, NVG_ALIGN_CENTER | NVG_ALIGN_BOTTOM); + NVGtextRow textRow; + nvgTextBreakLines(args.vg, text.c_str(), NULL, box.size.x, &textRow, 1); + nvgTextBox(args.vg, textOffset.x, textOffset.y, box.size.x, textRow.start, textRow.end); + } + } + nvgResetScissor(args.vg); + } + }; + + + struct MidiDriverItem : ui::MenuItem { + midi::Port* port; + int driverId; + void onAction(const event::Action& e) override { + port->setDriverId(driverId); + } + }; + + struct MidiDriverChoice : LedDisplayCenterChoiceEx { + midi::Port* port; + void onAction(const event::Action& e) override { + if (!port) + return; + createContextMenu(); + } + + virtual ui::Menu* createContextMenu() { + ui::Menu* menu = createMenu(); + menu->addChild(createMenuLabel("MIDI driver")); + for (int driverId : midi::getDriverIds()) { + MidiDriverItem* item = new MidiDriverItem; + item->port = port; + item->driverId = driverId; + item->text = midi::getDriver(driverId)->getName(); + item->rightText = CHECKMARK(item->driverId == port->driverId); + menu->addChild(item); + } + return menu; + } + + void step() override { + text = port ? port->getDriver()->getName() : ""; + if (text.empty()) { + text = "(No driver)"; + color.a = 0.5f; + } + else { + color.a = 1.f; + } + } + }; + + struct MidiDeviceItem : ui::MenuItem { + midi::Port* outPort, *inPort; + int deviceId; + void onAction(const event::Action& e) override { + outPort->setDeviceId(deviceId); + inPort->setDeviceId(deviceId); + } + }; + + struct MidiDeviceChoice : LedDisplayCenterChoiceEx { + midi::Port* outPort, *inPort; + void onAction(const event::Action& e) override { + if (!outPort || !inPort) + return; + createContextMenu(); + } + + virtual ui::Menu* createContextMenu() { + ui::Menu* menu = createMenu(); + menu->addChild(createMenuLabel("MIDI device")); + { + MidiDeviceItem* item = new MidiDeviceItem; + item->outPort = outPort; + item->inPort = inPort; + item->deviceId = -1; + item->text = "(No device)"; + item->rightText = CHECKMARK(item->deviceId == outPort->deviceId); + menu->addChild(item); + } + for (int deviceId : outPort->getDeviceIds()) { + MidiDeviceItem* item = new MidiDeviceItem; + item->outPort = outPort; + item->inPort = inPort; + item->deviceId = deviceId; + item->text = outPort->getDeviceName(deviceId); + item->rightText = CHECKMARK(item->deviceId == outPort->deviceId); + menu->addChild(item); + } + return menu; + } + + void step() override { + text = outPort ? outPort->getDeviceName(outPort->deviceId) : ""; + if (text.empty()) { + text = "(No device)"; + color.a = 0.5f; + } + else { + color.a = 1.f; + } + } + }; + + struct MidiWidget : LedDisplay { + MidiDriverChoice* driverChoice; + LedDisplaySeparator* driverSeparator; + MidiDeviceChoice* deviceChoice; + LedDisplaySeparator* deviceSeparator; + + void setMidiPorts(midi::Port* outPort, midi::Port* inPort) { + + clearChildren(); + math::Vec pos; + + MidiDriverChoice* driverChoice = createWidget(pos); + driverChoice->box.size = Vec(box.size.x, 20.f); + //driverChoice->textOffset = Vec(6.f, 14.7f); + driverChoice->color = nvgRGB(0xf0, 0xf0, 0xf0); + driverChoice->port = outPort; + + addChild(driverChoice); + pos = driverChoice->box.getBottomLeft(); + this->driverChoice = driverChoice; + + this->driverSeparator = createWidget(pos); + this->driverSeparator->box.size.x = box.size.x; + addChild(this->driverSeparator); + + MidiDeviceChoice* deviceChoice = createWidget(pos); + deviceChoice->box.size = Vec(box.size.x, 21.f); + //deviceChoice->textOffset = Vec(6.f, 14.7f); + deviceChoice->color = nvgRGB(0xf0, 0xf0, 0xf0); + deviceChoice->outPort = outPort; + deviceChoice->inPort = inPort; + addChild(deviceChoice); + pos = deviceChoice->box.getBottomLeft(); + this->deviceChoice = deviceChoice; + } + }; + + + MidiThingWidget(MidiThing* module) { + setModule(module); + setPanel(createPanel(asset::plugin(pluginInstance, "res/panels/MidiThing.svg"))); + + addChild(createWidget(Vec(RACK_GRID_WIDTH, 0))); + addChild(createWidget(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); + + MidiWidget* midiInputWidget = createWidget(Vec(1.5f, 36.4f)); //mm2px(Vec(0.5f, 10.f))); + midiInputWidget->box.size = mm2px(Vec(5.08 * 6 - 1, 13.5f)); + if (module) { + midiInputWidget->setMidiPorts(&module->midiOut, &module->inputQueue); + } + else { + midiInputWidget->setMidiPorts(nullptr, nullptr); + } + addChild(midiInputWidget); + + addParam(createParamCentered(mm2px(Vec(21.12, 57.32)), module, MidiThing::REFRESH_PARAM)); + + const float xStartLed = 0.2 + 0.628; + const float yStartLed = 28.019; + + for (int row = 0; row < 4; row++) { + for (int col = 0; col < 3; col++) { + + LEDDisplay* display = createWidget(mm2px(Vec(xStartLed + 9.751 * col, yStartLed + 5.796 * row))); + display->module = module; + display->row = row; + display->col = col; + addChild(display); + + auto input = createInputCentered(mm2px(Vec(5.08 + 10 * col, 69.77 + 14.225 * row)), module, MidiThing::A1_INPUT + 3 * row + col); + input->row = row; + input->col = col; + input->module = module; + addInput(input); + + + } + } + } + + void appendContextMenu(Menu* menu) override { + MidiThing* module = dynamic_cast(this->module); + assert(module); + + menu->addChild(new MenuSeparator()); + + menu->addChild(createSubmenuItem("Select MIDI Device", "", + [ = ](Menu * menu) { + + for (auto driverId : rack::midi::getDriverIds()) { + midi::Driver* driver = midi::getDriver(driverId); + const bool activeDriver = module->midiOut.getDriverId() == driverId; + + menu->addChild(createSubmenuItem(driver->getName(), CHECKMARK(activeDriver), + [ = ](Menu * menu) { + + for (auto deviceId : driver->getOutputDeviceIds()) { + const bool activeDevice = activeDriver && module->midiOut.getDeviceId() == deviceId; + + menu->addChild(createMenuItem(driver->getOutputDeviceName(deviceId), + CHECKMARK(activeDevice), + [ = ]() { + module->midiOut.setDriverId(driverId); + module->midiOut.setDeviceId(deviceId); + + module->inputQueue.setDriverId(driverId); + module->inputQueue.setDeviceId(deviceId); + module->inputQueue.setChannel(0); // TODO update + + module->doSync(); + + // DEBUG("Updating Output MIDI settings - driver: %s, device: %s", + // driver->getName().c_str(), driver->getOutputDeviceName(deviceId).c_str()); + })); + } + })); + } + })); + + menu->addChild(createIndexPtrSubmenuItem("All channels MIDI update rate", + module->updateRateNames, + &module->updateRateIdx)); + + float updateRate = module->updateRates[module->updateRateIdx] / module->numActiveChannels; + menu->addChild(createMenuLabel(string::f("Per-channel MIDI update rate: %.3g Hz", updateRate))); + } +}; + + +Model* modelMidiThing = createModel("MidiThingV2"); \ No newline at end of file diff --git a/src/Octaves.cpp b/src/Octaves.cpp new file mode 100644 index 0000000..e783eb2 --- /dev/null +++ b/src/Octaves.cpp @@ -0,0 +1,336 @@ +#include "plugin.hpp" +#include "ChowDSP.hpp" + +using namespace simd; + +struct Octaves : Module { + enum ParamId { + PWM_CV_PARAM, + OCTAVE_PARAM, + TUNE_PARAM, + PWM_PARAM, + RANGE_PARAM, + GAIN_01F_PARAM, + GAIN_02F_PARAM, + GAIN_04F_PARAM, + GAIN_08F_PARAM, + GAIN_16F_PARAM, + GAIN_32F_PARAM, + PARAMS_LEN + }; + enum InputId { + VOCT1_INPUT, + VOCT2_INPUT, + SYNC_INPUT, + PWM_INPUT, + GAIN_01F_INPUT, + GAIN_02F_INPUT, + GAIN_04F_INPUT, + GAIN_08F_INPUT, + GAIN_16F_INPUT, + GAIN_32F_INPUT, + INPUTS_LEN + }; + enum OutputId { + OUT_01F_OUTPUT, + OUT_02F_OUTPUT, + OUT_04F_OUTPUT, + OUT_08F_OUTPUT, + OUT_16F_OUTPUT, + OUT_32F_OUTPUT, + OUTPUTS_LEN + }; + enum LightId { + LIGHTS_LEN + }; + + bool limitPW = true; + bool removePulseDC = false; + bool useTriangleCore = false; + static const int NUM_OUTPUTS = 6; + const float ranges[3] = {4.f, 1.f, 1.f / 12.f}; // full, octave, semitone + + float_4 phase[4] = {}; // phase for core waveform, in [0, 1] + chowdsp::VariableOversampling<6, float_4> oversampler[NUM_OUTPUTS][4]; // uses a 2*6=12th order Butterworth filter + int oversamplingIndex = 2; // default is 2^oversamplingIndex == x4 oversampling + + DCBlockerT<2, float_4> blockDCFilter[NUM_OUTPUTS][4]; // optionally block DC with RC filter @ ~22 Hz + dsp::TSchmittTrigger syncTrigger[4]; // for hard sync + + Octaves() { + config(PARAMS_LEN, INPUTS_LEN, OUTPUTS_LEN, LIGHTS_LEN); + configParam(PWM_CV_PARAM, 0.f, 1.f, 1.f, "PWM CV attenuater"); + + auto octParam = configSwitch(OCTAVE_PARAM, 0.f, 6.f, 1.f, "Octave", {"C1", "C2", "C3", "C4", "C5", "C6", "C7"}); + octParam->snapEnabled = true; + + configParam(TUNE_PARAM, -1.f, 1.f, 0.f, "Tune"); + configParam(PWM_PARAM, 0.5f, 0.f, 0.5f, "PWM"); + auto rangeParam = configSwitch(RANGE_PARAM, 0.f, 2.f, 1.f, "Range", {"VCO: Full", "VCO: Octave", "VCO: Semitone"}); + rangeParam->snapEnabled = true; + + configParam(GAIN_01F_PARAM, 0.f, 1.f, 1.00f, "Gain Fundamental"); + configParam(GAIN_02F_PARAM, 0.f, 1.f, 0.75f, "Gain x2 Fundamental"); + configParam(GAIN_04F_PARAM, 0.f, 1.f, 0.50f, "Gain x4 Fundamental"); + configParam(GAIN_08F_PARAM, 0.f, 1.f, 0.25f, "Gain x8 Fundamental"); + configParam(GAIN_16F_PARAM, 0.f, 1.f, 0.f, "Gain x16 Fundamental"); + configParam(GAIN_32F_PARAM, 0.f, 1.f, 0.f, "Gain x32 Fundamental"); + + configInput(VOCT1_INPUT, "V/Octave 1"); + configInput(VOCT2_INPUT, "V/Octave 2"); + configInput(SYNC_INPUT, "Sync"); + configInput(PWM_INPUT, "PWM"); + configInput(GAIN_01F_INPUT, "Gain x1F CV"); + configInput(GAIN_02F_INPUT, "Gain x1F CV"); + configInput(GAIN_04F_INPUT, "Gain x1F CV"); + configInput(GAIN_08F_INPUT, "Gain x1F CV"); + configInput(GAIN_16F_INPUT, "Gain x1F CV"); + configInput(GAIN_32F_INPUT, "Gain x1F CV"); + + configOutput(OUT_01F_OUTPUT, "x1F"); + configOutput(OUT_02F_OUTPUT, "x2F"); + configOutput(OUT_04F_OUTPUT, "x4F"); + configOutput(OUT_08F_OUTPUT, "x8F"); + configOutput(OUT_16F_OUTPUT, "x16F"); + configOutput(OUT_32F_OUTPUT, "x32F"); + + // calculate up/downsampling rates + onSampleRateChange(); + } + + void onSampleRateChange() override { + float sampleRate = APP->engine->getSampleRate(); + for (int c = 0; c < NUM_OUTPUTS; c++) { + for (int i = 0; i < 4; i++) { + oversampler[c][i].setOversamplingIndex(oversamplingIndex); + oversampler[c][i].reset(sampleRate); + blockDCFilter[c][i].setFrequency(22.05 / sampleRate); + } + } + } + + + void process(const ProcessArgs& args) override { + + const int numActivePolyphonyEngines = getNumActivePolyphonyEngines(); + + // work out active outputs + const std::vector connectedOutputs = getConnectedOutputs(); + if (connectedOutputs.size() == 0) { + return; + } + // only process up to highest active channel + const int highestOutput = *std::max_element(connectedOutputs.begin(), connectedOutputs.end()); + + for (int c = 0; c < numActivePolyphonyEngines; c += 4) { + + const int rangeIndex = params[RANGE_PARAM].getValue(); + float_4 pitch = ranges[rangeIndex] * params[TUNE_PARAM].getValue() + inputs[VOCT1_INPUT].getPolyVoltageSimd(c) + inputs[VOCT2_INPUT].getPolyVoltageSimd(c); + pitch += params[OCTAVE_PARAM].getValue() - 3; + const float_4 freq = dsp::FREQ_C4 * dsp::exp2_taylor5(pitch); + // -1 to +1 + const float_4 pwmCV = params[PWM_CV_PARAM].getValue() * clamp(inputs[PWM_INPUT].getPolyVoltageSimd(c) / 10.f, -1.f, 1.f); + const float_4 pulseWidthLimit = limitPW ? 0.05f : 0.0f; + + // pwm in [-0.25 : +0.25] + const float_4 pwm = 2 * clamp(0.5 - params[PWM_PARAM].getValue() + 0.5 * pwmCV, -0.5f + pulseWidthLimit, 0.5f - pulseWidthLimit); + + const int oversamplingRatio = oversampler[0][0].getOversamplingRatio(); + + const float_4 deltaPhase = freq * args.sampleTime / oversamplingRatio; + + // process sync + float_4 sync = syncTrigger[c / 4].process(inputs[SYNC_INPUT].getPolyVoltageSimd(c)); + phase[c / 4] = simd::ifelse(sync, 0.5f, phase[c / 4]); + + + for (int i = 0; i < oversamplingRatio; i++) { + + phase[c / 4] += deltaPhase; + phase[c / 4] -= simd::floor(phase[c / 4]); + + float_4 sum = {}; + for (int oct = 0; oct <= highestOutput; oct++) { + + const float_4 gainCV = simd::clamp(inputs[GAIN_01F_INPUT + oct].getNormalPolyVoltageSimd(10.f, c) / 10.f, 0.f, 1.0f); + const float_4 gain = params[GAIN_01F_PARAM + oct].getValue() * gainCV; + + // don't bother processing if gain is zero and no output is connected + const bool isGainZero = simd::movemask(gain != 0.f) == 0; + if (isGainZero && !outputs[OUT_01F_OUTPUT + oct].isConnected()) { + continue; + } + + // derive phases for higher octaves from base phase (this keeps things in sync!) + const float_4 n = (float)(1 << oct); + // this is on [0, 1] + const float_4 effectivePhase = n * simd::fmod(phase[c / 4], 1 / n); + const float_4 waveTri = 1.0 - 2.0 * simd::abs(2.f * effectivePhase - 1.0); + // build square from triangle + comparator + const float_4 waveSquare = simd::ifelse(waveTri > pwm, +1.f, -1.f); + + sum += (useTriangleCore ? waveTri : waveSquare) * gain; + sum = clamp(sum, -1.f, 1.f); + + if (outputs[OUT_01F_OUTPUT + oct].isConnected()) { + oversampler[oct][c/4].getOSBuffer()[i] = sum; + sum = 0.f; + + // DEBUG("here %f %f %f %f %f", phase[c/4][0], waveTri[0], sum[0], gain[0], gainCV[0]); + } + + + + } + + } // end of oversampling loop + + // only downsample required channels + for (int oct = 0; oct <= highestOutput; oct++) { + if (outputs[OUT_01F_OUTPUT + oct].isConnected()) { + + // downsample (if required) + float_4 out = (oversamplingRatio > 1) ? oversampler[oct][c/4].downsample() : oversampler[oct][c/4].getOSBuffer()[0]; + if (removePulseDC) { + out = blockDCFilter[oct][c/4].process(out); + } + + outputs[OUT_01F_OUTPUT + oct].setVoltageSimd(5.f * out, c); + } + } + } // end of polyphony loop + + for (int connectedOutput : connectedOutputs) { + outputs[OUT_01F_OUTPUT + connectedOutput].setChannels(numActivePolyphonyEngines); + } + } + + // polyphony is defined by the largest number of active channels on voct, pwm or gain inputs + int getNumActivePolyphonyEngines() { + int activePolyphonyEngines = 1; + for (int c = 0; c < NUM_OUTPUTS; c++) { + if (inputs[GAIN_01F_INPUT + c].isConnected()) { + activePolyphonyEngines = std::max(activePolyphonyEngines, inputs[GAIN_01F_INPUT + c].getChannels()); + } + } + activePolyphonyEngines = std::max({activePolyphonyEngines, inputs[VOCT1_INPUT].getChannels(), inputs[VOCT2_INPUT].getChannels()}); + activePolyphonyEngines = std::max(activePolyphonyEngines, inputs[PWM_INPUT].getChannels()); + + return activePolyphonyEngines; + } + + std::vector getConnectedOutputs() { + std::vector connectedOutputs; + for (int c = 0; c < NUM_OUTPUTS; c++) { + if (outputs[OUT_01F_OUTPUT + c].isConnected()) { + connectedOutputs.push_back(c); + } + } + return connectedOutputs; + } + + json_t* dataToJson() override { + json_t* rootJ = json_object(); + json_object_set_new(rootJ, "removePulseDC", json_boolean(removePulseDC)); + json_object_set_new(rootJ, "limitPW", json_boolean(limitPW)); + json_object_set_new(rootJ, "oversamplingIndex", json_integer(oversampler[0][0].getOversamplingIndex())); + json_object_set_new(rootJ, "useTriangleCore", json_boolean(useTriangleCore)); + + return rootJ; + } + + void dataFromJson(json_t* rootJ) override { + + json_t* removePulseDCJ = json_object_get(rootJ, "removePulseDC"); + if (removePulseDCJ) { + removePulseDC = json_boolean_value(removePulseDCJ); + } + + json_t* limitPWJ = json_object_get(rootJ, "limitPW"); + if (limitPWJ) { + limitPW = json_boolean_value(limitPWJ); + } + + json_t* oversamplingIndexJ = json_object_get(rootJ, "oversamplingIndex"); + if (oversamplingIndexJ) { + oversamplingIndex = json_integer_value(oversamplingIndexJ); + onSampleRateChange(); + } + + json_t* useTriangleCoreJ = json_object_get(rootJ, "useTriangleCore"); + if (useTriangleCoreJ) { + useTriangleCore = json_boolean_value(useTriangleCoreJ); + } + } +}; + +struct OctavesWidget : ModuleWidget { + OctavesWidget(Octaves* module) { + setModule(module); + setPanel(createPanel(asset::plugin(pluginInstance, "res/panels/Octaves.svg"))); + + addChild(createWidget(Vec(RACK_GRID_WIDTH, 0))); + addChild(createWidget(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0))); + addChild(createWidget(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); + addChild(createWidget(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); + + addParam(createParamCentered(mm2px(Vec(52.138, 15.037)), module, Octaves::PWM_CV_PARAM)); + addParam(createParam(mm2px(Vec(22.171, 30.214)), module, Octaves::OCTAVE_PARAM)); + addParam(createParamCentered(mm2px(Vec(10.264, 33.007)), module, Octaves::TUNE_PARAM)); + addParam(createParamCentered(mm2px(Vec(45.384, 40.528)), module, Octaves::PWM_PARAM)); + addParam(createParam(mm2px(Vec(6.023, 48.937)), module, Octaves::RANGE_PARAM)); + addParam(createParam(mm2px(Vec(2.9830, 60.342)), module, Octaves::GAIN_01F_PARAM)); + addParam(createParam(mm2px(Vec(12.967, 60.342)), module, Octaves::GAIN_02F_PARAM)); + addParam(createParam(mm2px(Vec(22.951, 60.342)), module, Octaves::GAIN_04F_PARAM)); + addParam(createParam(mm2px(Vec(32.936, 60.342)), module, Octaves::GAIN_08F_PARAM)); + addParam(createParam(mm2px(Vec(42.920, 60.342)), module, Octaves::GAIN_16F_PARAM)); + addParam(createParam(mm2px(Vec(52.905, 60.342)), module, Octaves::GAIN_32F_PARAM)); + + addInput(createInputCentered(mm2px(Vec(5.247, 15.181)), module, Octaves::VOCT1_INPUT)); + addInput(createInputCentered(mm2px(Vec(15.282, 15.181)), module, Octaves::VOCT2_INPUT)); + addInput(createInputCentered(mm2px(Vec(25.316, 15.181)), module, Octaves::SYNC_INPUT)); + addInput(createInputCentered(mm2px(Vec(37.092, 15.135)), module, Octaves::PWM_INPUT)); + addInput(createInputCentered(mm2px(Vec(5.247, 100.492)), module, Octaves::GAIN_01F_INPUT)); + addInput(createInputCentered(mm2px(Vec(15.282, 100.492)), module, Octaves::GAIN_02F_INPUT)); + addInput(createInputCentered(mm2px(Vec(25.316, 100.492)), module, Octaves::GAIN_04F_INPUT)); + addInput(createInputCentered(mm2px(Vec(35.35, 100.492)), module, Octaves::GAIN_08F_INPUT)); + addInput(createInputCentered(mm2px(Vec(45.384, 100.492)), module, Octaves::GAIN_16F_INPUT)); + addInput(createInputCentered(mm2px(Vec(55.418, 100.492)), module, Octaves::GAIN_32F_INPUT)); + + addOutput(createOutputCentered(mm2px(Vec(5.247, 113.508)), module, Octaves::OUT_01F_OUTPUT)); + addOutput(createOutputCentered(mm2px(Vec(15.282, 113.508)), module, Octaves::OUT_02F_OUTPUT)); + addOutput(createOutputCentered(mm2px(Vec(25.316, 113.508)), module, Octaves::OUT_04F_OUTPUT)); + addOutput(createOutputCentered(mm2px(Vec(35.35, 113.508)), module, Octaves::OUT_08F_OUTPUT)); + addOutput(createOutputCentered(mm2px(Vec(45.384, 113.508)), module, Octaves::OUT_16F_OUTPUT)); + addOutput(createOutputCentered(mm2px(Vec(55.418, 113.508)), module, Octaves::OUT_32F_OUTPUT)); + + } + + void appendContextMenu(Menu* menu) override { + Octaves* module = dynamic_cast(this->module); + assert(module); + + menu->addChild(new MenuSeparator()); + menu->addChild(createSubmenuItem("Hardware compatibility", "", + [ = ](Menu * menu) { + menu->addChild(createBoolPtrMenuItem("Limit pulsewidth (5\%-95\%)", "", &module->limitPW)); + menu->addChild(createBoolPtrMenuItem("Remove pulse DC", "", &module->removePulseDC)); + menu->addChild(createBoolPtrMenuItem("Use triangle core", "", &module->useTriangleCore)); + } + )); + + menu->addChild(createIndexSubmenuItem("Oversampling", + {"Off", "x2", "x4", "x8"}, + [ = ]() { + return module->oversamplingIndex; + }, + [ = ](int mode) { + module->oversamplingIndex = mode; + module->onSampleRateChange(); + } + )); + + } +}; + +Model* modelOctaves = createModel("Octaves"); \ No newline at end of file diff --git a/src/PonyVCO.cpp b/src/PonyVCO.cpp index bc424b5..ad6f52c 100644 --- a/src/PonyVCO.cpp +++ b/src/PonyVCO.cpp @@ -1,6 +1,7 @@ #include "plugin.hpp" #include "ChowDSP.hpp" +using simd::float_4; // references: // * "REDUCING THE ALIASING OF NONLINEAR WAVESHAPING USING CONTINUOUS-TIME CONVOLUTION" (https://www.dafx.de/paper-archive/2016/dafxpapers/20-DAFx-16_paper_41-PN.pdf) @@ -8,46 +9,27 @@ // * https://ccrma.stanford.edu/~jatin/Notebooks/adaa.html // * Pony waveshape https://www.desmos.com/calculator/1kvahyl4ti +template class FoldStage1 { public: - float process(float x, float xt) { - float y; + T process(T x, T xt) { + T y = simd::ifelse(simd::abs(x - xPrev) < 1e-5, + f(0.5 * (xPrev + x), xt), + (F(x, xt) - F(xPrev, xt)) / (x - xPrev)); - if (fabs(x - xPrev) < 1e-5) { - y = f(0.5 * (xPrev + x), xt); - } - else { - y = (F(x, xt) - F(xPrev, xt)) / (x - xPrev); - } xPrev = x; return y; } // xt - threshold x - static float f(float x, float xt) { - if (x > xt) { - return +5 * xt - 4 * x; - } - else if (x < -xt) { - return -5 * xt - 4 * x; - } - else { - return x; - } + static T f(T x, T xt) { + return simd::ifelse(x > xt, +5 * xt - 4 * x, simd::ifelse(x < -xt, -5 * xt - 4 * x, x)); } - static float F(float x, float xt) { - if (x > xt) { - return 5 * xt * x - 2 * x * x - 2.5 * xt * xt; - } - else if (x < -xt) { - return -5 * xt * x - 2 * x * x - 2.5 * xt * xt; - - } - else { - return x * x / 2.f; - } + static T F(T x, T xt) { + return simd::ifelse(x > xt, 5 * xt * x - 2 * x * x - 2.5 * xt * xt, + simd::ifelse(x < -xt, -5 * xt * x - 2 * x * x - 2.5 * xt * xt, x * x / 2.f)); } void reset() { @@ -55,55 +37,29 @@ class FoldStage1 { } private: - float xPrev = 0.f; + T xPrev = 0.f; }; +template class FoldStage2 { public: - float process(float x) { - float y; - - if (fabs(x - xPrev) < 1e-5) { - y = f(0.5 * (xPrev + x)); - } - else { - y = (F(x) - F(xPrev)) / (x - xPrev); - } + T process(T x) { + const T y = simd::ifelse(simd::abs(x - xPrev) < 1e-5, f(0.5 * (xPrev + x)), (F(x) - F(xPrev)) / (x - xPrev)); xPrev = x; return y; } - static float f(float x) { - if (-(x + 2) > c) { - return c; - } - else if (x < -1) { - return -(x + 2); - } - else if (x < 1) { - return x; - } - else if (-x + 2 > -c) { - return -x + 2; - } - else { - return -c; - } + static T f(T x) { + return simd::ifelse(-(x + 2) > c, c, simd::ifelse(x < -1, -(x + 2), simd::ifelse(x < 1, x, simd::ifelse(-x + 2 > -c, -x + 2, -c)))); } - static float F(float x) { - if (x < 0) { - return F(-x); - } - else if (x < 1) { - return x * x * 0.5; - } - else if (x < 2 + c) { - return 2 * x * (1.f - x * 0.25f) - 1.f; - } - else { - return 2 * (2 + c) * (1 - (2 + c) * 0.25f) - 1.f - c * (x - 2 - c); - } + static T F(T x) { + return simd::ifelse(x > 0, F_signed(x), F_signed(-x)); + } + + static T F_signed(T x) { + return simd::ifelse(x < 1, x * x * 0.5, simd::ifelse(x < 2.f + c, 2.f * x * (1.f - x * 0.25f) - 1.f, + 2.f * (2.f + c) * (1.f - (2.f + c) * 0.25f) - 1.f - c * (x - 2.f - c))); } void reset() { @@ -111,8 +67,8 @@ class FoldStage2 { } private: - float xPrev = 0.f; - static constexpr float c = 0.1; + T xPrev = 0.f; + static constexpr float c = 0.1f; }; @@ -148,10 +104,10 @@ struct PonyVCO : Module { }; float range[4] = {8.f, 1.f, 1.f / 12.f, 10.f}; - chowdsp::VariableOversampling<6> oversampler; // uses a 2*6=12th order Butterworth filter + chowdsp::VariableOversampling<6, float_4> oversampler[4]; // uses a 2*6=12th order Butterworth filter int oversamplingIndex = 1; // default is 2^oversamplingIndex == x2 oversampling - dsp::RCFilter blockTZFMDCFilter; + dsp::TRCFilter blockTZFMDCFilter[4]; bool blockTZFMDC = true; // hardware doesn't limit PW but some user might want to (to 5%->95%) @@ -160,10 +116,10 @@ struct PonyVCO : Module { // hardware has DC for non-50% duty cycle, optionally add/remove it bool removePulseDC = true; - dsp::SchmittTrigger syncTrigger; + dsp::TSchmittTrigger syncTrigger[4]; - FoldStage1 stage1; - FoldStage2 stage2; + FoldStage1 stage1[4]; + FoldStage2 stage2[4]; PonyVCO() { config(PARAMS_LEN, INPUTS_LEN, OUTPUTS_LEN, LIGHTS_LEN); @@ -191,22 +147,21 @@ struct PonyVCO : Module { void onSampleRateChange() override { float sampleRate = APP->engine->getSampleRate(); - blockTZFMDCFilter.setCutoffFreq(5.0 / sampleRate); - oversampler.setOversamplingIndex(oversamplingIndex); - oversampler.reset(sampleRate); + for (int c = 0; c < 4; c++) { + blockTZFMDCFilter[c].setCutoffFreq(5.0 / sampleRate); + oversampler[c].setOversamplingIndex(oversamplingIndex); + oversampler[c].reset(sampleRate); - stage1.reset(); - stage2.reset(); + stage1[c].reset(); + stage2[c].reset(); + } } // implementation taken from "Alias-Suppressed Oscillators Based on Differentiated Polynomial Waveforms", // also the notes from Surge Synthesier repo: // https://github.com/surge-synthesizer/surge/blob/09f1ec8e103265bef6fc0d8a0fc188238197bf8c/src/common/dsp/oscillators/ModernOscillator.cpp#L19 - // Calculation is performed at double precision, as the differencing equations appeared to work poorly with only float. - double phase = 0.0; // phase at current (sub)sample - double phases[3] = {}; // phase as extrapolated to the current and two previous samples - double sawBuffer[3] = {}, sawOffsetBuff[3] = {}, triBuffer[3] = {}; // buffers for storing the terms in the difference equation + float_4 phase[4] = {}; // phase at current (sub)sample void process(const ProcessArgs& args) override { @@ -216,130 +171,160 @@ struct PonyVCO : Module { const Waveform waveform = (Waveform) params[WAVE_PARAM].getValue(); const float mult = lfoMode ? 1.0 : dsp::FREQ_C4; const float baseFreq = std::pow(2, (int)(params[OCT_PARAM].getValue() - 3)) * mult; - const int oversamplingRatio = lfoMode ? 1 : oversampler.getOversamplingRatio(); - const float timbre = clamp(params[TIMBRE_PARAM].getValue() + inputs[TIMBRE_INPUT].getVoltage() / 10.f, 0.f, 1.f); - - float tzfmVoltage = inputs[TZFM_INPUT].getVoltage(); - if (blockTZFMDC) { - blockTZFMDCFilter.process(tzfmVoltage); - tzfmVoltage = blockTZFMDCFilter.highpass(); - } + const int oversamplingRatio = lfoMode ? 1 : oversampler[0].getOversamplingRatio(); - const double pitch = inputs[VOCT_INPUT].getVoltage() + params[FREQ_PARAM].getValue() * range[rangeIndex]; - const double freq = baseFreq * simd::pow(2.f, pitch); - const double deltaBasePhase = clamp(freq * args.sampleTime / oversamplingRatio, -0.5f, 0.5f); - // denominator for the second-order FD - const double denominator = 0.25 / (deltaBasePhase * deltaBasePhase); - // not clamped, but _total_ phase treated later with floor/ceil - const double deltaFMPhase = freq * tzfmVoltage * args.sampleTime / oversamplingRatio; - - float pw = timbre; - if (limitPW) { - pw = clamp(pw, 0.05, 0.95); - } - // pulsewave waveform doesn't have DC even for non 50% duty cycles, but Befaco team would like the option - // for it to be added back in for hardware compatibility reasons - const float pulseDCOffset = (!removePulseDC) * 2.f * (0.5f - pw); - - // hard sync - if (syncTrigger.process(inputs[SYNC_INPUT].getVoltage())) { - // hardware waveform is actually cos, so pi/2 phase offset is required - // - variable phase is defined on [0, 1] rather than [0, 2pi] so pi/2 -> 0.25 - phase = (waveform == WAVE_SIN) ? 0.25f : 0.f; - } + // number of active polyphony engines (must be at least 1) + const int channels = std::max({inputs[TZFM_INPUT].getChannels(), inputs[VOCT_INPUT].getChannels(), inputs[TIMBRE_INPUT].getChannels(), 1}); - float* osBuffer = oversampler.getOSBuffer(); - for (int i = 0; i < oversamplingRatio; ++i) { + for (int c = 0; c < channels; c += 4) { + const float_4 timbre = simd::clamp(params[TIMBRE_PARAM].getValue() + inputs[TIMBRE_INPUT].getPolyVoltageSimd(c) / 10.f, 0.f, 1.f); - phase += deltaBasePhase + deltaFMPhase; - if (phase > 1.f) { - phase -= floor(phase); + float_4 tzfmVoltage = inputs[TZFM_INPUT].getPolyVoltageSimd(c); + if (blockTZFMDC) { + blockTZFMDCFilter[c / 4].process(tzfmVoltage); + tzfmVoltage = blockTZFMDCFilter[c / 4].highpass(); } - else if (phase < 0.f) { - phase += -ceil(phase) + 1; + + const float_4 pitch = inputs[VOCT_INPUT].getPolyVoltageSimd(c) + params[FREQ_PARAM].getValue() * range[rangeIndex]; + const float_4 freq = baseFreq * simd::pow(2.f, pitch); + const float_4 deltaBasePhase = simd::clamp(freq * args.sampleTime / oversamplingRatio, -0.5f, 0.5f); + // floating point arithmetic doesn't work well at low frequencies, specifically because the finite difference denominator + // becomes tiny - we check for that scenario and use naive / 1st order waveforms in that frequency regime (as aliasing isn't + // a problem there). With no oversampling, at 44100Hz, the threshold frequency is 44.1Hz. + const float_4 lowFreqRegime = simd::abs(deltaBasePhase) < 1e-3; + + // 1 / denominator for the second-order FD + const float_4 denominatorInv = 0.25 / (deltaBasePhase * deltaBasePhase); + // not clamped, but _total_ phase treated later with floor/ceil + const float_4 deltaFMPhase = freq * tzfmVoltage * args.sampleTime / oversamplingRatio; + + float_4 pw = timbre; + if (limitPW) { + pw = clamp(pw, 0.05, 0.95); } + // pulsewave waveform doesn't have DC even for non 50% duty cycles, but Befaco team would like the option + // for it to be added back in for hardware compatibility reasons + const float_4 pulseDCOffset = (!removePulseDC) * 2.f * (0.5f - pw); - // sin is simple + // hard sync + const float_4 syncMask = syncTrigger[c / 4].process(inputs[SYNC_INPUT].getPolyVoltageSimd(c)); if (waveform == WAVE_SIN) { - osBuffer[i] = sin2pi_pade_05_5_4(phase); + // hardware waveform is actually cos, so pi/2 phase offset is required + // - variable phase is defined on [0, 1] rather than [0, 2pi] so pi/2 -> 0.25 + phase[c / 4] = simd::ifelse(syncMask, 0.25f, phase[c / 4]); } else { + phase[c / 4] = simd::ifelse(syncMask, 0.f, phase[c / 4]); + } - phases[0] = phase - 2 * deltaBasePhase + (phase < 2 * deltaBasePhase); - phases[1] = phase - deltaBasePhase + (phase < deltaBasePhase); - phases[2] = phase; + float_4* osBuffer = oversampler[c / 4].getOSBuffer(); + for (int i = 0; i < oversamplingRatio; ++i) { - switch (waveform) { - case WAVE_TRI: { - osBuffer[i] = aliasSuppressedTri() * denominator; - break; - } - case WAVE_SAW: { - osBuffer[i] = aliasSuppressedSaw() * denominator; - break; - } - case WAVE_PULSE: { - double saw = aliasSuppressedSaw(); - double sawOffset = aliasSuppressedOffsetSaw(pw); + phase[c / 4] += deltaBasePhase + deltaFMPhase; + // ensure within [0, 1] + phase[c / 4] -= simd::floor(phase[c / 4]); - osBuffer[i] = (sawOffset - saw) * denominator; - osBuffer[i] += pulseDCOffset; - break; + // sin is simple + if (waveform == WAVE_SIN) { + osBuffer[i] = sin2pi_pade_05_5_4(phase[c / 4]); + } + else { + float_4 phases[3]; // phase as extrapolated to the current and two previous samples + + phases[0] = phase[c / 4] - 2 * deltaBasePhase + simd::ifelse(phase[c / 4] < 2 * deltaBasePhase, 1.f, 0.f); + phases[1] = phase[c / 4] - deltaBasePhase + simd::ifelse(phase[c / 4] < deltaBasePhase, 1.f, 0.f); + phases[2] = phase[c / 4]; + + switch (waveform) { + case WAVE_TRI: { + const float_4 dpwOrder1 = 1.0 - 2.0 * simd::abs(2 * phase[c / 4] - 1.0); + const float_4 dpwOrder3 = aliasSuppressedTri(phases) * denominatorInv; + + osBuffer[i] = simd::ifelse(lowFreqRegime, dpwOrder1, dpwOrder3); + break; + } + case WAVE_SAW: { + const float_4 dpwOrder1 = 2 * phase[c / 4] - 1.0; + const float_4 dpwOrder3 = aliasSuppressedSaw(phases) * denominatorInv; + + osBuffer[i] = simd::ifelse(lowFreqRegime, dpwOrder1, dpwOrder3); + break; + } + case WAVE_PULSE: { + float_4 dpwOrder1 = simd::ifelse(phase[c / 4] < 1. - pw, +1.0, -1.0); + dpwOrder1 -= removePulseDC ? 2.f * (0.5f - pw) : 0.f; + + float_4 saw = aliasSuppressedSaw(phases); + float_4 sawOffset = aliasSuppressedOffsetSaw(phases, pw); + float_4 dpwOrder3 = (sawOffset - saw) * denominatorInv + pulseDCOffset; + + osBuffer[i] = simd::ifelse(lowFreqRegime, dpwOrder1, dpwOrder3); + break; + } + default: break; } - default: break; } - } - if (waveform != WAVE_PULSE) { - osBuffer[i] = wavefolder(osBuffer[i], (1 - 0.85 * timbre)); - } - } + if (waveform != WAVE_PULSE) { + osBuffer[i] = wavefolder(osBuffer[i], (1 - 0.85 * timbre), c); + } + + } // end of oversampling loop - // downsample (if required) - const float out = (oversamplingRatio > 1) ? oversampler.downsample() : osBuffer[0]; + // downsample (if required) + const float_4 out = (oversamplingRatio > 1) ? oversampler[c / 4].downsample() : osBuffer[0]; - // end of chain VCA - const float gain = std::max(0.f, inputs[VCA_INPUT].getNormalVoltage(10.f) / 10.f); - outputs[OUT_OUTPUT].setVoltage(5.f * out * gain); + // end of chain VCA + const float_4 gain = simd::clamp(inputs[VCA_INPUT].getNormalPolyVoltageSimd(10.f, c) / 10.f, 0.f, 1.f); + outputs[OUT_OUTPUT].setVoltageSimd(5.f * out * gain, c); + + } // end of channels loop + + outputs[OUT_OUTPUT].setChannels(channels); } - double aliasSuppressedTri() { + float_4 aliasSuppressedTri(float_4* phases) { + float_4 triBuffer[3]; for (int i = 0; i < 3; ++i) { - double p = 2 * phases[i] - 1.0; // range -1.0 to +1.0 - double s = 0.5 - std::abs(p); // eq 30 + float_4 p = 2 * phases[i] - 1.0; // range -1.0 to +1.0 + float_4 s = 0.5 - simd::abs(p); // eq 30 triBuffer[i] = (s * s * s - 0.75 * s) / 3.0; // eq 29 } return (triBuffer[0] - 2.0 * triBuffer[1] + triBuffer[2]); } - double aliasSuppressedSaw() { + float_4 aliasSuppressedSaw(float_4* phases) { + float_4 sawBuffer[3]; for (int i = 0; i < 3; ++i) { - double p = 2 * phases[i] - 1.0; // range -1 to +1 + float_4 p = 2 * phases[i] - 1.0; // range -1 to +1 sawBuffer[i] = (p * p * p - p) / 6.0; // eq 11 } return (sawBuffer[0] - 2.0 * sawBuffer[1] + sawBuffer[2]); } - double aliasSuppressedOffsetSaw(double pw) { + float_4 aliasSuppressedOffsetSaw(float_4* phases, float_4 pw) { + float_4 sawOffsetBuff[3]; + for (int i = 0; i < 3; ++i) { - double p = 2 * phases[i] - 1.0; // range -1 to +1 - double pwp = p + 2 * pw; // phase after pw (pw in [0, 1]) - pwp += (pwp > 1) * -2; // modulo on [-1, +1] + float_4 p = 2 * phases[i] - 1.0; // range -1 to +1 + float_4 pwp = p + 2 * pw; // phase after pw (pw in [0, 1]) + pwp += simd::ifelse(pwp > 1, -2, 0); // modulo on [-1, +1] sawOffsetBuff[i] = (pwp * pwp * pwp - pwp) / 6.0; // eq 11 } return (sawOffsetBuff[0] - 2.0 * sawOffsetBuff[1] + sawOffsetBuff[2]); } - float wavefolder(float x, float xt) { - return stage2.process(stage1.process(x, xt)); + float_4 wavefolder(float_4 x, float_4 xt, int c) { + return stage2[c / 4].process(stage1[c / 4].process(x, xt)); } json_t* dataToJson() override { json_t* rootJ = json_object(); json_object_set_new(rootJ, "blockTZFMDC", json_boolean(blockTZFMDC)); json_object_set_new(rootJ, "removePulseDC", json_boolean(removePulseDC)); - json_object_set_new(rootJ, "oversamplingIndex", json_integer(oversampler.getOversamplingIndex())); + json_object_set_new(rootJ, "limitPW", json_boolean(limitPW)); + json_object_set_new(rootJ, "oversamplingIndex", json_integer(oversampler[0].getOversamplingIndex())); return rootJ; } @@ -355,6 +340,11 @@ struct PonyVCO : Module { removePulseDC = json_boolean_value(removePulseDCJ); } + json_t* limitPWJ = json_object_get(rootJ, "limitPW"); + if (limitPWJ) { + limitPW = json_boolean_value(limitPWJ); + } + json_t* oversamplingIndexJ = json_object_get(rootJ, "oversamplingIndex"); if (oversamplingIndexJ) { oversamplingIndex = json_integer_value(oversamplingIndexJ); diff --git a/src/Voltio.cpp b/src/Voltio.cpp new file mode 100644 index 0000000..bba5c39 --- /dev/null +++ b/src/Voltio.cpp @@ -0,0 +1,85 @@ +#include "plugin.hpp" + +using simd::float_4; + +struct Voltio : Module { + enum ParamId { + OCT_PARAM, + RANGE_PARAM, + SEMITONES_PARAM, + PARAMS_LEN + }; + enum InputId { + SUM_INPUT, + INPUTS_LEN + }; + enum OutputId { + OUT_OUTPUT, + OUTPUTS_LEN + }; + enum LightId { + PLUSMINUS5_LIGHT, + ZEROTOTEN_LIGHT, + LIGHTS_LEN + }; + + Voltio() { + config(PARAMS_LEN, INPUTS_LEN, OUTPUTS_LEN, LIGHTS_LEN); + auto octParam = configParam(OCT_PARAM, 0.f, 10.f, 0.f, "Octave"); + octParam->snapEnabled = true; + + configSwitch(RANGE_PARAM, 0.f, 1.f, 0.f, "Range", {"0 to 10", "-5 to +5"}); + auto semitonesParam = configParam(SEMITONES_PARAM, 0.f, 11.f, 0.f, "Semitones"); + semitonesParam->snapEnabled = true; + + configInput(SUM_INPUT, "Sum"); + configOutput(OUT_OUTPUT, ""); + } + + void process(const ProcessArgs& args) override { + const int channels = std::max(1, inputs[SUM_INPUT].getChannels()); + + for (int c = 0; c < channels; c += 4) { + float_4 in = inputs[SUM_INPUT].getPolyVoltageSimd(c); + + float offset = params[RANGE_PARAM].getValue() ? -5.f : 0.f; + in += params[SEMITONES_PARAM].getValue() / 12.f + params[OCT_PARAM].getValue() + offset; + + outputs[OUT_OUTPUT].setVoltageSimd(in, c); + } + + outputs[OUT_OUTPUT].setChannels(channels); + + lights[PLUSMINUS5_LIGHT].setBrightness(params[RANGE_PARAM].getValue() ? 1.f : 0.f); + lights[ZEROTOTEN_LIGHT].setBrightness(params[RANGE_PARAM].getValue() ? 0.f : 1.f); + } + +}; + + +struct VoltioWidget : ModuleWidget { + VoltioWidget(Voltio* module) { + setModule(module); + setPanel(createPanel(asset::plugin(pluginInstance, "res/panels/Voltio.svg"))); + + addChild(createWidget(Vec(RACK_GRID_WIDTH, 0))); + addChild(createWidget(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); + + addParam(createParamCentered(mm2px(Vec(15.0, 20.828)), module, Voltio::OCT_PARAM)); + addParam(createParamCentered(mm2px(Vec(22.083, 44.061)), module, Voltio::RANGE_PARAM)); + auto p = createParamCentered(mm2px(Vec(15.0, 67.275)), module, Voltio::SEMITONES_PARAM); + p->minAngle = -0.83 * M_PI; + p->maxAngle = M_PI; + addParam(p); + + addInput(createInputCentered(mm2px(Vec(7.117, 111.003)), module, Voltio::SUM_INPUT)); + + addOutput(createOutputCentered(mm2px(Vec(22.661, 111.003)), module, Voltio::OUT_OUTPUT)); + + addChild(createLightCentered>(mm2px(Vec(5.695, 41.541)), module, Voltio::PLUSMINUS5_LIGHT)); + addChild(createLightCentered>(mm2px(Vec(5.695, 46.633)), module, Voltio::ZEROTOTEN_LIGHT)); + } +}; + + +Model* modelVoltio = createModel("Voltio"); \ No newline at end of file diff --git a/src/plugin.cpp b/src/plugin.cpp index 49dbfdc..90d4b02 100644 --- a/src/plugin.cpp +++ b/src/plugin.cpp @@ -27,4 +27,8 @@ void init(rack::Plugin *p) { p->addModel(modelChannelStrip); p->addModel(modelPonyVCO); p->addModel(modelMotionMTR); + p->addModel(modelBurst); + p->addModel(modelMidiThing); + p->addModel(modelVoltio); + p->addModel(modelOctaves); } diff --git a/src/plugin.hpp b/src/plugin.hpp index 441efcb..8d79940 100644 --- a/src/plugin.hpp +++ b/src/plugin.hpp @@ -28,6 +28,10 @@ extern Model* modelNoisePlethora; extern Model* modelChannelStrip; extern Model* modelPonyVCO; extern Model* modelMotionMTR; +extern Model* modelBurst; +extern Model* modelMidiThing; +extern Model* modelVoltio; +extern Model* modelOctaves; struct Knurlie : SvgScrew { Knurlie() { @@ -221,6 +225,21 @@ struct BefacoSlidePotSmall : app::SvgSlider { } }; +struct BefacoButton : app::SvgSwitch { + BefacoButton() { + momentary = true; + addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/components/BefacoButton_0.svg"))); + addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/components/BefacoButton_1.svg"))); + } +}; + +struct Davies1900hWhiteKnobEndless : Davies1900hKnob { + Davies1900hWhiteKnobEndless() { + setSvg(Svg::load(asset::plugin(pluginInstance, "res/components/Davies1900hWhiteEndless.svg"))); + bg->setSvg(Svg::load(asset::plugin(pluginInstance, "res/components/Davies1900hWhiteEndless_bg.svg"))); + } +}; + inline int unsigned_modulo(int a, int b) { return ((a % b) + b) % b; } @@ -295,7 +314,7 @@ struct ADEnvelope { }; // Creates a Butterworth 2*Nth order highpass filter for blocking DC -template +template struct DCBlockerT { DCBlockerT() { @@ -308,7 +327,7 @@ struct DCBlockerT { recalculateCoefficients(); } - float process(float x) { + T process(T x) { for (int idx = 0; idx < N; idx++) { x = blockDCFilter[idx].process(x); } @@ -325,17 +344,17 @@ struct DCBlockerT { for (int idx = 0; idx < N; idx++) { float Q = 1.0f / (2.0f * std::cos(firstAngle + idx * poleInc)); - blockDCFilter[idx].setParameters(dsp::BiquadFilter::HIGHPASS, fc_, Q, 1.0f); + blockDCFilter[idx].setParameters(dsp::TBiquadFilter::HIGHPASS, fc_, Q, 1.0f); } } float fc_; static const int order = 2 * N; - dsp::BiquadFilter blockDCFilter[N]; + dsp::TBiquadFilter blockDCFilter[N]; }; -typedef DCBlockerT<2> DCBlocker; +typedef DCBlockerT<2, float> DCBlocker; /** When triggered, holds a high value for a specified time before going low again */ struct PulseGenerator_4 {