Skip to content
KODA
Reference

KODA Scripting Reference

Lists every function available to scripts along with code examples.

Introduction


Pre-release

This document is not finalized for publish and is still being worked on.

Conventions used in this reference

FunctionReturnsDescription
functionName(argType argName) ReturnType A description of what the function does, with range or unit information for numeric arguments and midpoints, or defaults where relevant.TipOptional note about parameter-accepting overloads or related functions.

Names say their unit

A function that takes a gain, a time or a level says its unit in its name: setGainLinear beside setVolume (decibels), setAttackSeconds, setLFOFadeInMS. The names below were renamed in 1.0.12. The old ones still work, and the console names the new one, once per name, when your script compiles.

Velocity and alpha follow the type of the number you pass. A whole-number velocity is MIDI, 0-127, and a float is 0.0-1.0. An alpha is always 0.0-1.0, and one past 1.0 (withAlpha(128)) is drawn opaque with a console warning; withAlpha8 and getColourRGBA8 take 0-255, and getColourARGB(0xAARRGGBB_L) reads alpha first.

Old nameNew nameNote
setGain / getGainsetGainLinear / getGainLinearA factor: 1.0 is unity. For decibels, use setVolume.
setInstrumentGainsetInstrumentGainLinear
setSendLevelsetSendLevelLinearFor decibels, use setSendLevelDecibels.
setPreDelay, setAttack, setHold, setDecay, setReleasesetPreDelaySeconds, setAttackSeconds, setHoldSeconds, setDecaySeconds, setReleaseSeconds
Note.setLengthsetLengthSecondsA Note also has setLengthMS, setLengthSamples and setLengthBeats.
setSampleStartsetSampleStartMS
setLFOFadeIn, setMultiLFOFadeInsetLFOFadeInMS, setMultiLFOFadeInMS
setEnvelopePreDelay, …Attack, …Hold, …Decay, …ReleasesetEnvelopePreDelaySeconds, …AttackSeconds, …HoldSeconds, …DecaySeconds, …ReleaseSeconds
Bus.setBypass, bypassInsertsetBypassed, setInsertBypassedBypassed means off, for buses, mics and inserts alike.
Mic.setMicEnabledsetBypassedThe opposite way round: setBypassed(true) turns the mic off.
getppqPositiongetPpqPosition

How instrument scripts start

Nearly every instrument script opens the same way: an event initialize() that runs once when the instrument loads, switching on logging and setting how much of KODA's automatic note handling you want to keep.

event initialize()
{
    setLogEnabled(true);          // Without this, debug.log() output is silent
    setIgnoreMidiNotes(false);    // Make sure incoming MIDI notes still play
}
  • setLogEnabled(true) - logging is off by default, so debug.log() stays silent until you turn it on.
  • setIgnoreMidiNotes(false) - KODA keeps triggering notes for you. Use this when the script only listens: logging, GUI work, or modulation.
  • setIgnoreNoteOns(true) - KODA stops triggering notes so the script can start them itself with startNote(). setIgnoreMidiNotes(true) does the same for note-offs as well.

These flags live on the instrument, but the script owns them: every time a script loads or reloads, they reset to their defaults before initialize() runs, so the engine only keeps what the current version of the script actually sets. Remove a setIgnoreNoteOns(true) and reload - the engine goes back to handling note-ons. See MIDI input control for the full set.

No timing values yet

initialize() runs before any audio is flowing. The sample rate and block size are already set there (the rate the script was compiled at; sampleRateChanged() follows if the device runs at another), but the tempo, time signature and transport read 0 until the first audio block. So anything that depends on tempo reads 0 in initialize(): getBeat(), getBar(), the note length helpers and setLengthBeats. Nothing errors. setDelayMS and setDelaySeconds are safe to use here: they keep the delay in milliseconds and convert it when the note starts. Building a Pattern here is fine too - patterns store beat positions as beats and only convert them to samples during playback.

If your setup needs them, do that part on the first process() call instead, where the numbers are real:

bool ready;

event process()
{
    if(!ready)
    {
        buildDelayTables();   // sample rate and tempo are real by now
        ready = true;
    }
}

Everything that doesn't depend on timing still belongs in initialize(): logging, MIDI flags, building UI, reading parameters.

Compressed examples

Since this opening block appears in nearly every example, the examples below often compress it onto a single line to save space: event initialize() { setIgnoreNoteOns(true); }. Both forms do the same thing, so write it whichever way you prefer.

Getting by name vs. by index

Two ways to fetch

Most getter functions that fetch a part of the instrument - getArticulation, getVariation, getGroup, getMic, getBus, getParameter, and others - accept either a name (string) or an index (int). Both forms return the same kind of object.

Either way, a lookup that finds nothing - a misspelled name, an index past the end - returns an object whose isIdValid() is false. It is never swapped for another part of the instrument. Calling a setter or starting a note on it does nothing, and the console says so once.

One index is not a miss, though it is deprecated: -1 for a variation or a group stands for the layer above it. art.getVariation(-1) gives the articulation as a whole, and variation.getGroup(-1) the variation as a whole, and the console says once that the call is deprecated. Use the Articulation or Variation itself instead: its setters change that layer's own values, and a note started on it plays where the layer's note distribution sends it.

  • By name - More robust. If you reorder articulations, variations, or other parts of the instrument, scripts keep working because they reference the parts by what they're called, not where they sit.
  • By index - Less typing, and natural inside for loops where you'd iterate over every articulation, mic, etc. Index access skips the string lookup, but breaks if you reorder.
// By name - survives reordering
Articulation soft = getArticulation("Soft");
Mic close = getMic("Close");
// By index - concise in loops
event initialize()
{
    setLogEnabled(true);    // Without this, debug.log() output is silent

    for(int i = 0; i < getNumArticulations(); i++)
    {
        Articulation art = getArticulation(i);
        debug.log(art.getName());
    }
}

Note vs NoteData

Two related but distinct types describe a note at different points in its life:

  • NoteData - a template for a note before it plays. Carries pitch, velocity, envelope, timing, and routing. KODA hands one to your noteOn handler describing each incoming MIDI note. Changing it changes nothing on its own: KODA plays the incoming note as it arrived. To play it changed, call setIgnoreNoteOns(true) and start it yourself with start() or startNote(). You can also build new ones via createNoteData().
  • Note - a handle to a note that's currently playing. You get one back from startNote(). Use it to stop the playing note, or change its tuning, gain, pan, or trigger its release.

The typical flow is configure (NoteData) → start (returns a Note) → modify (Note):

event initialize() { setIgnoreNoteOns(true); }

event noteOn(NoteData note)  // NoteData is a template for a note to be played
{
    note.setAttackSeconds(0.05f);   // Set attack before note plays

    Articulation art = getCurrentArticulation();
    Note playing = art.startNote(note); // Trigger it, get back a Note handle.

    playing.setGainLinear(0.8f);              // Modify the playing note
}

Once startNote() has fired, changes to the original NoteData have no effect on the playing note. They only describe the template. To affect a sounding note, always use its Note handle.

Two ways to call a function: with a dot or without

Same call, two ways

artic.startNote(note); can also be written as startNote(artic, note);

artic.setGainLinear(0.5f); can also be written as setGainLinear(artic, 0.5f);

Although written differently, they are identical.

Examples in this reference use dot syntax because it's the more common style in the Cmajor standard library and KODA codebase. If you prefer passing the object as the first argument, that form works everywhere too.

Using Parameter to skip using .getValue() (Overload Convenience)

Many setter functions that take a primitive (float, int, or bool) also accept a Parameter directly, saving you a .getValue() / .getIntValue() / .getBoolValue() call. The Parameter overload exists wherever you see a Tip line in a function's description.

// Both of these set the articulation's gain from the built-in Dynamics Parameter:
event Dynamics(Parameter parameter)
{
    Articulation art = getCurrentArticulation();

    art.setGainLinear(parameter.getValue());   // Explicit unwrap
    art.setGainLinear(parameter);              // Parameter overload - same result, less typing
}

For non-setter contexts (arithmetic, comparisons, logging, passing to functions without a Parameter overload) you'll always need an explicit .getValue():

// ✗ Won't compile
if(parameter > 0.5f)
// ✓ Works
if(parameter.getValue() > 0.5f)

Built-in Parameters

Every KODA instrument always carries these eight Parameters. They're created automatically - you don't need to add them in Figma - and you can react to them from a script with the standard event <ParameterName>(Parameter parameter) handler pattern without any extra UI setup. Their CC assignments are fixed. The CONTROL tab that will let users remap them is still to come.

Each has a range of 0.0-1.0 except where the table says otherwise. Note that the defaults are not all 0.0. Dynamics starts at 0.8, and BreathController starts at 1.0. If your script reads one of these before the user has touched it, that starting value is what you'll get. They appear in the order below in the app's Instrument Parameters table.

ParameterDefault CCDefaultDescription
Dynamics CC 1 0.8 Continuous expressive level - typically used to blend dynamic-layer Articulations or to control a Variation crossfader. Standard mod-wheel destination.
Vibrato CC 2 0.0 Vibrato depth or rate. Sometimes wired to a Modulator's LFO depth for scripted vibrato.TipThis is the one built-in that ships with IGNORE ticked in the Instrument Parameters table, so incoming CC 2 is muted until the author clears it. Setting the Parameter from a script is unaffected.
BreathController CC 3 1.0 Breath-controller position. Starts at 1.0 (fully open), not 0.0.
Expression CC 11 0.0 Continuous expression / volume-after-fader.
SustainPedal CC 64 0.0 Sustain pedal state, defaulting to pedal-up so a freshly loaded instrument never starts with sustain engaged. Conventionally treated as a switch above 0.5. To stop the pedal affecting notes at all, call setIgnoreSustainPedal(true).
PitchBend Pitch-bend msg 0.0 Pitch-bend wheel position. Range −1.0 (full down) to 1.0 (full up); 0.0 is centered. Driven by the dedicated MIDI pitch-bend message rather than a CC, so it has no CC number to remap.
Aftertouch - 0.0 Aftertouch pressure, normalized to 0.0-1.0. Fed by both channel pressure and polyphonic aftertouch. Whichever arrived last wins. Driven by the MIDI pressure message rather than a CC.
CurrentArticulation - 0 Index of the currently active Articulation, from 0 to the number of Articulations minus one. Controlled by a GUI control bound to it (for example a Button with SetToValue), by keyswitches, or by script via setCurrentArticulation(...). It holds a whole-number index rather than a continuous control value, so it snaps between articulations instead of sliding through the values in between. Has no CC mapping.TipThis is the only built-in that isn't offered to the host as an automation slot. The other seven are.

Don't write scripts around the CC numbers themselves. You always address these by name - getParameter("Dynamics"), event Dynamics(Parameter parameter) - and the CC is just an input-routing detail handled outside your code. Once user remapping arrives, a script written this way keeps working with no changes.

How to use the script examples in this reference

Script examples throughout this reference use built-in Parameters like Dynamics, Expression, and SustainPedal so they copy-paste into any instrument and run without you building UI first.

It does make a few examples impractical - bypassing a distortion with the sustain pedal isn't something you'd normally do. Replace the built-in Parameter with one of your own, the Parameter behind your knob or slider, and rename the handler to match:

  • A button in place of SustainPedal
  • A knob or slider in place of a continuous CC like Expression
  • A menu in place of CurrentArticulation

Built-in helpers

Generic utility functions that don't belong to any specific type. Always in scope.

FunctionReturnsDescription
limit(Type value, Type min, Type max)TypeReturns value clamped to the inclusive range [min, max]. Works with any numeric type, inferred from the arguments. It returns the clamped value rather than changing value in place, so assign the result: x = limit(x, 0, 40);

Cmajor patterns you'll see

A few Cmajor language conventions that aren't part of the KODA API but show up regularly in scripts.

Safe array indexing with wrap<N> or .at()

When you index a fixed-size array with a plain int, the Cmajor compiler rejects the access unless the index is guaranteed to be in bounds. The standard fix is to cast the index via wrap<N>, which wraps the value round so it's always valid for an array of size N.

.at(index) does the same job in fewer characters: it takes a plain int and wraps out-of-range values the same way. You can assign through it as well as read from it.

float[8] table = (0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f);

int i = 12;
float v = table[wrap<8>(i)];   // 12 wraps into [0, 8) as 4, so v is 0.4
float w = table.at(i);         // same element, so w is 0.4 too

The difference is cost. wrap<N> guarantees the index is in range as part of its type, so the compiler emits no check at all. .at() checks on every access. Either is fine for occasional lookups; prefer wrap<N> in code that runs every block.

You'll see this most often in event process() when stepping through a precomputed table - for example, looking up an entry in a vibrato LFO waveform.

Fetching and calling need to be separate lines

Writing art.startNote(note) is shorthand for startNote(art, note), and the dot form needs a named variable on its left. So fetching something and calling a function on it need to be separate lines. Put both on one line and the compiler often can't work out which function you meant.

// ✗ May fail to compile
Note n = getArticulation("Straight").startNote(note);
// ✓ Fetch on one line, call on the next
Articulation art = getArticulation("Straight");
Note n = art.startNote(note);

Names you declare share the script with KODA's

Your variables and functions live in the same namespace as every function in this reference. Short, common words - transpose, start, set - are often already taken, and the compiler reports the collision as "The name is already in use", pointing at your declaration. The fix is a more specific name: transposeSemitones instead of transpose.

Instrument (Global)


This is your script's top-level entry point into the instrument. Everything you've built in the KODA app - the Articulations, Variations, Groups, Parameters, Modulators, Mics, and Buses - is reachable from here, alongside instrument-wide controls (volume, tuning, MIDI input filters) and host-supplied info (BPM, play state, time signature, sample rate, elapsed time).

When calling setInstrumentVolume(-6.0f) or setInstrumentTuning(2.0f), you're setting the same values as the instrument-wide volume and tuning controls in the KODA app's GUI.

These are always in scope. Call them from anywhere in your script - no setup, no object to fetch.

Logging

When logging, you'll need to write debug.log(...) to avoid a name collision with the built-in math function for logarithms.

Logging is disabled by default. Enable it once in event initialize() so messages reach the debug console.

KODA's own warnings about your script show in orange whether logging is on or not: a lookup that finds nothing (getBus("Rverb")), a value set from its own update event, a Canvas that filled up. Each warning shows once per compile, so one in noteOn doesn't repeat on every note.

A lookup written with a name in quotes is also checked when the script compiles. If the instrument has no bus, parameter, mic, articulation, variation, group, tap, send or modulator by that name, the compile shows a warning at that line.

Example: Log a note's position only when the transport is playing

event initialize()
{
    setLogEnabled(true);          // Without this, debug.log() output is silent
    setIgnoreMidiNotes(false);    // Make sure incoming MIDI notes still play
}

// Triggered every time the user plays a note
event noteOn(NoteData note)
{
    // Skip if the host transport isn't running (no DAW playback)
    if(getIsPlaying())
    {
        // Quarter notes elapsed since the start of the timeline (e.g. 2.5 = halfway through beat 3)
        debug.log("Note played at PPQ:", getPpqPosition());
    }
}

Logging

FunctionReturnsDescription
setLogEnabled(bool enabled) void Enables or disables debug.log() output. Call once in event initialize() to enable.
debug.log(string message) void Logs a message to the debug console (requires setLogEnabled(true)).
debug.log<Type>(string message, Type value) void Logs a message followed by a value (any printable type) to the debug console.

Group Structure Section

This is where the Group Structure (Articulation / Variation / Group) hierarchy you've built in the KODA app becomes reachable from your script. Use these to grab a handle to whichever Articulation, Variation, or Group you want to act on.

FunctionReturnsDescription
getArticulation(int index)
getArticulation(string name)
Articulation Gets an Articulation by 0-based index or by name (names are defined in the instrument's structure).
getArticulations() Articulation[] Returns an array of all articulations in the instrument.
getNumArticulations() int Returns the total number of articulations in the instrument.
getCurrentArticulation() Articulation Returns the currently active articulation (controlled by the CurrentArticulation parameter).
setCurrentArticulation(int index)
setCurrentArticulation(string name)
setCurrentArticulation(Articulation articulation)
void Sets the current articulation by 0-based index, name, or an existing Articulation object. It sets the CurrentArticulation Parameter, so it does nothing when called from event CurrentArticulation itself, and the console says so: a Parameter can't be set from its own event, which could otherwise set it again on every block.

Parameters & Modulators

The Parameters you've defined in Figma and the Modulators wired up in the KODA app's Modulators panel become reachable from your script here. Use these to grab a handle to the Parameter or Modulator you want to read, set, or react to.

FunctionReturnsDescription
getParameter(string name) Parameter Gets a Parameter by name. The name matches what was defined in Figma.
getParameters() Parameter[] Array of every Parameter currently registered in the engine. Iterate to scan them all.
getModulator(int index)
getModulator(string name)
Modulator Gets a Modulator by 0-based index or by name.

Mics

The mic mixer you've configured in the KODA app becomes reachable from your script here. Use these to grab a handle to a specific Mic so you can adjust its gain, pan, solo, or mute from your script.

FunctionReturnsDescription
getMic(int index)
getMic(string name)
Mic Gets a Mic by 0-based index or by name.

Convolution IRs

Your script can read the library's impulse-response .wav files - the same list the Convolution effect shows in its own dropdown - and use them to autopopulate a front-end menu of IRs. They live in the library's IR Samples folder. The index matches Convolution::File, so a menu item's value can route straight to setInsertParameter(slot, Convolution::File, index).

FunctionReturnsDescription
getNumConvolutionFiles() int Returns the number of IR .wav files found in the library's IR Samples folder (0 if the folder is absent or empty). Useful for for-loops that build a menu of every available IR.
getConvolutionFileName(int index) string Returns the display name (extension stripped) of the IR at the given 0-based index (0 … getNumConvolutionFiles() - 1), in the same order as the Convolution effect's dropdown. Returns "" if the index is out of range.

Example: Autopopulate a menu with the library's IRs

(Three things have to be in place before this example will run: a Menu widget named mnuConvolution in your Figma UI, a Convolution insert in slot 0 of the master bus, and at least one .wav in the library's IR Samples folder.)

// Runs once when the instrument loads.
event initialize()
{
    createConvolutionMenu("mnuConvolution");   // must match the Menu widget's name
}

// Build a front-end dropdown from the library's "IR Samples" folder.
Component createConvolutionMenu(string name)
{
    Component menu = getComponent(name);
    menu.clearItems();
    menu.addItem("None", -1);   // -1 clears the IR (pass-through)

    for (int i = 0; i < getNumConvolutionFiles(); i++)
        menu.addItem(getConvolutionFileName(i), i);

    return menu;
}

// The menu value maps directly to the Convolution insert's File parameter.
event mnuConvolution(Parameter parameter)
{
    Bus master = getMasterBus();
    master.setInsertParameter(0, Convolution::File, parameter.getValue());   // slot 0 of the master bus
}

Instrument output

The instrument-wide volume, pan and tuning controls in the KODA app are exposed here. Use these to adjust the global volume, pan or tuning from a script.

FunctionReturnsDescription
setInstrumentGainLinear(float gain) void Sets the global instrument gain (linear). Range: 0.0 (silence) to 4.0 (~+12 dB); 1.0 is unity.
setInstrumentVolume(float decibels) void Sets the global instrument volume in decibels - the same value, and the same range, as the master volume control in the KODA app. Range: -180 dB (silence) to +12 dB; 0 dB is unity. Anything at or below -180 dB is exact silence.TipAlso accepts a Parameter directly: setInstrumentVolume(myVolumeKnob).
setInstrumentPan(float pan) void Sets the global instrument pan. Range: -1.0 (full left) to 1.0 (full right); 0.0 is center. This sets the instrument Amplifier's pan knob itself, replacing the user's setting.TipAlso accepts a Parameter directly: setInstrumentPan(myPanKnob).
setInstrumentTuning(float semitones) void Sets the global instrument tuning in semitones, replacing the user's tuning setting. 0.0 = no change. Range: -24 to +24, the same as the Tune knob; a value past either end is held there.TipAlso accepts a Parameter directly: setInstrumentTuning(myTuneKnob).

MIDI input control

Filter or block specific kinds of incoming MIDI messages at the instrument level. These flags reset to their defaults whenever the script loads or reloads, then the script's initialize() re-asserts whatever it sets - so a call removed from the script never lingers in the engine.

FunctionReturnsDescription
setIgnorePitchBend(bool ignore) void Sets whether to ignore incoming pitch-bend messages. true = ignore, false = process normally.
setIgnoreSustainPedal(bool ignore) void Sets whether to ignore sustain pedal messages. true = ignore, false = process normally.
setIgnoreNoteOns(bool ignoreNoteOns) void Sets whether the instrument ignores incoming note-on events.
setIgnoreNoteOffs(bool ignoreNoteOffs) void Sets whether the instrument ignores incoming note-off events.
setIgnoreMidiNotes(bool ignore) void Sets whether the instrument ignores both note-on and note-off events. Shortcut for calling setIgnoreNoteOns + setIgnoreNoteOffs together.
setNoteOffCancelsDelayedNotes(bool cancel) void Sets whether a note-off cancels notes that are still in their delay phase (haven't started yet).
Taking manual control of routing

When your script routes notes itself - picking an articulation per note, applying script-side modulation, or generating notes programmatically - call setIgnoreNoteOns(true) in event initialize(). Without it, every incoming MIDI note triggers twice: once through the instrument's default routing and again through your startNote() call.

setIgnoreNoteOffs works the same way for releases. Most scripted instruments want both. setIgnoreMidiNotes(true) turns them on together in one call.

Both flags belong to the instrument, not to the script that set them. They are saved with the instrument and restored on load, so a flag switched on by one script stays on after you replace that script with another. KODA's default script template sets setIgnoreNoteOns(true), so most instruments start out ignoring MIDI notes.

Instrument runtime state

Read-only queries about what your instrument is doing right now.

FunctionReturnsDescription
getNumActiveNotes() int Returns the number of currently active notes (across all articulations).
isNoteHeld(int noteNumber) bool Returns true if the given MIDI note number is currently held (key down). Tracks host MIDI only. Script-triggered notes are not counted. false for a number outside 0-127.
getHeldNotes() HeldNotes Returns the current set of held MIDI notes as a HeldNotes value. Tracks host MIDI only. Script-triggered notes are not counted.

Transport state

Read-only queries about the host's current transport state and audio configuration. Note: although you access this from the instrument, the data is being passed in from the host DAW.

FunctionReturnsDescription
getBPM() float64 Returns the host transport's current BPM (beats per minute).
getPpqPosition() float64 Returns the host transport's current position in PPQ (pulses per quarter note). In noteOn and noteOff, the position at the note's own sample.
getTimeSignature() TimeSignature Returns the host transport's current time signature as a TimeSignature struct (numerator + denominator).
getTimeSignatureNumerator() float64 Returns the time signature numerator only (e.g. 4.0 in 4/4 time).
getIsPlaying() bool Returns true if the host transport is currently playing.
getIsRecording() bool Returns true if the host transport is currently recording. Not every DAW reports this. Hosts that don't will return false even while recording.
getIsStandalone() bool Returns true if KODA is running as a standalone application (not loaded as a plugin in a DAW).
getBlockSize() int Returns the audio processing block size for the current block, in samples. Note: this can vary block-to-block depending on the host; don't assume it's constant.
getSampleRate() float64 Returns the audio sample rate in Hz (e.g. 48000.0). It follows the host's audio device; when that rate changes, sampleRateChanged() fires.

The sampleRateChanged() event

event sampleRateChanged() fires when the sample rate getSampleRate() returns has changed since your script last saw it, before any other event in that audio block. By the time it runs, getSampleRate() already returns the new rate. Recompute anything you worked out from the sample rate in initialize(), such as a delay or length held as a number of samples.

It can fire on your script's very first audio block. initialize() runs before any audio, so it sees the rate the script was compiled at, and if the device turns out to run at a different rate, this event follows straight away. A script that computes its sample-based values in one function and calls it from both events is always up to date:

int delaySamples;

void updateRateDependentValues()
{
    delaySamples = int(0.25 * getSampleRate());   // a quarter of a second
}

event initialize()        { updateRateDependentValues(); }
event sampleRateChanged() { updateRateDependentValues(); }

System & environment

Read-only info about the host environment and machine.

FunctionReturnsDescription
getIsRealTime() bool True in a real-time audio context; false during offline/bounce render.
getWrapperType() string Plugin format/wrapper (e.g. "Standalone", "AU", "VST3").
getHostType() string Host/DAW name.
getOperatingSystem() string OS name.
getCpuArchitecture() string CPU architecture (e.g. "arm64", "x86_64").
getCoreCount() int Logical CPU cores.
getPhysicalCoreCount() int Physical CPU cores.
getMemorySizeMB() int Total system RAM in MB.
getUserLanguage() string User's language.
getUserRegion() string User's region.
getBlockTimeSeconds() float64 Duration of one audio block in seconds (block size ÷ sample rate).

Time elapsed & beats

Two clocks, and helpers for sample-counts until the next beat or bar. getSecondsSinceStart() counts the time the script has run, whether or not the host is playing. getTransportTimeSeconds() is where the host's playhead is: it stands still while the transport is stopped and jumps when the user moves the playhead or loops. Reach for the samples versions for sample-accurate scheduling (they combine naturally with getBeat(), getNextBeat(), and getBlockSize()); reach for the seconds versions for logging or human-readable duration checks.

In noteOn and noteOff, the transport's position (getTransportTimeSamples(), getPpqPosition(), getNextBeat(), getNextBar()) is the position at the note's own sample, so a note that arrives late in an audio block reads where the song is when it plays. A delay counts from that sample too, so note.setDelaySamples(getNextBeat()) starts a note on the next beat, and so does a Pattern started there. The same holds in a Parameter's event when the change comes from a MIDI controller, pitch bend, aftertouch, a key switch or the DAW's automation: it reads the position at the change's own sample, and a note played from it starts there. Every other event, a change made in KODA's interface for instance, reads the position at the start of its audio block. getEventOffset() says where in the block the event is.

FunctionReturnsDescription
getEventOffset() int Returns the sample inside the current audio block that the event being handled sits at, counted from 0, the block's first sample. In noteOn and noteOff, the note's sample. In a Parameter's event, the change's sample when it comes from a MIDI controller, pitch bend, aftertouch, a key switch or the DAW's automation. 0 for every other event. A DAW that doesn't send its automation with a position, or sends it once per audio block, gives 0 too.
getSamplesSinceStart() int64 Returns how long the script has been running, in samples: 0 in initialize(), then the start of the current audio block. It counts whether or not the transport is playing, and starts again from 0 when the script is recompiled.
getSecondsSinceStart() float64 As getSamplesSinceStart(), in seconds. Use it for timeouts and "first second after loading" windows.
getTransportTimeSamples() int64 Returns the host transport's position, in samples. It stands still while the transport is stopped and jumps when the user moves the playhead or loops. In noteOn and noteOff, the position at the note's own sample.
getTransportTimeSeconds() float64 As getTransportTimeSamples(), in seconds.
getTimeElapsedSamples() int64 The earlier name for getTransportTimeSamples(), kept for existing scripts. Despite the name, it is the transport position, not the time since the script started: for that, use getSamplesSinceStart().
getTimeElapsedSeconds() float64 The earlier name for getTransportTimeSeconds(), kept for existing scripts. For the time since the script started, use getSecondsSinceStart().
getSamplesPerBeat() float64 The same as getBeat(), with the unit in its name.
getBeat() float64 Returns the length of one beat in samples (at the current host BPM and sample rate). Returns 0 until the host reports a tempo, so 0 in initialize().
getNextBeat() int Returns the number of samples remaining until the next quarter-note beat (the unit getBeat() measures). Returns 0 exactly on a beat. In noteOn and noteOff, counted from the note's own sample, as a delay set on the note is. While the transport is stopped, counted from where the playhead is parked: check getIsPlaying() first when the wait only makes sense while the song plays.
getNextBar() int Returns the number of samples remaining until the next bar line, following the host's time signature (a 6/8 bar is three quarter notes long). Returns 0 exactly on a bar line. In noteOn and noteOff, counted from the note's own sample, as a delay set on the note is. While the transport is stopped, counted from where the playhead is parked, as getNextBeat() is.

Note length helpers

Length of musical note durations in samples, based on the host BPM (and time signature for bars). Useful for scheduling delays and lengths in rhythmic units.

FunctionReturnsDescription
getBar() float64 Length of one bar in samples (depends on time signature and BPM). getSamplesPerBar() is the same, with the unit in its name.
getWholeNote() float64 Length of a whole note in samples.
getHalfNote() float64 Length of a half note in samples.
getHalfNoteTriplet() float64 Length of a half-note triplet in samples.
getQuarterNote() float64 Length of a quarter note in samples.
getQuarterNoteTriplet() float64 Length of a quarter-note triplet in samples.
get8thNote() float64 Length of an 8th note in samples.
get8thNoteTriplet() float64 Length of an 8th-note triplet in samples.
get16thNote() float64 Length of a 16th note in samples.
get16thNoteTriplet() float64 Length of a 16th-note triplet in samples.
get32ndNote() float64 Length of a 32nd note in samples.
get32ndNoteTriplet() float64 Length of a 32nd-note triplet in samples.

Example: Print the host's sample rate and tempo

initialize() runs before the first block of audio, so anything the host supplies - sample rate, BPM, time signature, transport position - is still 0 there. Read it from process() or noteOn() instead. The flag below keeps it to a single log line.

bool loggedHostInfo;

event initialize() { setLogEnabled(true); }   // Without this, debug.log() output is silent

// Runs once per block of 32 samples, after the host has supplied its info
event process()
{
    if (!loggedHostInfo)
    {
        debug.log("Sample rate:", getSampleRate());
        debug.log("BPM:", getBPM());
        loggedHostInfo = true;
    }
}

Parameter


The Parameters you've created in Figma - knobs, sliders, buttons, etc. - become reachable from your script here. Use these to grab a handle to whichever Parameter you want to read, set, or react to.

  • Access a parameter inside its specific callback: event <ParameterName>(Parameter parameter). There is no catch-all event for every parameter: to handle several in one place, have each named event call a shared function of your own.
  • Or, for use outside the callback, create a global Parameter via getParameter("Name").

A Parameter's name also becomes an identifier inside the script, so it must not be a Cmajor keyword or a name this reference already uses: a type such as Colour or Note, a function such as start or getComponent, an event such as process. Such a name breaks the compile. A parameter name that is no identifier at all (one with a space, say) still works but gets no event <ParameterName>, so the script cannot react to its changes; give any Parameter the script must react to a name that is a valid identifier.

Parameter expression = getParameter("Expression");   // Expression is a built-in parameter. Swap in your own.
float currentExpression = expression.getValue();

Reading values

(Where multiple functions are listed in the below tables, they do the same thing.)

FunctionReturnsDescription
getValue()
get()
float Returns the Parameter's current value as a float.
getIntValue()
toInt()
int Returns the Parameter's current value rounded to the nearest integer.
getBoolValue()
isTrue()
bool Returns true if the Parameter's current value is greater than 0.5, otherwise false.
getValueNormalized() float Returns the Parameter's current value normalized to the 0.0-1.0 range, based on its min and max.
getValueInverted(float& value) void Writes the inverted-normalized value (max − normalized × range) into the supplied reference.

Range & identity

FunctionReturnsDescription
getId() Identifier Returns the Parameter's unique identifier. Use to compare against another Parameter's ID (e.g. inside a function that several named event <ParameterName>(...) handlers share, to identify which Parameter changed).
getName() string Returns the Parameter's name as defined in Figma. Returns "Invalid Parameter" if the ID is out of range.
getMinValue() float Returns the Parameter's minimum value as set in Figma. Returns 0.0 if the ID is invalid.
getMaxValue() float Returns the Parameter's maximum value as set in Figma. Returns 1.0 if the ID is invalid.
getDefaultValue() float Returns the Parameter's default value as set in Figma. Returns 0.0 if the ID is invalid.
getRange() float Returns the Parameter's range (max − min).
idIsValid() bool Returns true if the Parameter's ID falls within the valid range.
isEqualTo(Parameter other) bool Returns true if this Parameter has the same ID as other. Useful inside a function that several named Parameter events share, when you need to tell which Parameter changed.

Setting values

FunctionReturnsDescription
setValue(float newValue)
setValue(int newValue)
setValue(bool newValue)
void Sets the Parameter's value, clamped to its min/max range. Bool true = 1.0, false = 0.0.NoteCalling setValue() from within the Parameter's own named event handler is not allowed (logs a warning and is ignored). To change a Parameter in reaction to its own change, defer the write to viewRefresh() or process().NoteA setValue() that changes the value fires the Parameter's event on the next block. Several calls in one block fire it once, with the last value, and not at all if the value ends the block where it started.

Reacting to parameter changes

To run code when a Parameter's value changes, write a named event handler. The handler's name must match the Parameter's name (the string passed to getParameter). KODA sends each change to its own handler automatically.

A handler may name a Parameter the instrument doesn't have yet, for example in a script shared between instruments, or one written before the Parameter is added. The script still compiles, with a warning at the handler, and the handler never runs until a Parameter with that name exists. Since names are matched exactly, the same warning also catches a misspelled handler name.

The event runs once per change, with the new value already on the parameter. Read it with parameter.getValue() / parameter.getIntValue() / parameter.getBoolValue(), or pass the parameter directly to any setter that accepts a Parameter overload (see Parameter Convenience).

Example: Using the Expression parameter to control current articulation volume

event Expression(Parameter parameter)
{
    Articulation art = getCurrentArticulation();  // Get handle to current articulation
    art.setGainLinear(parameter); // Set the volume of the articulation
}

Articulation, Variation & Group


Every KODA instrument's samples are organized into a three-level container hierarchy:

  • Articulation - the top-level grouping, typically a name for a playing style ("Sustain", "Staccato", "Pizzicato"). Switching articulations via the keyswitch UI changes which Articulation plays, as well as the elements contained within.
  • Variation - a mid-level container inside an Articulation. Used for things like dynamic layers (pp / mf / ff), vibrato vs. non-vibrato, or alternate takes.
  • Group - the bottom-level container inside a Variation. Where the actual sample mappings live. The level you'd reach to manipulate the insert FX chain attached to those samples.

All three containers share most of the same functions - identity / state, gain / pan, tuning / transposition, sample loading, note triggering, and per-container parameters, so they're documented together below. Three subsections at the end cover the per-type extras: navigating a parent's children (Articulation, Variation) and the insert FX chain (Group).

You can use the structure however you like. That said, structuring your articulations in the Articulations section will give KODA automatic awareness of what articulations are available and what the user currently has selected, which lets you harness some automatic functionality for free. Similarly, placing your release tails on the Group level allows you to use built-in release tail trigger functionality.

Get a handle via getCurrentArticulation(), getArticulation(), articulation.getVariation(), or variation.getGroup().

Example: Log which articulation received each note

event initialize()
{
    setLogEnabled(true);          // Without this, debug.log() output is silent
    setIgnoreMidiNotes(false);    // Make sure incoming MIDI notes still play
}

// Fires every time a note is played
event noteOn(NoteData note)
{
    // Reach into the currently-active articulation and log its name
    Articulation art = getCurrentArticulation();
    debug.log("Note routed to articulation:", art.getName());
}

Example: Alter current articulation volume/pan/tuning with sustain pedal

event initialize()
{
    setLogEnabled(true);          // Without this, debug.log() output is silent
    setIgnoreMidiNotes(false);    // Make sure incoming MIDI notes still play
}

// Fires whenever the sustain pedal moves (built-in, MIDI CC 64 by default)
event SustainPedal(Parameter parameter)
{
    Articulation art = getCurrentArticulation();

    if(parameter.isTrue())      // pedal down
    {
        art.setVolume(-6.0f);       // 6 dB below unity
        art.setPan(-0.5f);          // half left
        art.setTuningCents(50.0f);  // a quarter-tone sharp

        debug.log("Trimmed:", art.getName());
    }
    else                        // pedal up: back to normal
    {
        art.setVolume(0.0f);        // unity
        art.setPan(0.0f);           // centered
        art.setTuningCents(0.0f);   // no offset

        debug.log("Restored:", art.getName());
    }
}
Shared setter pattern

Most setter functions on Articulation, Variation, and Group (gain, pan, tuning variants, transposition, active child, insert parameters) accept either a primitive value or a Parameter directly. See the Parameter convenience at the top of this reference.

Identity & state

FunctionReturnsDescription
getName() string Returns the container's name as defined in the instrument (e.g. "Sustain").
getIndex() int Returns the container's 0-based index within its parent. (Articulation's parent is the instrument itself.)
isIdValid() bool Returns true if this handle refers to a real container in the instrument. Use as a null check before calling functions on the handle.
validate() void Logs whether this handle is valid (and its name if so) to the console. Useful while debugging name lookups.
getTypeName() string Returns the type name as a string ("Articulation", "Variation", or "Group"). Useful for generic logging.

Gain & pan

Gain, pan and tuning are the item's own volume, pan and tuning knobs in KODA. A setter moves the knob, replacing what the user set, and a getter reads where the knob is now: what the instrument holds when your script starts, then whatever your script or the user set last.

FunctionReturnsDescription
setGainLinear(float gain) void Sets gain (linear). Range: 0.0 (silence) to 4.0 (~+12 dB); 1.0 is unity.
setVolume(float decibels) void Sets volume in decibels - the same value, and the same range, as the volume knob on this item in the KODA app. Range: -180 dB (silence) to +12 dB; 0 dB is unity. Anything at or below -180 dB is exact silence.TipAlso accepts a Parameter directly: art.setVolume(myVolumeKnob).
setPan(float pan) void Sets pan position. Range: -1.0 (full left) to 1.0 (full right); 0.0 is center. Clamped.
getGainLinear() float Returns the gain the item's volume knob is at, linear. Range: 0.0-4.0.
getPan() float Returns the position the item's pan knob is at. Range: -1.0-1.0.

Tuning & transposition

Tuning shifts the pitch of a sample. Transposition offsets the position of the note to trigger a different sample.

FunctionReturnsDescription
setTuningSemitones(float semitones) void Sets tuning in semitones. 0.0 = no change. Range: -24 to +24, the same as the Tune knob; a value past either end is held there.
setTuningCents(float cents) void Sets tuning in cents. 100 cents = 1 semitone; 0.0 = no change. Range: -2400 to +2400.
setTuningFactor(float speedRatio) void Sets tuning as a speed/frequency ratio. 1.0 = no change; 2.0 = one octave up; 0.5 = one octave down. Range: 0.25 to 4.0 (two octaves either way). A ratio at or below 0 is no change; a negative one also warns once in the console, since it is usually semitones passed by mistake.
setTransposition(int transposition) void Sets transposition in semitones by changing the note number played (not by pitch-shifting). 0 = no change. Range: -127 to +127; a value past either end is held there.
getTuningSemitones() float Returns the tuning the item's tuning knob is at, in semitones. 0.0 = no change.
getTransposition() float Returns the transposition your script set, in semitones. There is no knob for it, so it is 0.0 until your script sets one.

Sample loading/purging

Load or purge this container's samples from memory. Useful for templating instruments that hold many articulations but only need a few in memory at once.

FunctionReturnsDescription
loadSamples() void Loads this container's samples into memory if they aren't already. Calling it on a container that is already loaded does nothing, so it is safe to repeat.
purgeSamples() void Unloads this container's samples from memory (frees RAM). Its notes stay silent until loadSamples() has loaded it again.
Good to know

Both work in the background: loading can take seconds, and notes played before it finishes stay silent. So load sounds before they're needed, for example those a key switch can jump to.

The purged state is saved with the instrument and with the DAW project. A container saved as purged loads nothing when the instrument opens, which makes opening faster; the script then loads what it needs, e.g. in initialize().

A purged parent wins: purging an Articulation or Variation purges everything beneath it, and loadSamples() on a Group has no effect while its parent is purged.

A script can't ask whether a container is loaded, so keep track of what it has loaded.

Example: Keep only the selected sound in memory

// One Group per sound, all in the first Variation of the first Articulation,
// saved purged. (Assumes a Menu parameter named "SoundMenu" that picks the Group.)
int loadedSound = -1;   // the Group in memory, -1 = none yet

event initialize()
{
    setIgnoreNoteOns(true);   // the script plays each note on the loaded sound
    Parameter menu = getParameter("SoundMenu");
    selectSound(menu.getIntValue());   // the sound the instrument was saved with
}

event SoundMenu(Parameter parameter)
{
    selectSound(parameter.getIntValue());
}

void selectSound(int sound)
{
    if (sound == loadedSound)
        return;

    Articulation art = getArticulation(0);
    Variation variation = art.getVariation(0);

    if (loadedSound >= 0)
    {
        Group previous = variation.getGroup(loadedSound);
        previous.purgeSamples();   // frees the old sound's memory
    }

    Group next = variation.getGroup(sound);
    next.loadSamples();   // loads in the background
    loadedSound = sound;
}

event noteOn(NoteData note)
{
    if (loadedSound < 0)
        return;

    Articulation art = getArticulation(0);
    Variation variation = art.getVariation(0);
    Group sound = variation.getGroup(loadedSound);
    sound.startNote(note);   // new notes play the loaded Group
}

Keyboard highlight

Overlay this container's mapped range - the exact set of MIDI notes covered by every zone beneath it (across all child Variations and Groups) - on the GUI piano, tinted with a chosen Colour. Handy for showing the user which keys an Articulation, Variation, or Group responds to, e.g. when a menu switches the active Variation. This overlay is transient and independent of the articulation's own mapped-range bar (the DISPLAY checkbox in the KEY RANGES module, addressable from a script as the "Playable Range" name via hideKeyRange()).

FunctionReturnsDescription
showPlayableRange(Colour colour) void Highlights every note this container covers on the GUI piano in colour. Several containers can be highlighted at once. Each keeps its own colour, and when two overlap on a note the most recently shown one wins, so call order acts as draw order (show a small, informative range last to keep it on top of full-keyboard layers). Remove with hidePlayableRange() or clearPlayableRanges().
hidePlayableRange() void Removes this container's playable-range highlight from the GUI piano. No-op if it isn't currently shown.

Playing notes

Trigger and stop notes scoped to this container. A note started on an Articulation or a Variation plays where that layer's note distribution sends it: by default an Articulation sends it to every one of its Variations, and each Variation to every one of its Groups. Notes started on a Group play that Group's samples directly.

FunctionReturnsDescription
createNoteData() NoteData Returns a fresh NoteData struct with this container's indices pre-filled - ready to be customized (velocity, note number, envelope, etc.) and passed to startNote().
startNote(NoteData note)
startNote(int note, float velocity)
startNote(int note, int velocity)
Note Starts a note on this container and returns a Note handle you can use to modify or stop the note while it plays. The simple form takes a MIDI note number (0-127) and a velocity: a float is 0.0-1.0, a whole number is MIDI 0-127, so startNote(60, 100) and startNote(60, 0.79f) play alike; the NoteData form lets you pre-configure envelope, gain, pan, and routing first.
stopNote(NoteData note) bool Stops the matching note (sends it into its release envelope) and returns whether the stop was sent. It stops every voice on that key in the container; to stop one note you started, keep its Note and call note.stop().
stopAllNotes() void Stops every active note belonging to this container.

Parameters & properties

Each container can carry its own set of named parameters (numeric values) and properties (typed values) defined alongside it in the instrument. Both are authored in the GROUP VARIABLES section of the Setup tab, where properties are labelled Constants. Use these to attach per-container settings without polluting the global parameter list - and see Using Constants (properties) and parameters to make templates for the pattern that builds on them.

FunctionReturnsDescription
getParameterValue(string name) float Returns the container's named parameter value as a float. Returns 0.0 if not found.
getParameterIntValue(string name) int Returns the container's named parameter as an integer (cast from float).
getParameterBoolValue(string name) bool Returns the container's named parameter as a bool (true if value > 0.5).
getProperty(string name) string Returns the container's named property as a string. Returns "" if not found.
getIntProperty(string name) int Returns the container's named property as an integer, read as getFloatProperty reads it, then rounded toward zero. A number past an int's range reads as the nearest one an int holds.
getFloatProperty(string name) float Returns the container's named property as a float: the number its text starts with, so "12 semitones" reads as 12. Text that doesn't start with a number reads as 0, and a number too large for a float as the largest one.
getBoolProperty(string name) bool Returns the container's named property as a bool.

Variations Articulation only

Access an Articulation's child Variations.

FunctionReturnsDescription
getVariation(int index)
getVariation(string name)
Variation Gets a child Variation by 0-based index or by name.
getNumVariations() int Returns the number of Variations under this Articulation. Useful for for-loops that iterate over every Variation.

Example: Crossfade between vibrato and non-vibrato

// Fires whenever Vibrato changes (built-in, MIDI CC 2 by default).
// (Assumes the current articulation has Variations named "NonVibrato" and "Vibrato".)
event Vibrato(Parameter parameter)
{
    Articulation art = getCurrentArticulation();
    Variation nonVib = art.getVariation("NonVibrato");
    Variation vib   = art.getVariation("Vibrato");

    float blend = parameter.getValue();

    // 0.0 = full NonVibrato, 1.0 = full Vibrato, in-between = blended
    nonVib.setGainLinear(1.0f - blend);
    vib.setGainLinear(blend);
}

Example: Manually trigger a release-tail Variation when a note is released

The script takes over note handling so it can decide which Variation sounds and when. Left to itself, KODA sends each note-on to every Variation in the articulation, so the tail would sound on the way down as well as the way up.

// (Assumes the current articulation has Variations named "Sustain" and "ReleaseTail".)

float[128] noteOnVelocity;   // remembers how hard each key was struck

event initialize() { setIgnoreMidiNotes(true); }   // Override automatic note handling so we can implement in script

event noteOn(NoteData note)
{
    Articulation art = getCurrentArticulation();
    Variation sus = art.getVariation("Sustain");

    noteOnVelocity.at(note.getNoteNumber()) = note.getVelocity();   // Stash it for the release tail
    sus.startNote(note);
}

// Fires when the user lifts a key
event noteOff(NoteData note)
{
    Articulation art = getCurrentArticulation();
    Variation sus = art.getVariation("Sustain");
    Variation tail = art.getVariation("ReleaseTail");

    sus.stopNote(note);   // Stop sustain manually

    // A note-off carries release velocity, so swap in the note-on velocity
    note.setVelocity(noteOnVelocity.at(note.getNoteNumber()));
    tail.startNote(note); // Trigger release tail manually
}

Because the script starts the note, it also has to stop it - nothing releases it otherwise. The noteOnVelocity array lives at module level so it persists between the two events, and .at() is used because a plain int index into a fixed-size array won't compile (see Cmajor patterns you'll see).

Release tails without a script

Setting a Group's trigger type to Release does this natively: the group stays silent at note-on and sounds at note-off, using the recorded note-on velocity, with its own Release Level and sustain-pedal modes. Reach for the script when you need something that setting can't express - picking between several tails, or skipping the tail depending on how long the key was held.

Groups Variation only

Access a Variation's child Groups.

FunctionReturnsDescription
getGroup(int index)
getGroup(string name)
Group Gets a child Group by 0-based index or by name.
getNumGroups() int Returns the number of Groups under this Variation. Useful for for-loops that iterate over every Group.

Insert FX Group only

Each Group can host a chain of insert FX (compressor, EQ, reverb, etc.) defined in the instrument. These functions let you modulate individual insert parameters or bypass entire inserts at runtime. To change which effect a slot holds, empty it, or reorder the chain, use the slot's Insert: group.getInsert(slot). A Group's effects run once per note, so it takes only the effects that can: see InsertType.

FunctionReturnsDescription
setInsertParameter(int insertIndex, int paramIndex, value) void Sets a parameter on an insert FX. insertIndex: 0-based insert slot. paramIndex: the effect's constant (Filter::Cutoff), which the engine refuses on a slot holding another effect, or a plain index. The same write as getInsert(insertIndex).setParameter(...). value: float, int, or bool depending on the parameter type.TipAlso accepts a Parameter directly: group.setInsertParameter(0, 0, myKnob).
setInsertBypassed(int insertIndex, bool bypassed) void Bypasses (or un-bypasses) an entire insert FX slot. true = bypassed, false = active.TipIf you're wiring this to an "Enabled" button (where true means the user wants the effect on), invert the value: setInsertBypassed(0, !param.getBoolValue()).

Example: Darken soft notes with a velocity-driven filter cutoff

// (Assumes first insert of the Group is a Filter effect.)

event initialize() { setIgnoreMidiNotes(false); }   // Make sure incoming MIDI notes still play

// Fires every time a note is played
event noteOn(NoteData note)
{
    Articulation art = getCurrentArticulation();
    Group group = art.getGroup(0);

    // Lower-velocity notes get a lower cutoff (darker tone, mimicking a softer note)
    float cutoffHz = 200.0f + note.getVelocity() * 10000.0f; // Adjust to taste, depending on the instrument
    group.setInsertParameter(0, Filter::Cutoff, cutoffHz);
}

Each effect publishes named constants for its own parameters - Filter::Cutoff, Filter::Resonance, and so on. A constant knows which effect it belongs to: written to a slot that holds a different effect (after the user reordered the chain, say), it changes nothing, and the console says so once. To find the slot that holds an effect wherever it is, use findInsert(InsertType::Filter). A plain whole number still works as a parameter index, unchecked, which is how a Cmajor patch's own parameters are addressed.

Note

Be aware, the insert changes are applied per-group and not per-note. So in the above example, a user playing a chord with varying velocities will get a cutoff set by the last note played.

Example: Bypass a distortion with the sustain pedal

// Holding the sustain pedal bypasses the distortion on the group's FX insert.
// (Assumes a distortion in the first insert slot of the current articulation's group.)
event SustainPedal(Parameter parameter)
{
    Articulation art = getCurrentArticulation();
    Group group = art.getGroup(0);

    // Pedal pressed = bypass on, pedal released = bypass off
    group.setInsertBypassed(0, parameter.getBoolValue());
}
Technical sidenote

Articulation, Variation, and Group all share the same underlying state representation internally - which is why their gain / pan / tuning functions look identical.

Group is the last level of the AVG hierarchy as exposed via these functions. At the engine level, Groups contain Zones (one per note/velocity region), and Zones contain Voices - alternate samples used for round-robin playback. Zone selection and round-robin cycling are normally handled by the engine automatically. Round robins can be manually overridden per-note via NoteData.forceRoundRobinIndex(); Zones themselves aren't reachable from scripts.

NoteData


A NoteData describes a note before it plays - its pitch, velocity, envelope, timing, and which articulation / variation / group / mic / bus it routes through. KODA hands one to your noteOn and noteOff handlers describing each incoming MIDI note, and you can also build your own by calling createNoteData() on an Articulation, Variation, or Group.

Once a NoteData is configured, trigger it with noteData.start() to play it through its current routing (see Triggering below). A NoteData is just a value. Changing it after the note has started has no effect on the playing note (use the returned Note handle for that).

Always blank a NoteData before you use it

A NoteData you declare yourself starts out full of zeros - zero volume, zero velocity, and every envelope stage at zero - so it plays nothing, silently. Blanking it sets the volume, envelope and routing to "inherit from the Group" and the velocity to full (127). Three ways to get a usable note:

How you get itRoutingWhen to use it
initialize()
(after declaring one)
not set The everyday case. Play it with art.startNote(note) and the Articulation supplies the routing.
a copy of a note
you were handed
copied Echoes and doubled layers. A note from noteOn is already blanked, but you inherit its pitch and velocity too.
createNoteData()
on an Articulation,
Variation, or Group
set for you When the note carries its own destination - queuing it in a Pattern, or starting it with note.start(). On a handle that names nothing, the note has no destination and does not play until setTarget(...) gives it one.

Those are the only ways to get one. A NoteData built from a list of values, such as NoteData n = (0, 1, 2); or NoteData (…), is an error when the script compiles, and so is a Pattern built that way: set a note's values with its setters instead.

Example: Build a note from scratch

// Holding the sustain pedal plays middle C on the current articulation.

Note playing;                       // Handle to the note, so we can stop it again

event SustainPedal(Parameter parameter)
{
    Articulation art = getCurrentArticulation();

    if(parameter.isTrue())          // Pedal down: build a note and play it
    {
        NoteData note;              // Build a note from scratch
        note.initialize();          // Blank it, or it plays silently
        note.setNoteNumber(60);     // Middle C
        note.setMidiVelocity(100);

        playing = art.startNote(note);
    }
    else                            // Pedal up: stop it
    {
        playing.stop();
    }
}
Use the functions

A NoteData's values are read and set only through its functions, such as getVelocity() and setVelocity(). A script that names a value directly, as in note.velocity, doesn't compile: the error names the function to use instead.

Example: Add an octave-up echo to every note

Note[128] echoes;   // One handle per MIDI note, so each echo can be stopped

event initialize() { setIgnoreMidiNotes(false); }   // Original note pressed by user is handled automatically

event noteOn(NoteData incoming)
{
    Articulation art = getCurrentArticulation();

    // Build a copy of the incoming note, an octave higher and half as loud.
    // KODA still triggers the original note normally.
    NoteData echo = art.createNoteData();
    echo.setNoteNumber(incoming.getNoteNumber() + 12);
    echo.setVelocity(incoming.getVelocity() * 0.5f);

    echoes.at(incoming.getNoteNumber()) = art.startNote(echo); // Start echo manually and store note handle
}

// Fires when the user lifts a key
event noteOff(NoteData incoming)
{
    Note echo = echoes.at(incoming.getNoteNumber()); // Retrieve note handle
    echo.stop(); // End echo manually
}

Pitch & velocity

Set or read the note's pitch (note number, tuning offsets, transposition) and velocity. Velocity has two unit conventions exposed as separate function pairs - float (0.0-1.0) and MIDI integer (0-127) - that read and write the same underlying value.

FunctionReturnsDescription
setNoteNumber(int note) void Sets the MIDI note number, 0-127. A note set outside that range doesn't play, and the console says so: it is not moved to the nearest key.
getNoteNumber() int Returns the MIDI note number (before transposition).
getNoteNumberWithTransposition() int Returns the effective MIDI note that will be played (note number + transposition).
getNoteName() string Returns the note name as a string (e.g. "C3", "F#2"). Middle C (MIDI 60) is "C3".
transpose(int interval) void Sets transposition to interval semitones (replaces, doesn't accumulate). Range: -127 to +127; a value past either end is held there.
transposeToNote(int note) void Sets transposition so the note plays as note (e.g. transpose every incoming note to middle C). The transposition it sets holds to -127 to +127, as transpose's does.
getTransposition() int Returns the current transposition in semitones.
setVelocity(float velocity) void Sets velocity as a float. Range: 0.0-1.0 (clamped).
setVelocity(int velocity) void A whole number is a MIDI velocity, 0-127, the same as setMidiVelocity.
setMidiVelocity(int velocity) void Sets velocity from a MIDI value. Range: 0-127.
getVelocity() float Returns velocity as a float (0.0-1.0).
getMidiVelocity() int Returns velocity as a MIDI integer (0-127).
setTuningSemitones(float semitones) void Sets fine-tuning in semitones (continuous, not quantised to MIDI notes). Range: -48 to +48; a value past either end is held there.
setTuningCents(float cents) void Sets fine-tuning in cents. 100 cents = 1 semitone. Range: -4800 to +4800.
setTuningRatio(float ratio) void Sets tuning as a frequency ratio (2.0 = one octave up, 0.5 = one octave down). Range: 0.0625 to 16 (four octaves either way). A ratio at or below 0 is no change; a negative one also warns once in the console, since it is usually semitones passed by mistake.
setPitchShift(float semitones) void Shifts the note's pitch without changing its playback speed or sample timbre, using the time-stretch engine. 0.0 = no shift. Range: -24 to +24 semitones. Distinct from setTuning*, which retunes by changing the sample's playback rate (faster/slower, with a shifted timbre).
getTuningSemitones()
getTuningCents()
getTuningRatio()
float Return the note's tuning in semitones, in cents, or as a frequency ratio. A note whose tuning was never set reads 0, 0 and 1.0.
getPitchShift() float Returns the pitch shift set with setPitchShift, in semitones.

Gain & pan

FunctionReturnsDescription
setGainLinear(float gain) void Sets gain (linear). Range: 0.0 (silence) to 4.0 (~+12 dB); 1.0 is unity. Clamped.
getGainLinear() float Returns the note's gain (linear). A note whose gain was never set reads 1.0, the unity it plays at.
setVolume(float decibels) void Sets the note's volume in decibels. Range: -180 dB (silence) to +12 dB; 0 dB is unity. Anything at or below -180 dB is exact silence.TipAlso accepts a Parameter directly: note.setVolume(myVolumeKnob).
getGainDecibels() float Returns the note's gain in decibels. A note whose gain was never set reads 0 dB.
setPan(float pan) void Sets pan position. Range: -1.0 (full left) to 1.0 (full right); 0.0 is center. Clamped.
getPan() float Returns the pan position.

Delay, length & stretch

Control where in the sample to start playback (sample start), how long to delay before triggering, and how time-stretched it is.

FunctionReturnsDescription
setDelaySamples(int delaySamples) void Sets the delay before the note starts, in audio samples. Replaces a delay set with setDelayMS or setDelaySeconds: the last call wins.
setDelayMS(float delayMS) void Sets the delay before the note starts, in milliseconds. A NoteData built ahead of time keeps the right delay if the sample rate changes. Replaces a delay set with setDelaySamples: the last call wins.
setDelaySeconds(float delaySeconds) void Sets the delay before the note starts, in seconds. Works as setDelayMS does.
getDelaySamples()
getDelayMS()
getDelaySeconds()
int
float
float
Return the note's delay, however it was set, in samples, milliseconds or seconds at the engine's current sample rate.
setLengthMS(float lengthMS) void Schedules the note to release itself this many milliseconds after it starts. 0 = no scheduled release. Absolute time - a later tempo change doesn't rescale it.
setLengthSeconds(float lengthSeconds) void Schedules the note's release, in seconds.
setLengthSamples(int lengthSamples) void Schedules the note's release, in audio samples.
setLengthBeats(float64 lengthInBeats) void Schedules the note's release a number of beats after it starts, converted using the tempo at the moment of the call - so call it in the same handler that fires the note. Reads 0 in initialize(). For a gate that keeps tracking tempo inside a Pattern, use addNote's length argument instead.
getLengthMS()
getLengthSeconds()
getLengthSamples()
float
float
int
Return the note's scheduled length. 0 when the note has no scheduled note-off.
setSampleStartMS(float sampleStartMS) void Sets the starting offset within the source sample, in milliseconds. 0 = play from the beginning. It takes the place of the group's Start Position for this note, and the Start Position's modulation is skipped. Use it when the start is a fixed time into the sample, such as trimming a legato transition's pre-roll: unlike setSampleStartPercent, it does not move when the Start Range changes. It is also the only way to start a note inside a beat slice (see setSlice). Milliseconds are used rather than samples because the triggered voice may run at a different sample rate than the engine. In Normal (streaming) playback the start can reach at most the voice's Start Range (its zone's own, or else the group's), which is the window preloaded for it - set Start Range to at least the furthest start the script uses. In Sampler and TimeStretch modes the whole sample is in memory and any start is honoured. Clears a start set with setSampleStartPercent: the last call wins.
setSampleStartPercent(float percent) void Sets where the note starts as a percentage of each voice's Start Range (its zone's own, or else the group's), 0 to 100: 50 starts it halfway through the range. It takes the place of the group's Start Position for this note, and the Start Position's modulation is skipped. Always inside the Start Range, so it is always preloaded, in every playback mode. With a Start Range of 0 the note starts at the beginning. A slice note ignores it: a sliced voice has no Start Range. Clears a start set with setSampleStartMS: the last call wins.
getSampleStartMS()
getSampleStartPercent()
float Return the start set with setSampleStartMS or setSampleStartPercent. Each is -1 when the start isn't set that way: the two replace each other.
setStretchRatioByLength(float stretchRatio) void Sets time-stretch as a length ratio. 1.0 = no change; 2.0 = twice as long.
setStretchRatioBySpeed(float speedRatio) void Sets time-stretch as a speed ratio. 1.0 = no change; 2.0 = twice as fast (half as long).
getStretchRatioByLength()
getStretchRatioBySpeed()
float Return the note's stretch as a length factor, or as the speed factor it amounts to. A note whose stretch was never set reads 1.0.
getTimeElapsedSeconds() float For notes already playing, returns the time elapsed since the note started, in seconds.

Envelope

Override the note's envelope stages individually, or apply a whole envelope at once via setEnvelope(). Curve exponents take values in the range 0.25-4.0: below 1.0 = convex (fast start, slow finish), 1.0 = linear, above 1.0 = concave (slow start, fast finish).

FunctionReturnsDescription
setPreDelaySeconds(float preDelay) void Sets pre-delay before the envelope begins, in seconds.
setAttackSeconds(float attack) void Sets attack time in seconds. 0.0 = instant.
setAttackSeconds(float attack, float curve) void Sets attack time and curve exponent together.
setHoldSeconds(float hold) void Sets hold time in seconds (after attack, before decay begins).
setDecaySeconds(float decay) void Sets decay time in seconds.
setDecaySeconds(float decay, float curve) void Sets decay time and curve exponent together.
setSustain(float sustain) void Sets sustain level. Range: 0.0 (silence) to 1.0 (full level). Clamped.
setReleaseSeconds(float release) void Sets release time in seconds.
setReleaseSeconds(float release, float curve) void Sets release time and curve exponent together.
setAttackCurve(float curve)
setDecayCurve(float curve)
setReleaseCurve(float curve)
void Set one stage's curve exponent on its own, the curve the two-argument stage setters take.
getPreDelaySeconds()
getAttackSeconds()
getHoldSeconds()
getDecaySeconds()
getReleaseSeconds()
float Return a stage's length in seconds, or -1 when the note inherits the Group's.
getAttackCurve()
getDecayCurve()
getReleaseCurve()
float Return a stage's curve exponent, or -1 when the note inherits the Group's.
getSustain() float Returns the sustain level, or -1 when the note inherits the Group's.
setEnvelope(Envelope envelope) void Applies an entire envelope (all stages and curves) at once. Every field is copied, so blank the Envelope first with envelope.initialize() and set only the stages you want to change: a field left at zero is a real zero (a zero sustain silences the note after its decay).
getEnvelope() Envelope Returns every stage and curve at once, the pair to setEnvelope. Fields the note inherits read -1.
Envelope.initialize() void Sets every stage and curve of an Envelope to "inherit from the Group". Call it right after declaring one.
scheduleRelease(float timeToRelease, float releaseTime, float releaseCurve) void Schedules an automatic release a fixed time after the note starts. Older helper - prefer a length setter plus setReleaseSeconds(), which do the same job as separate calls.

Behavior flags

FunctionReturnsDescription
setOneShot(bool oneShot) void Sets the note's trigger mode, the two-way shorthand for setTriggerMode. true = ONE SHOT: the note plays through to completion regardless of MIDI note-off. false = ENV: the note respects note-off, overriding a group set to ONE SHOT or AHD. Leave it unset to inherit the group's TRIGGER mode (ENV, ONE SHOT or AHD).
setTriggerMode(TriggerMode mode) void Sets how the note's envelope answers its note-off: TriggerMode::Env, TriggerMode::OneShot or TriggerMode::AHD, the Amplifier's ENV, ONE SHOT and AHD. TriggerMode::Inherit, the default, plays the group's own mode.
getTriggerMode() TriggerMode Returns the trigger mode set with setTriggerMode or setOneShot, or TriggerMode::Inherit.
setIsNoteOff(bool isNoteOff)
isNoteOff()
void
bool
Marks the note as a note-off, and reads it back. startNote and stopNote set it for you.
forceRoundRobinIndex(int rr) void Overrides automatic round-robin cycling and plays the specified round-robin index for this note. rr: 0-based index into the available round robins; an index past the last one (or below 0) wraps around. The forced round robin counts as the one just played, so the automatic cycle carries on from it: in Sequential mode the next note plays the round robin after it, and in Random mode the next note avoids it.
getForcedRoundRobinIndex() int Returns the round robin forceRoundRobinIndex chose, or -1 when none is forced.
clearForcedRoundRobin() void Undoes forceRoundRobinIndex: the zone's own round robin picks again.

Routing

Direct the note through a specific articulation, variation, group, mic, or bus. The setTarget(...) overloads are the most ergonomic. They set the relevant indices in one call. For low-level control, use the individual index setters; indices of -1 mean "no override - use the engine's default routing".

FunctionReturnsDescription
setTarget(Articulation articulation)
setTarget(Variation variation)
setTarget(Group group)
void Routes the NoteData through the given Articulation, Variation, or Group. Indices below the target's hierarchy level are cleared (e.g. passing a Variation sets the articulation and variation indices but clears the group index). A handle that names nothing leaves the routing as it was.
setArticulationIndex(int index) void Low-level: routes through the Articulation at this 0-based index.
setVariationIndex(int index) void Low-level: routes through the Variation at this 0-based index.
setGroupIndex(int index) void Low-level: routes through the Group at this 0-based index.
setMicIndex(int index) void Forces the note through a specific Mic (by 0-based index).
getMicIndex() int Returns the Mic set with setMicIndex, or -1 when the note plays through every mic.
setBusIndex(int index) void Routes the note's output to a specific Bus (by 0-based index).
getBusIndex() int Returns the Bus set with setBusIndex, or -1 when the note follows its mics' routing.
getGroupType() GroupType Returns the most specific routing level set on this NoteData: GroupType::Group, ::Variation, ::Articulation, or ::Invalid if no routing is set.
getArticulation() Articulation Returns the Articulation this NoteData routes through.
getVariation() Variation Returns the Variation this NoteData routes through.
getGroup() Group Returns the Group this NoteData routes through.

Beat slices

A voice with slice markers is sliced. A plain note on it plays its slices on the host's grid, each starting on its beat. Set a slice on the note instead and it plays only that slice: from the slice's marker to the next one, and then it ends, whether or not the key is still down. No key picks a slice by itself, so a script maps keys (or anything else) to slices with setSlice.

FunctionReturnsDescription
setSlice(int sliceNumber) void Plays only this slice of a sliced voice, counted from 1. 0 (the default) = no slice: the note plays the voice's grid, or the whole voice when it isn't sliced. A slice past the voice's last is silent, and so is any slice but 1 on a voice that isn't sliced. A start offset (setSampleStartMS) applies inside the slice; the group's Start Position doesn't. The note pitches with its key like any other note: to play a slice at its recorded pitch, transposeToNote the zone's root.
getSlice() int Returns the slice set with setSlice, or 0 for none.

In a zone whose slice choke is on (the default), a new slice note fades out that zone's sounding slice notes, so the slices play one at a time. Plain notes are never choked. Round robins can hold different slices: a slice past a round robin's last is silent for it.

Example: Play one slice per key, at its recorded pitch

event initialize() { setIgnoreNoteOns(true); }   // The script plays every note

event noteOn(NoteData note)
{
    let firstKey = 48;   // C2 plays slice 1, C#2 slice 2, and so on
    let rootKey = 60;    // The sliced zone's root note

    if (note.getNoteNumber() < firstKey)
        return;

    note.setSlice(note.getNoteNumber() - firstKey + 1);
    note.transposeToNote(rootKey);   // Every key plays the root's zone, at recorded pitch
    note.start();
}

Triggering

Convert a configured NoteData into a playing note. The note plays through the routing set on the NoteData (via setTarget(...) or inherited from the incoming noteOn event).

FunctionReturnsDescription
initialize() void Blanks the note so it inherits the Group's envelope, volume and tuning, at full velocity. Call it right after declaring a NoteData. See Always blank a NoteData before you use it.
startNote()
start()
Note Triggers this NoteData and returns a Note handle you can use to modify or stop the note while it plays. Both read the routing off the note itself, so the note must already know its destination - from createNoteData() or setTarget(...). To play a note that has no routing of its own, pass it to an Articulation, Variation, or Group instead: art.startNote(note).

Example: Make soft notes longer and breathier

event initialize() { setIgnoreNoteOns(true); }  // Override automatic note-on handling

event noteOn(NoteData note)
{
    if(note.getVelocity() < 0.4f)
    {
        // Slow swell, gentle release for soft notes (curve 2.0 = slow start / fast end)
        note.setAttackSeconds(0.5f, 2.0f);
        note.setReleaseSeconds(2.0f, 2.0f);
    }

    // Use the routing already on the incoming note - no need to fetch the articulation
    note.start();
}

Note


A Note is a handle to a currently-playing note. You get one back from startNote() on an Articulation, Variation, or Group, and you use it to modify or stop that specific note while it's still sounding.

Every Note function returns a bool: true if the note was still active and the change was applied, false if the note had already finished. That return value lets you safely call functions on a Note without first checking isActive().

Example: Apply a longer release to every incoming note

event initialize() { setIgnoreNoteOns(true); }  // Override automatic note-on handling

event noteOn(NoteData note)
{
    Articulation art = getCurrentArticulation();
    Note playing = art.startNote(note);

    // Stretch the release out to 2 seconds with a slightly concave curve (slow start)
    playing.setReleaseSeconds(2.0f, 1.5f);
}

Lifecycle

FunctionReturnsDescription
isActive() bool Returns true while the note sounds, through its release: after stop() it stays true until the release has finished. To ask whether the key is up, use isReleased.
isReleased() bool Returns true once the note's release has begun, or the note has ended: after stop(), and also when a length set on it runs out or a stopNote() on its key releases it. KODA learns of those from the engine, so isReleased() turns true from the next block, and in time for your noteReleased handler.
stop() bool Triggers the note's release stage using its currently-configured envelope. Returns true if the note was active when stopped.
stop(float releaseSeconds, float curveExponent) bool Stops the note with this release, in one call. A release set after stop() comes too late, so this is the way to fade a note out with a release of its own.
getNoteNumber()
getVelocity()
getMidiVelocity()
int / float / int What the note was started with: its key, and its velocity as 0.0-1.0 or 0-127.
getTypeName() string Returns the type name as a string ("Note"). Useful for generic logging.
Pattern

To fade an active note out with a custom timing - for legato slurs, voice stealing, or any "active fade-out from script" - call stop(releaseSeconds, curveExponent). It sets the release and triggers it, in that order.

Calling stop() alone uses whatever release was configured when the note started. Calling setReleaseSeconds() alone changes what will happen when the note is later released (e.g. when the user lifts the key), but doesn't itself produce sound. After stop() it returns false and changes nothing, with a console warning: the release has already begun.

Per-note properties

Adjust gain, tuning, length, time-stretch, pan, and release on a single note while it's playing. Each function returns true if the change landed (the note was still active), false if the note had already finished.

Absolute setters

These setters overwrite the property's current value rather than adding to it. Each call replaces what the previous call set, so if two modulators want to influence the same property in the same audio block - e.g. a legato pitch glide running alongside a vibrato LFO - sum their contributions in script and apply the total with a single call.

FunctionReturnsDescription
setGainLinear(float gain) bool Sets the note's gain (linear). Range: 0.0 (silence) to 4.0 (~+12 dB); 1.0 is unity. A negative value is decibels by mistake: it silences the note, with a console warning.
setVolume(float decibels) bool Sets the playing note's volume in decibels. Range: -180 dB (silence) to +12 dB; 0 dB is unity. Anything at or below -180 dB is exact silence.
setTuningSemitones(float semitones) bool Sets the note's tuning offset in semitones. 0.0 = no change. Range: -48 to +48; a value past either end is held there.
setTuningCents(float cents) bool Sets the note's tuning offset in cents. 100 cents = 1 semitone. Range: -4800 to +4800.
setTuningRatio(float ratio) bool Sets tuning as a frequency ratio. 1.0 = no change; 2.0 = one octave up. Range: 0.0625 to 16 (four octaves either way). A ratio at or below 0 is no change; a negative one also warns once in the console, since it is usually semitones passed by mistake.
setPitchShift(float semitones) bool Shifts the playing note's pitch without changing its playback speed or sample timbre, using the time-stretch engine. 0.0 = no shift. Range: -24 to +24 semitones. Distinct from setTuning*, which retunes by changing the sample's playback rate.
setLengthSeconds(float lengthSeconds) bool Sets the total length of the note in seconds. No hard clamp.
setLengthMS(float lengthMS)
setLengthSamples(int lengthSamples)
setLengthBeats(float64 lengthInBeats)
bool The same in milliseconds, samples, or beats at the tempo in effect now, as on NoteData.
setStretch(float stretch) bool Sets the time-stretch factor. 1.0 = no change; > 1.0 = slower playback; < 1.0 = faster playback.
setStretchRatioByLength(float stretchRatio) bool Sets time-stretch as a length ratio (2.0 = twice as long).
setStretchRatioBySpeed(float speedRatio) bool Sets time-stretch as a speed ratio (2.0 = twice as fast).
setPan(float pan) bool Sets the note's pan position. Range: -1.0 (full left) to 1.0 (full right); 0.0 is center.
setReleaseSeconds(float lengthSeconds, float curveExponent) bool Configures the note's release envelope. lengthSeconds: release time (0.0 = instant). curveExponent: range 0.25-4.0, as the stage curves; below 1.0 = convex, 1.0 = linear, above 1.0 = concave.NoteThis only updates the envelope settings. It does not trigger the release. The new settings take effect when the note is released, either by the user lifting the key or by an explicit stop() call. After stop() it is too late: it returns false. Use stop(releaseSeconds, curveExponent) instead.
setReleaseSeconds(float lengthSeconds) bool The same, keeping the note's own release curve.

Insert FX

FunctionReturnsDescription
setParameter(int insertIndex, int paramIndex, float value) bool Sets a parameter on the note's insert FX chain. insertIndex: 0-based insert slot. paramIndex: 0-based parameter on that insert. value: float value (range depends on the insert parameter).

Example: Vary release length by velocity

event initialize() { setIgnoreNoteOns(true); }  // Override automatic note-on handling

event noteOn(NoteData note)
{
    Articulation art = getCurrentArticulation();
    Note playing = art.startNote(note);

    // Scale the release straight off velocity: harder hits ring out longer
    float releaseSeconds = note.getVelocity() * 3.0f;    // velocity is 0.0-1.0, so 0.0-3.0 seconds
    playing.setReleaseSeconds(releaseSeconds, 1.0f);            // 1.0 = a linear fade
}

HeldNotes


A HeldNotes is a snapshot of every MIDI note the user is currently holding down - useful for chord recognition, arpeggiator-style logic, or any script behavior that needs to know what's pressed at a given moment. Get one via the free function getHeldNotes(); for a quick single-note query, use isNoteHeld(int) instead.

HeldNotes stores up to 128 note numbers. The size member variable tells you how many are currently held.

Host MIDI only

HeldNotes tracks notes the user is physically holding on a keyboard or sending from the host DAW. Notes you trigger from a script via startNote() do not register as held. Only incoming MIDI does.

Example: Detect chords by counting held notes

// Logs to the debug console when three or more notes are pressed at once.

event initialize()
{
    setLogEnabled(true);          // Without this, debug.log() output is silent
    setIgnoreMidiNotes(false);    // Make sure incoming MIDI notes still play
}

event noteOn(NoteData note)
{
    HeldNotes held = getHeldNotes();

    if(held.size >= 3)
        debug.log("Chord detected, notes:", held.size);
}

Functions

FunctionReturnsDescription
isEmpty() bool Returns true if no notes are currently held.
getHeldNote(int index) int Returns the MIDI note number at the given 0-based index. Notes are ordered lowest to highest, not in the order they were pressed. Returns -1 when there is no held note at that index.
visit<Type>(Type& visitor) void Generic-visitor iteration. Calls visitor.processHeldNote(int) for every held note. Pass any struct that defines a processHeldNote(int) function.

Member Variables

Member VariableTypeDescription
size int Number of notes currently held.

Time-varying modulation


The script-side API has no built-in glide, fade, or ramp helpers for active notes. There's no glideTo(target, durationSec) or fadeOutOver(durationSec). Instead, you interpolate values yourself in event process() and call Note's per-note setters (setTuningSemitones, setGainLinear, etc.) each audio block. This pattern is the standard answer to "how do I make X change smoothly over time".

The process() event

event process() fires once per audio block (typical block size 32 samples ≈ 0.67 ms at 48 kHz). Use it to advance any time-varying state - pitch glides, fade-outs, scripted LFOs, parameter sweeps - and apply the result to active notes.

event process()
{
    // runs every block - keep work small and predictable
}

Use process() for anything you can hear, and viewRefresh() for anything you can see. viewRefresh() fires at 12-60 Hz, far too slow to step a glide smoothly, and its frame timing isn't guaranteed, so you can't measure elapsed time from it. process() gives you both: a fast rate, and an exact time step you can calculate.

Block-delta seconds

To advance a glide, fade, or any other value that changes over time, you need to know how much time has passed between block calls. Divide the block size (samples) by the sample rate:

event process()
{
    float blockSec = float(getBlockSize()) / float(getSampleRate());
    // blockSec ≈ 0.00067 at 48 kHz / 32-sample blocks

    // ... advance an elapsed-time counter, look up a position, etc.
}

Example: 200 ms pitch glide

Animate a Note's tuning offset linearly from a starting value down to zero over a fixed duration. The state lives at module level so it persists across block calls.

Note currentNote;                        // Handle to the note currently gliding
bool gliding;                            // True while a glide is in progress
float glideElapsedSec;                   // Seconds since this glide started
const float kGlideDurationSec = 0.2f;    // Glide length. Portamento usually sits around 0.1 - 0.3
const float kGlideSemitones = -1.0f;     // Glide distance. Negative starts below pitch, positive above

event initialize() { setIgnoreNoteOns(true); }  // The script plays the note, not KODA's default routing

event noteOn(NoteData note)
{
    Articulation art = getCurrentArticulation();
    currentNote = art.startNote(note);   // Keep the handle so we can retune the note while it sounds

    // Start off-pitch by kGlideSemitones, then glide up to natural pitch
    currentNote.setTuningSemitones(kGlideSemitones);
    glideElapsedSec = 0.0f;
    gliding = true;
}

event process()                          // Runs once per audio block
{
    if(!gliding)                         // Nothing to do between glides
        return;

    float blockSec = float(getBlockSize()) / float(getSampleRate());   // How much time one block covers
    glideElapsedSec += blockSec;

    float ratio = min(glideElapsedSec / kGlideDurationSec, 1.0f);      // 0.0 at the start, 1.0 when finished
    currentNote.setTuningSemitones(kGlideSemitones * (1.0f - ratio));  // Shrink the offset to zero as ratio rises

    if(ratio >= 1.0f)
        gliding = false;
}
One note at a time

A single Note member variable holds one note, so playing a second note before the first finishes hands the glide to the new one and leaves the previous note stuck at whatever tuning it had reached. To glide chords or overlapping notes, keep a Note per MIDI note number in an array and give each one its own elapsed-time counter.

Combining glide and vibrato on the same note

The scripted glide and vibrato below are both intended to change the same note's tuning. The problem is that note setters are absolute, so each call replaces the last one. If the two wrote their own values, you'd hear only whichever ran last. The solution is to add their offsets into one total instead, and apply that in a single call.

Note currentNote;
bool gliding;
float glideElapsedSec;
bool vibratoActive;
float vibratoPhase;                          // Kept between blocks so the sine stays continuous
const float kGlideDurationSec = 0.2f;
const float kGlideSemitones = -1.0f;
const float kVibratoHz = 5.0f;               // Vibrato speed in cycles per second
const float kVibratoDepthSemitones = 0.15f;  // Roughly a 15 cent wobble either side

event initialize() { setIgnoreNoteOns(true); }  // The script plays the note, not KODA's default routing

event noteOn(NoteData note)
{
    Articulation art = getCurrentArticulation();
    currentNote = art.startNote(note);

    glideElapsedSec = 0.0f;                  // Start both modulators from scratch on every note
    gliding = true;
    vibratoPhase = 0.0f;
    vibratoActive = true;
}

event process()
{
    float blockSec = float(getBlockSize()) / float(getSampleRate());

    float totalSemitones = 0.0f;             // Each modulator adds its offset here

    if(gliding)
    {
        glideElapsedSec += blockSec;
        float ratio = min(glideElapsedSec / kGlideDurationSec, 1.0f);
        totalSemitones += kGlideSemitones * (1.0f - ratio);
        if(ratio >= 1.0f) gliding = false;
    }

    if(vibratoActive)
    {
        // Phase counts whole cycles, so scale it by twoPi for sin().
        // twoPi is a Cmajor built-in constant, and a float64, so cast it to keep the math in float
        vibratoPhase += kVibratoHz * blockSec;
        totalSemitones += kVibratoDepthSemitones * sin(vibratoPhase * float(twoPi));
    }

    // One call carries both offsets
    currentNote.setTuningSemitones(totalSemitones);
}
Per-note state lives in the script

If you want to remember something extra about a note - its vibrato phase, a glide timer, a custom envelope counter - there's nowhere to attach that data to the Note itself. Instead, declare your variables at the top of the script (outside any event handler) so they persist between calls.

For a single-voice instrument, plain variables are enough. See the glide example above. For polyphonic instruments, use an array with one slot per MIDI note (size 128) or one slot per voice the script keeps track of.

Bus


A Bus is one of the audio routing destinations in your instrument - the master bus, a mic bus, or an FX bus. It's the level you'd reach to adjust output gain, route signal between buses, or toggle an insert FX on a shared FX chain rather than per-Group.

Buses are also how a signal becomes visible to the user. Each one can appear as a channel strip in the plugin's Mix tab with its own fader, pan, solo and mute buttons, and meters, so anything you want the user to mix has to live on a bus.

Get a Bus via the free functions getMasterBus() or getBus() (by name or 0-based index).

Handles

A Bus, like every handle (Parameter, Mic, Send, Tap, Modulator, Articulation, Variation, Group), is something you get from its lookup function. One you only declare (Bus b;) names nothing, and so does a lookup that finds nothing: isIdValid() is false for both. Calling a setter on one does nothing. Read a handle's position with getIndex(), which is -1 when the handle is not valid. Always get a handle from its lookup function rather than building one yourself: the compiler refuses a handle built any other way.

Sends are still filling out

getSend(int index) and getSend(string name) both return a Send, not a Bus. A Send can set pan, solo, mute, output index, and its insert FX parameters and bypass, and its insert slots are reachable with getInsert(), but it has no gain control yet.

Set send levels on the Bus that's sending: bus.setSendLevelLinear(int sendIndex, float level) or bus.setSendLevelDecibels(int sendIndex, float decibels), up to 8 send slots.

Send levels only work on the buses you see in the mixer. Setting one on the bus from getMasterBus() is accepted but never heard, since nothing is tapped from the master bus.

Example: Drive a reverb send from a MIDI controller

// Fires when Expression changes (built-in, MIDI CC 11 by default).
// Repurposed here as a reverb-send amount for portable testing.
// (Assumes a reverb sitting on the first send bus.)
event Expression(Parameter parameter)
{
    Bus main = getBus("Main");   // The first bus in the mixer, called "Main" by default

    // Send a portion of that bus's output to the first send bus (send index 0)
    main.setSendLevelLinear(0, parameter);
}
Shared setter pattern

Most setter functions on Bus (gain, pan, bypass, solo, mute, send level, insert parameters, setInsertBypassed) accept either a primitive value or a Parameter directly. See the Parameter convenience at the top of this reference.

Identity & state

FunctionReturnsDescription
isIdValid() bool Returns true if this Bus refers to a real bus in the instrument, Master included. Use as a null check before calling functions on the Bus.
getIndex() int The bus's 0-based index, -1 for Master, and -1 when the Bus is not valid: check isIdValid() or isMaster() to tell them apart.
isMaster() bool Whether this is the Bus getMasterBus() returns. A lookup that finds nothing is not Master.
validate() void Logs whether this Bus is valid (and its index if so) to the console.
getTypeName() string Returns the type name as a string ("Bus"). Useful for generic logging.

Gain & pan

FunctionReturnsDescription
setGainLinear(float gain) void Sets the Bus's gain (linear). Range: 0.0 (silence) to 4.0 (~+12 dB); 1.0 is unity.
setVolume(float decibels) void Sets the Bus's volume in decibels - the same value, and the same range, as the bus fader in the KODA app's mixer. Range: -180 dB (silence) to +12 dB; 0 dB is unity. Anything at or below -180 dB is exact silence.TipAlso accepts a Parameter directly: bus.setVolume(myVolumeKnob).
setPan(float pan) void Sets pan position. Range: -1.0 (full left) to 1.0 (full right); 0.0 is center.

Bypass, solo & mute

Toggle the Bus's playback state. These mirror the bypass, solo, and mute buttons users see on each bus in the plugin's mixer.

FunctionReturnsDescription
setBypassed(bool bypass) void Bypasses (or un-bypasses) the entire Bus. true = bypassed (Bus disabled), false = active. This is also how you enable and disable mics: bypassing a Bus drops the preloaded samples of every mic routed to it.
setSolo(bool solo) void Solos the Bus. While any bus is soloed, only soloed buses are audible.
setMute(bool mute) void Mutes the Bus. true = silenced, false = audible.

Send levels

Each Bus can send a portion of its signal to the instrument's send buses (up to 8 of them). Use this to drive parallel effects like reverbs and delays.

FunctionReturnsDescription
setSendLevelLinear(int sendIndex, float level) void Sets the send level on this Bus. sendIndex: 0-based index into the instrument's send buses (up to 8). level: typically 0.0 (no send) to 1.0 (unity send); no hard clamp.
setSendLevelDecibels(int sendIndex, float decibels) void Same as setSendLevelLinear but in decibels - the same value, and the same range, as the send control in the KODA app. Range: -180 dB (send off) to +12 dB; 0 dB is unity. Anything at or below -180 dB turns the send fully off.TipAlso accepts a Parameter directly: bus.setSendLevelDecibels(0, mySendKnob).

Insert FX

Like Groups, each Bus can host a chain of insert FX defined in the instrument. These functions let you modulate individual insert parameters or bypass entire inserts at runtime. To change which effect a slot holds, empty it, or reorder the chain, use the slot's Insert: bus.getInsert(slot).

FunctionReturnsDescription
setInsertParameter(int insertIndex, int paramIndex, float value) void Sets a parameter on an insert FX. insertIndex: 0-based insert slot. paramIndex: the effect's constant (Filter::Cutoff), which the engine refuses on a slot holding another effect, or a plain index. The same write as getInsert(insertIndex).setParameter(...). value: the new value as a float. For switch-type parameters use 0.0f / 1.0f; to bypass a whole insert, use setInsertBypassed below.TipAlso accepts a Parameter directly: bus.setInsertParameter(0, 0, myKnob).
setInsertBypassed(int insertIndex, bool bypassed) void Bypasses (or un-bypasses) an entire insert FX slot on this Bus. true = bypassed, false = active.TipIf you're wiring this to an "Enabled" button (where true means the user wants the effect on), invert the value: setInsertBypassed(0, !param.getBoolValue()).
Technical sidenote

Bus uses setInsertBypassed(index, bypassed) where Group uses setInsertBypassed(index, bypassed). The two do the same conceptual thing - toggle an insert slot - but the function names differ. setInsertParameter is spelled the same on both. An Insert has one spelling wherever its slot is: setBypassed.

Example: Bypass a reverb on the master bus

// Fires when SustainPedal changes (built-in, MIDI CC 64 by default).
// Repurposed here as a reverb-bypass toggle for portable testing.
// (Assumes a reverb at insert slot 0 of the master bus.)
event SustainPedal(Parameter parameter)
{
    Bus master = getMasterBus();

    // Pass the button state straight to the insert's bypass flag
    master.setInsertBypassed(0, parameter);
}

Output levels

Read a bus's current output meter. getLevels() returns a Levels snapshot, refreshed once per audio block, holding an RMS level and a held peak for each channel. Read it in event viewRefresh() or event process() to drive meters. Buses are always stereo, so a center-panned mono source reads the same on left and right and either getter will do.

FunctionReturnsDescription
getLevels() Levels Current output levels of this bus (also callable as the free function getLevels(myBus)). A Bus that names nothing reads silence.

Tap levels

A Tap insert passes its audio through untouched and measures it where it sits in the chain: before a compressor and after it, say, to show how hard it works. Find one by its insert name with getTap(); getLevels() reads it the way a bus's own levels read, refreshed once per audio block. Taps are looked up on Master, the input buses, the output buses, then the sends, and a name two taps share finds the first. Adding, removing or renaming a Tap insert recompiles the script. Shaders read the same taps (see Shaders).

FunctionReturnsDescription
getTap(string name) Tap The Tap insert with that name. One no tap has is reported in the console and reads silence.
getTap(int index) Tap The Tap insert at that 0-based position, in the order getTap(name) searches.
getIndex() int The tap's 0-based position, or -1 when it is not valid.
isIdValid() bool Whether getTap found a tap.
getLevels() Levels The tap's current levels (also callable as the free function getLevels(myTap)).
event viewRefresh()
{
    Tap before = getTap("Pre Comp");
    Tap after  = getTap("Post Comp");
    Levels pre = before.getLevels();
    Levels post = after.getLevels();
    float reduction = pre.getRmsDecibels() - post.getRmsDecibels();   // dB of gain reduction
}

Tap audio

A script can also read the audio a Tap insert passes, a block at a time: to follow a signal's level or pitch from your script, or to gather samples for a scope or an analyser in your GUI. getBlock() returns a TapBlock holding the last block of the tap's audio, both channels, oldest sample first.

One block at a time

KODA runs in blocks of 32 samples, and a TapBlock holds one. Read it once in every process() and the blocks join up into the tap's audio without a gap, one block behind it. Reading twice in the same block gets the same block, and a block your script doesn't read is gone. While nothing plays through the tap, its block reads silence.

For anything longer than a block, such as a scope's window or a spectrum, copy each block into an array of your own in process(). A read in viewRefresh() gets only the last block.

FunctionReturnsDescription
getBlock() TapBlock The last block of the tap's audio. A Tap that names nothing returns no samples (also callable as the free function getBlock(myTap)).
TapBlock fieldTypeDescription
left, right float[32] The two channels, oldest sample first, as linear sample values.
frames int How many samples of each channel hold audio: a whole block once audio has played through the tap, and 0 before that and for a Tap that names nothing. The samples past them read 0.0.
// (Assumes a Tap insert named "Pre Verb".) An envelope follower: the loudest
// sample of each block, rising at once and falling slowly. The tap is read
// once every process(), so no block is missed.
float envelope;

event process()
{
    Tap verb = getTap("Pre Verb");
    TapBlock block = verb.getBlock();

    float peak = 0.0f;
    for (int i = 0; i < block.frames; ++i)
        peak = max(peak, max(abs(block.left.at(i)), abs(block.right.at(i))));

    envelope = peak > envelope ? peak : envelope * 0.995f;
}

Levels

A read-only snapshot of a bus's output meter, returned by bus.getLevels(). It carries two measurements per channel. RMS is the smoothed level the meter bar shows. Peak is the loudest instant of a recent hit, the marker that sits above the meter bar. It jumps up on the hit, holds for about half a second, then falls at 40 dB per second. The getters without a channel name return the louder of the two channels.

Linear values run from 0.0 (silence) to ~3.98 (+12 dB), with 1.0 at unity (0 dB). Decibel values are floored at -180 dB, so a silent bus reads exactly -180.

Before 1.0.9, getPeak() returned the louder channel's RMS level; that reading is now getRms(), and getPeak() is the held peak described above. getLeft()/getRight() became getLeftRms()/getRightRms(), and getAverage() was removed.

FunctionReturnsDescription
getLeftRms()floatLeft channel RMS, linear (see range above).
getRightRms()floatRight channel RMS, linear (see range above).
getRms()floatRMS of the louder channel, linear (see range above).
getLeftRmsDecibels()floatLeft channel RMS in dB (floored at -180).
getRightRmsDecibels()floatRight channel RMS in dB (floored at -180).
getRmsDecibels()floatRMS of the louder channel in dB (floored at -180).
getLeftPeak()floatLeft channel held peak, linear (see range above).
getRightPeak()floatRight channel held peak, linear (see range above).
getPeak()floatHeld peak of the louder channel, linear (see range above).
getLeftPeakDecibels()floatLeft channel held peak in dB (floored at -180).
getRightPeakDecibels()floatRight channel held peak in dB (floored at -180).
getPeakDecibels()floatHeld peak of the louder channel in dB (floored at -180).

Insert


An Insert is one slot of one insert FX chain: the master bus's, a mic bus's, a send's, or a Group's. Through it a script decides what the slot holds - which effect, or none - as well as bypassing it and setting its parameters. It is how you build an FX rack into an instrument's UI, rebuild a chain when the user picks a preset, or set chains up when the instrument loads.

Get one with getInsert(int slot) on a Bus, a Send, or a Group. Slots are 0-based, every chain has KODA_MAX_INSERTS of them, and a slot may be empty anywhere in the chain.

Bus master = getMasterBus();
Insert verb = master.getInsert(2);       // slot 2
verb.setType(InsertType::Reverb);        // nothing happens if slot 2 already holds a Reverb
verb.setParameter(Reverb::Decay, 2.4f);  // reaches the new Reverb
verb.setBypassed(false);
Requests, not instant changes

setType, clear, setBypassed and moveInsert ask KODA to change the chain. It does so shortly after the audio block that asked, in the order you asked, as one change per chain. A setParameter after a setType in the same handler reaches the new effect. The getters show what you asked for at once. See When changes land.

Getting a slot

These are called on a Bus, a Send, or a Group. As with every KODA handle, keep the result in a local before calling it: Insert fx = bus.getInsert(0); fx.setType(...).

FunctionReturnsDescription
getInsert(int slot) Insert The chain's slot slot, 0-based. The handle keeps naming that slot whatever it comes to hold. On a Bus, Send or Group that names nothing, the Insert names no slot either: its isIdValid() is false and every change through it is refused.
getNumInsertSlots() int How many slots a chain has: KODA_MAX_INSERTS.
findInsert(InsertType type) Insert The first slot holding an effect of that InsertType, or an Insert whose isIdValid() is false when there is none. InsertType::None finds the first empty slot.TipLets a script work with "the reverb" without knowing which slot the builder put it in.
moveInsert(int fromSlot, int toSlot) void Moves the effect in fromSlot to toSlot, as dragging it in the app does. Into an empty slot it simply moves; onto an occupied one, the effects in between shift one slot back toward fromSlot. Modulation routed to the effect follows it.

Type, bypass & parameters

FunctionReturnsDescription
setType(InsertType type) void Makes the slot hold an effect of that InsertType. A slot that already holds one is left as it is, settings and all. Otherwise the slot gets a new effect at its own defaults, replacing what was there, and modulation routed to the old effect is removed. InsertType::None empties the slot. A Cmajor patch or a Tap is never replaced or emptied: see What KODA refuses.
clear() void Empties the slot: setType(InsertType::None).
setBypassed(bool bypassed) void Bypasses (true) or un-bypasses the effect in the slot. Ignored on an empty slot.TipAlso accepts a Parameter directly. For an "Enabled" button, invert it: fx.setBypassed(! on.getBoolValue()).
setParameter(int index, value) void Sets a parameter of the effect in the slot, using the effect's constants (Reverb::Decay, Filter::Cutoff, ...). A constant of another effect changes nothing, with a console warning; a plain index is sent unchecked. value: float, int, bool, or a Parameter. setInsertParameter on the Bus, Send or Group is the same write.
getType() int The InsertType the slot holds, InsertType::None when it is empty.
isEmpty() bool Whether the slot holds no effect.
isBypassed() bool Whether the effect in the slot is bypassed.
isIdValid() bool Whether this Insert names a slot of a real chain. An Insert that was only declared names none, nor does a findInsert that found nothing.
getSlot() int The slot index (-1 from a findInsert that found nothing).
validate() void Logs whether this Insert is valid (and its slot if so) to the console.
getTypeName() string Returns the type name as a string ("Insert").

InsertType

The effects a slot can hold, compared with ==: fx.getType() == InsertType::Reverb. InsertType is an enum: it is not a number and can't be mixed up with one, and an InsertType nobody set is None. Enums fit in arrays, which is how a menu's choices map to effects (see the rack example). A Group runs its effects once per note, so it takes only the effects marked as running in a Group.

ConstantEffectIn a Group
InsertType::NoneNo effect: an empty slot-
InsertType::EQ5-band parametric EQYes
InsertType::CompressorCompressorYes
InsertType::LimiterLimiterYes
InsertType::FilterFilterYes
InsertType::DistortionDistortionYes
InsertType::StereoImagerStereo ImagerYes
InsertType::PhaserPhaserYes
InsertType::TransientShaperTransient ShaperYes
InsertType::ReverbReverbNo: buses and sends
InsertType::DelayDelayNo: buses and sends
InsertType::ChorusChorusNo: buses and sends
InsertType::SaturationSaturationNo: buses and sends
InsertType::ConvolutionConvolution (choose its IR with setParameter(Convolution::File, i))No: buses and sends
InsertType::CmajorPatchA Cmajor patch: getType() reports it, but only the app adds or removes oneNo
InsertType::TapA Tap: getType() reports it, but only the app adds or removes oneNo
What KODA refuses

A request KODA can't carry out is refused with a line in the console, and the getters go back to what the slot really holds: an effect a Group can't run, adding a Cmajor patch or a Tap, replacing or clearing one, and a move that would change the order of two Taps. A script can't load a Cmajor patch, so one it removed could never come back. A Tap's name is compiled into your script (getTap()), so changing Taps would recompile it. Moving either, bypassing it and setting its parameters are fine.

When changes land

  • Shortly after the block that asked, within a few tens of milliseconds - not on a sample. Notes played in between go through the old chain. Changes that must land on the beat belong in parameters and bypass. Change effect types when the instrument loads, when a preset or snapshot loads, or from the UI.
  • In order, together. All your requests on one chain in one block are applied in the order you made them, as one change.
  • Parameter writes wait for them. While a setType or moveInsert on a bus or send is waiting, every parameter write to that chain (setParameter, setInsertParameter) waits with it, so it lands on the new effect. Other chains are not affected.
  • A bus or send chain dips where it changed. The effects you keep carry on as they were, tails, held synth notes and all, even when they move to another slot. The signal leaving the highest slot you changed dips for a few milliseconds while the new arrangement comes in. A change that alters the instrument's latency (adding or removing a Convolution with Latency Comp on) dips the whole instrument for a moment instead, so every output stays in time. Bypassing an effect, or turning it back on, dips that effect the same way.
  • A Group's playing notes keep their chain. Notes already sounding keep the effects they started with; new notes get the new ones.
  • Requests made in initialize() are carried out once audio is running.
  • The getters are right in initialize(), show your own requests at once, and follow changes made in the app, by undo, by a chain preset or by MCP shortly after they happen.
Calling it every block

Each setType, setBypassed and moveInsert is a request, even when nothing changes. Make them when the choice changes - in the Parameter event that decides it - not from process() or viewRefresh().

Loading, presets & snapshots

A DAW session and a snapshot save your Parameters and persist variables, not the effect in each slot. Make the chain follow them:

  • Structure that follows a Parameter is set in that Parameter's event. KODA runs every Parameter event once after initialize() when the instrument loads, and again whenever a preset or snapshot changes the value, so the chain follows by itself. Because setType leaves a slot that already holds the effect alone, that costs nothing.
  • Structure held in persist variables is set in initialize(), which runs with them restored, and again in snapshotLoaded().
  • Settings come from you. A new effect starts at its own defaults, and switching away and back does not bring the old settings back. Set what you want with setParameter after setType. Mind a default that changes how another parameter reads: a new Delay starts synced to the host tempo (Delay::Sync on), and while it is, Delay::Time is the length of a note division at 120 BPM (500 is a quarter note, 250 an eighth), played at the host's tempo. For a time in milliseconds, set Delay::Sync to 0 as well.
  • Undo. What a script does to inserts stays out of the user's undo history.
Technical sidenote

A Full snapshot sets insert parameters by slot and effect before your Parameter events change an effect. When a snapshot switches a slot to another effect, the values it saved for that slot don't fit the new one and are skipped. Controls of a scripted rack that must come back with a snapshot belong in Parameters, pushed to the effect with setParameter.

Example: an FX rack

Four rack slots on the master bus, after the builder's own effects in slots 0-3. Each rack slot has a menu Parameter choosing its effect and a button Parameter turning it on, both authored in the .kdui.

// Slot1Type .. Slot4Type: menus with the items None, Delay, Reverb, Chorus.
// Slot1On .. Slot4On: on/off buttons.
const InsertType[4] kRackChoices = (InsertType::None, InsertType::Delay,
                                    InsertType::Reverb, InsertType::Chorus);
const int kFirstRackSlot = 4;

void showRackSlot(int slot, Parameter type, Parameter on)
{
    Bus master = getMasterBus();
    Insert fx = master.getInsert(kFirstRackSlot + slot);
    fx.setType(kRackChoices.at(type.getIntValue()));
    fx.setBypassed(! on.getBoolValue());
}

// Each event runs at load, and when a preset or snapshot changes its Parameter.
event Slot1Type(Parameter parameter) { Parameter on = getParameter("Slot1On");     showRackSlot(0, parameter, on); }
event Slot1On(Parameter parameter)   { Parameter type = getParameter("Slot1Type"); showRackSlot(0, type, parameter); }
// Slot2 .. Slot4 the same.

Mic


A Mic represents one of the microphone positions in your instrument - the same mics users see in the plugin's mic mixer. Mics are defined at the clip level: when you import samples, the Tokenizer identifies a Signal (Mic) token in each filename (e.g. Close, Room, Overheads), and the unique set across all clips becomes the instrument's mic list. Each mic becomes an object you can address by name or index.

Get a Mic via the free functions getMic(string name) or getMic(int index).

Mic functions cover level and position: gain, pan, solo, and mute. To enable or disable a mic entirely, bypass the Bus it's routed to, which drops the preloaded samples of every mic on that bus.

Example: Tie a mic's gain to a MIDI controller

// Fires when BreathController changes (built-in, MIDI CC 3 by default).
// Repurposed here as close-mic gain for portable testing. It starts at 1.0,
// so the mic sits at full gain until the controller is moved.
// (Assumes a mic named "Close" in the instrument.)
event BreathController(Parameter parameter)
{
    Mic close = getMic("Close");   // Rename this to any mic you want to control

    // Pass the knob value straight to the mic's gain
    close.setGainLinear(parameter);
}
Shared setter pattern

Every setter on Mic (gain, gain in dB, pan, solo, mute) accepts either a primitive value or a Parameter directly. See the Parameter convenience at the top of this reference.

Identity & state

FunctionReturnsDescription
isIdValid() bool Returns true if this Mic refers to a real mic in the instrument. Use as a null check before calling functions on the Mic.
getIndex() int The mic's 0-based index, or -1 when it is not valid.
validate() void Logs whether this Mic is valid (and its index if so) to the console.
getTypeName() string Returns the type name as a string ("Mic"). Useful for generic logging.

Gain & pan

FunctionReturnsDescription
setGainLinear(float gain) void Sets the Mic's gain (linear). Range: 0.0 (silence) to 4.0 (~+12 dB); 1.0 is unity.
setVolume(float decibels) void Sets the Mic's volume in decibels - the same value, and the same range, as that mic's fader in the KODA app's mic mixer. Range: -180 dB (silence) to +12 dB; 0 dB is unity. Anything at or below -180 dB is exact silence.TipAlso accepts a Parameter directly: mic.setVolume(myVolumeKnob).
setPan(float pan) void Sets pan position. Range: -1.0 (full left) to 1.0 (full right); 0.0 is center.

Solo & mute

These mirror the solo and mute buttons users see for each mic in the plugin's mic mixer. To enable or disable a mic, bypass its Bus - see the note at the top of this section.

FunctionReturnsDescription
setSolo(bool solo) void Solos the Mic. While any mic is soloed, only soloed mics are audible.
setMute(bool mute) void Mutes the Mic. true = silenced, false = audible.

Example: Toggle a mic on/off from a MIDI controller

// Fires when SustainPedal changes (built-in, MIDI CC 64 by default).
// Repurposed here as a Room-mic on/off toggle for portable testing.
event SustainPedal(Parameter parameter)
{
    Mic room = getMic("Room");   // Rename this to any mic you want to control

    // Pedal down silences the Room mic, pedal up brings it back
    room.setMute(parameter);
}

Modulator


A Modulator represents an LFO, a Multi LFO, an envelope, a Flexible Envelope or a Step modulator defined in your instrument - the same modulators users see attached to parameters in the plugin's modulation panel. From a script, you can adjust the modulator's shape (LFO frequency, waveform, depth), its Multi LFO stack (base rate plus per-component waveform, level and rate), its envelope (attack, decay, sustain, release) or its step sequence (rate, length, direction, swing) at runtime, and enable or bypass it.

Get a Modulator via the free functions getModulator(string name) or getModulator(int index).

Depth chain

A modulator's effective output is the product of three things: its raw signal (LFO waveform output, Multi LFO sum, or envelope shape), the script-side depth amount (setLFODepth for LFOs, setMultiLFODepth for Multi LFOs, setEnvelopeSustain for envelopes), and the routing amount set in the modulation panel in the KODA app when the modulator was attached to its destination.

The script's depth is a normalized 0..1 multiplier. The absolute cents, semitones, or dB applied to the target come from the routing amount. If you've called setLFODepth(1.0) and still hear no modulation, open the modulation panel, find the modulator's attachment to its destination parameter, and check that the routing amount isn't zero.

Example: Tie vibrato depth to a MIDI controller

// Dynamics controls modulator depth (built-in, MIDI CC 1 by default).
// (Assumes a Modulator named "Vibrato" in the instrument.)
event Dynamics(Parameter parameter)
{
    Modulator vibrato = getModulator("Vibrato");

    // 0.0 = no vibrato, 1.0 = full vibrato
    vibrato.setLFODepth(parameter);
}
Shared setter pattern

Every setter on Modulator (enable, all LFO controls, all Multi LFO controls, all envelope controls, the Flexible Envelope toggles, all Step modulator controls) accepts either a primitive value or a Parameter directly. For the Multi LFO's per-component setters it is the value that may be a Parameter, not the component number. See the Parameter convenience at the top of this reference.

Enable & bypass

FunctionReturnsDescription
setEnabled(bool enabled) void Enables or bypasses the Modulator. true = enabled (active), false = bypassed (modulator has no effect).
isIdValid() bool Whether getModulator found a modulator.
getType() int Which kind of modulator this is: ModulatorType::LFO, ::Envelope, ::MultiLFO, ::FlexEnvelope, ::StepMod and so on, or -1 when it is not valid. A call for another kind (an LFO setter on an Envelope, a Step modulator getter on an LFO) does nothing, and the console says so once.
getIndex() int The modulator's 0-based index, or -1 when it is not valid.

Live value

A script can read a modulator's output as it plays, the value the MODS page's live indicator shows, to animate a script GUI or to follow a modulator from your script. A Step modulator also reports which step is playing (getStepModPlayingStep).

One block behind

KODA works out its modulators after your script's events in each block, so a read gets the value as the last block left it. In initialize(), it is the value the last block left before your script started.

A modulator that runs for each note separately (an envelope, an LFO that isn't global, a Step modulator on StepTrigger::Retrigger or StepTrigger::Legato) has a value for every note playing. You read one of those notes' values, as the MODS page shows it, and once no note is playing it, the value the last one had (a Step modulator's playing step reads -1 then). To shape the sound from a modulator's value, use a global one: an LFO or Multi LFO set global (setLFOGlobal(true)), a Parameter modulator, or a Step modulator on StepTrigger::Global.

FunctionReturnsDescription
getCurrentValue() float The modulator's output, 0.0 to 1.0, as the MODS page shows it. An LFO's centre line is 0.5. 0.0 while the modulator is bypassed, or when it is not valid.

LFO controls

These shape the LFO's behavior - rate, waveform, phase, depth, and whether the LFO runs globally (shared across all notes) or per-note (each note starts a fresh phase).

FunctionReturnsDescription
setLFOFrequency(float frequency) void Sets the LFO frequency in Hz. Range: 0.01 to 20 Hz, the same as the FREQ knob. Values outside it play at the nearest end.
setLFOWaveform(LFOWaveform waveform) void Sets the LFO waveform: LFOWaveform::Sine, Triangle, Saw, Square, SampleHold or Drift. A choice Parameter whose items run in that order can be passed directly. SampleHold is the app's "Sample & Hold" (random steps); Drift glides smoothly through the same random sequence.
setLFOPhaseOffset(float phaseOffset) void Sets the LFO phase offset (normalized). Range: 0.0 to 1.0; 0.5 = half cycle. Values outside it play at the nearest end.
setLFOBipolar(bool bipolar) void Sets whether the LFO output is bipolar. true = -1 to 1 (centered on 0), false = 0 to 1 (centered on 0.5).
setLFOGlobal(bool global) void Sets whether the LFO is global or per-note. true = global (all notes share phase), false = per-note (each note has independent phase).
setLFODepth(float depth) void Sets the LFO depth. Range: 0.0 (no modulation) to 1.0 (full routing-defined range). The absolute cents/semitones/dB are set by the routing in the editor. This just scales them.
setLFOFadeInMS(float fadeInMs) void Sets the fade-in time in milliseconds - how long the LFO takes to reach full depth after it starts. 0.0 = no fade (the default). Range: 0 to 10000 ms. Values outside it play at the nearest end.
setLFOWidth(float width) void Sets the pulse width (duty cycle) of the Square waveform. Range: 0.01 to 0.99; 0.5 = a symmetric square. Ignored by the other waveforms.
setLFOSync(bool synced) void Sets whether the LFO is tempo-synced. false = the rate is setLFOFrequency's Hz (the default); true = one cycle per setLFODivision of the host tempo, and a global LFO follows the DAW timeline while it plays.
setLFODivision(NoteDivision division) void Sets the length of one cycle while the LFO is synced, a NoteDivision, fastest first: ThirtySecondTriplet (1/32 T), ThirtySecond, SixteenthTriplet, ThirtySecondDotted, Sixteenth, EighthTriplet, SixteenthDotted, Eighth, QuarterTriplet, EighthDotted, Quarter, HalfTriplet, QuarterDotted, Half (the default), HalfDotted, Whole (1/1). A choice Parameter whose items run in that order can be passed directly. Ignored while the LFO runs in Hz.

Envelope controls

These shape the envelope's pre-delay, attack-hold-decay-sustain-release stages, and their curve exponents.

FunctionReturnsDescription
setEnvelopePreDelaySeconds(float preDelay) void Sets pre-delay in seconds. 0.0 = no delay. Range: 0.0 to 10.0 seconds. Values outside it play at the nearest end.
setEnvelopeAttackSeconds(float attack) void Sets attack time in seconds. 0.0 = instant. Range: 0.0 to 10.0 seconds. Values outside it play at the nearest end.
setEnvelopeAttackCurve(float attackCurve) void Sets the attack curve exponent. Range: 0.25 to 4.0; values outside it play at the nearest end. 0.5 = convex (fast start, slow finish), 1.0 = linear, 2.0 = concave (slow start, fast finish).
setEnvelopeHoldSeconds(float hold) void Sets hold time in seconds. 0.0 = no hold. Range: 0.0 to 10.0 seconds. Values outside it play at the nearest end.
setEnvelopeDecaySeconds(float decay) void Sets decay time in seconds. 0.0 = instant. Range: 0.0 to 10.0 seconds. Values outside it play at the nearest end.
setEnvelopeDecayCurve(float decayCurve) void Sets the decay curve exponent. Same conventions as attack curve.
setEnvelopeSustain(float sustain) void Sets the sustain level. Range: 0.0 (silence) to 1.0 (full level).
setEnvelopeReleaseSeconds(float release) void Sets release time in seconds. 0.0 = instant. Range: 0.0 to 10.0 seconds. Values outside it play at the nearest end.
setEnvelopeReleaseCurve(float releaseCurve) void Sets the release curve exponent. Same conventions as attack curve.

Multi LFO controls

A Multi LFO modulator sums up to six component LFOs into one output. Each component has its own waveform, phase, level and rate; the rate is a multiple of the module's single base frequency, so changing setMultiLFOFrequency speeds the whole stack up together. Depth and fade-in also apply to the summed output, not to individual components.

The first group of setters below shape the module as a whole. The second group takes a component number as its first argument.

Components are numbered from 0

Component 0 is the row the modulator editor labels LFO 1, component 1 is LFO 2, and so on up to component 5 (LFO 6). A component number outside that range is dropped rather than sent, so a loop that runs one too far cannot land on another parameter.

Setting a component above the current setMultiLFOCount is harmless - the value is stored and starts sounding when the count grows to reveal that component.

FunctionReturnsDescription
setMultiLFOFrequency(float frequency) void Sets the base rate in Hz. Every component runs at this rate multiplied by its own setMultiLFORate. Range: 0.01 to 20 Hz. Values outside it play at the nearest end.
setMultiLFOGlobal(bool global) void Sets whether the Multi LFO is global or per-note. true = global (all notes share one running stack), false = per-note (each note retriggers its own).
setMultiLFODepth(float depth) void Sets the depth of the summed output. Range: 0.0 (no modulation) to 1.0. As with the LFO, the absolute cents/semitones/dB come from the routing in the editor.
setMultiLFOCount(int count) void Sets how many components are live. Range: 1 to 6; out-of-range values are clamped. Components above the count keep their settings and stay silent.
setMultiLFONormalize(bool normalize) void Sets what happens when the component levels sum past full scale. false = clamp the sum (components can drive each other into the rails), true = scale the sum back down by the summed level so the shape is preserved.
setMultiLFOFadeInMS(float fadeInMs) void Sets the fade-in time in milliseconds for the whole module - one fade on the summed output, not one per component. 0.0 = no fade. Range: 0 to 10000 ms. Values outside it play at the nearest end.
setMultiLFOSync(bool synced) void Sets whether the base rate is tempo-synced. false = setMultiLFOFrequency's Hz (the default); true = one base cycle per setMultiLFODivision of the host tempo. Each component's rate stays a multiple of the base, and a global Multi LFO follows the DAW timeline while it plays.
setMultiLFODivision(NoteDivision division) void Sets the length of one base cycle while the Multi LFO is synced, by the same NoteDivision as setLFODivision (NoteDivision::Half is the default). Ignored while it runs in Hz.
FunctionReturnsDescription
setMultiLFOWaveform(int component, LFOWaveform waveform) void Sets one component's waveform, an LFOWaveform as for setLFOWaveform.
setMultiLFOPhase(int component, float phase) void Sets where in its cycle one component starts. Range: 0.0 to 1.0; 0.5 = half a cycle.
setMultiLFOLevel(int component, float level) void Sets how much of one component goes into the sum. Range: -1.0 to 1.0; 0.0 = silent, negative values invert that component.
setMultiLFORate(int component, float rate) void Sets one component's speed as a multiple of the base frequency. Range: 0.125 (an eighth of the base rate) to 8.0; 1.0 = the base rate itself.
setMultiLFOWidth(int component, float width) void Sets the pulse width (duty cycle) of one component's Square waveform. Range: 0.01 to 0.99; 0.5 = a symmetric square. Ignored by the other waveforms.
setMultiLFOParameter(int component, int field, float value) void Sets any component field by its index, for loops that would otherwise repeat the five setters above. The field indices are published as Modulator::MultiLFO::Field::Waveform, ::Phase, ::Level, ::Rate and ::Width - the same named-constant convention the insert effects use. Same 0-based component numbering, same out-of-range behaviour.

Example: Build a two-speed Multi LFO shimmer

// A slow sine under a fast, quieter triangle - the classic "breathing"
// vibrato that a single LFO can't make on its own.
// (Assumes a Multi LFO Modulator named "Shimmer" in the instrument.)
event initialize()
{
    Modulator shimmer = getModulator("Shimmer");

    shimmer.setMultiLFOFrequency(2.0f);   // base rate for the whole stack
    shimmer.setMultiLFOCount(2);
    shimmer.setMultiLFOFadeInMS(400.0f);    // ms, on the summed output

    // Component 0 is the editor's "LFO 1".
    shimmer.setMultiLFOWaveform(0, LFOWaveform::Sine);
    shimmer.setMultiLFORate(0, 1.0f);     // at the base rate
    shimmer.setMultiLFOLevel(0, 1.0f);

    shimmer.setMultiLFOWaveform(1, LFOWaveform::Triangle);
    shimmer.setMultiLFORate(1, 4.0f);     // four times faster
    shimmer.setMultiLFOLevel(1, 0.35f);
}

Flexible Envelope controls

A Flexible Envelope modulator is a breakpoint envelope: up to 32 nodes on a time axis, a marked region that holds or loops while the key is down, and the nodes after it as the release stage. A script can flip its four playback toggles. The breakpoints themselves, and the Sync toggle (which converts every node time between seconds and beats), are edited in the KODA app only.

FunctionReturnsDescription
setFlexEnvelopeLoop(bool shouldLoop) void Sets what the marked region does while the key is held. true = loop it (each pass continues from the loop-end level), false = play to the region's end and hold that level.
setFlexEnvelopeOneShot(bool oneShot) void Sets whether the envelope ignores the key-up. true = play through to the last node regardless (with Loop on, loop until the voice ends), false = jump to the release stage on key-up.
setFlexEnvelopeRetrigger(bool retrigger) void Sets where a new note starts on the envelope. true = every note starts its own envelope from the first node, false = notes played while others are held continue the running envelope (the phrase clock).
setFlexEnvelopePlayThru(bool playThru) void Sets what a held key does when Loop and OneShot are both off. true = play every node, then hold the last node's level; false = stop at the end of the marked region and hold that level. Either way the key-up starts the release. Has no effect while Loop or OneShot is on.

Step modulator controls

A Step modulator plays a sequence of up to 128 drawn step values, one after another, at a tempo-synced or free rate. A script can change how the sequence plays: its speed, length, order, swing and smoothing, and when it restarts. It can also set the step values themselves with setStepModStepValue, and read them with getStepModStepValue.

Steps are numbered from 0

Step 0 is the bar the modulator editor labels 1, step 1 is bar 2, and so on up to step 127. A step number outside that range does nothing.

A step value is the bar's height: 0.0 at the bottom, 1.0 at the top and 0.5 on the centre line. The numbers are the same whether the editor draws the steps bipolar or not.

A new value is heard at once, even on the step that is playing, and the editor shows it a moment later. getStepModStepValue reads it back straight away, in the same event too. It is saved with the instrument like a step drawn in the editor, but does not go on the undo list. Setting a step above the current setStepModSteps count is harmless: the value is stored and plays when the count grows to reach it.

FunctionReturnsDescription
setStepModSync(bool synced) void Sets how the step speed is set. true = each step lasts one setStepModDivision of the host tempo (the default, MUSICAL in the editor); false = steps advance at setStepModRate's Hz and the tempo is ignored (HZ).
setStepModDivision(NoteDivision division) void Sets the length of one step while the modulator is synced, by the same NoteDivision as setLFODivision (NoteDivision::Sixteenth is the default). A choice Parameter whose items run in that order can be passed directly. Ignored while it runs in Hz.
setStepModRate(float rate) void Sets how many steps play per second while the modulator runs in Hz. Range: 0.01 to 20 Hz; values outside it play at the nearest end. Ignored while it is synced.
setStepModTrigger(StepTrigger trigger) void Sets when the sequence starts again from step 1. StepTrigger::Global = one sequence shared by every note, which follows the DAW timeline while it plays if the modulator is synced; StepTrigger::Retrigger (the default) = every note starts the sequence from step 1; StepTrigger::Legato = a detached note restarts it, while slurred or pedal-held notes carry on from where it is. A choice Parameter whose items run in that order can be passed directly.
setStepModSteps(int count) void Sets how many steps the sequence plays before it repeats. Range: 1 to 128; out-of-range values are clamped. Steps beyond the count keep their values and play again when the count grows. The default is 16.
setStepModDirection(StepDirection direction) void Sets the order the steps play in: StepDirection::Forward (the default), Reverse, PingPong (back and forth, without playing the end steps twice) or Random. A choice Parameter whose items run in that order can be passed directly.
setStepModSmooth(float smooth) void Sets how much of each step is spent gliding in from the step before. Range: 0.0 (hard steps, the default) to 1.0 (a glide that fills the whole step).
setStepModSwing(float swing) void Sets the shuffle on every pair of steps: the first step of each pair gets longer and the second shorter. Range: 0.0 (straight, the default) to 1.0 (the first step takes three quarters of the pair).
setStepModBipolar(bool bipolar) void Sets whether the editor draws the steps around a centre line (true) or up from the bottom (false, the default). It changes how the steps look, not the sound.
setStepModSnap(bool snap) void Sets whether steps drawn in the editor snap to semitones. It changes editing only, not the sound.
setStepModStepValue(int step, float value) void Sets one step's value. step counts from 0, up to 127. Range: 0.0 to 1.0; out-of-range values are clamped. A Parameter can be passed as value. One step per call: a loop sets a whole pattern.
getStepModStepValue(int step) float Returns one step's value as the pattern plays it, 0.0 to 1.0: the value last drawn in the editor or set by a script. step counts from 0, up to 127; a step outside that range, or a modulator that isn't a Step modulator, returns 0.0.
getStepModPlayingStep() int The step playing, counted from 0, as the MODS page lights it, as of the last block (see Live value). -1 before the pattern has played, while the modulator is bypassed, while no note plays a pattern that runs for each note, or for a modulator that isn't a Step modulator.

Example: Pick a step pattern's speed and direction from the GUI

// (Assumes a Step Modulator named "Gate", a choice Parameter "GateSpeed" whose
// items are 1/16, 1/8 and 1/4, and an on/off Parameter "GateBounce".)
event GateSpeed(Parameter parameter)
{
    Modulator gate = getModulator("Gate");

    if (parameter.getIntValue() == 0)      gate.setStepModDivision(NoteDivision::Sixteenth);
    else if (parameter.getIntValue() == 1) gate.setStepModDivision(NoteDivision::Eighth);
    else                                    gate.setStepModDivision(NoteDivision::Quarter);
}

event GateBounce(Parameter parameter)
{
    Modulator gate = getModulator("Gate");

    gate.setStepModDirection(parameter.getBoolValue() ? StepDirection::PingPong : StepDirection::Forward);
    gate.setStepModSwing(parameter.getBoolValue() ? 0.3f : 0.0f);
}

Example: Choose a step pattern from a menu

// (Assumes a Step Modulator named "Gate" and a choice Parameter "GatePattern"
// whose items are Ramp, Accents and Off-beats.)
event GatePattern(Parameter parameter)
{
    Modulator gate = getModulator("Gate");
    int shape = parameter.getIntValue();

    for (int step = 0; step < 16; ++step)
    {
        float value = 0.0f;
        if (shape == 0)      value = float(step + 1) / 16.0f;          // a rising ramp
        else if (shape == 1) value = (step % 4 == 0) ? 1.0f : 0.2f;  // a peak on every beat
        else                 value = (step % 2 == 1) ? 1.0f : 0.0f;  // the off-beats only

        gate.setStepModStepValue(step, value);
    }
    gate.setStepModSteps(16);
}

Example: Rotate a step pattern

// (Assumes a Step Modulator named "Gate" playing 16 steps, and an on/off
// Parameter "Rotate".) Each time Rotate is switched on, the pattern moves one
// step later and the last step wraps round to the first. Each step is read
// before it is written over, so the loop runs from the end.
event Rotate(Parameter parameter)
{
    if (! parameter.getBoolValue())
        return;

    Modulator gate = getModulator("Gate");
    float last = gate.getStepModStepValue(15);

    for (int step = 15; step > 0; --step)
        gate.setStepModStepValue(step, gate.getStepModStepValue(step - 1));
    gate.setStepModStepValue(0, last);
}

Example: Switch LFO waveform with the current articulation

// Switching the current articulation number also changes the LFO wave shape
// (in your own instrument, swap in the Parameter behind a menu widget)
// 0 = Sine, 1 = Triangle, 2 = Saw, 3 = Square, 4 = SampleHold, 5 = Drift
// (Assumes an LFO Modulator named "Tremolo" in the instrument.)
event CurrentArticulation(Parameter parameter)
{
    Modulator tremolo = getModulator("Tremolo");

    tremolo.setLFOWaveform(parameter);
}

Component


A Component is a handle to a single GUI element from your instrument's UI - a knob, button, menu, label, panel, animation, etc. In a Figma project, components appear in the left panel as layers marked in purple. From a script you can toggle its visibility, move it, set its value, bind it to a parameter, paint shapes on it, or drive its animation.

Get a Component via the free function getComponent(string controlID). The controlID is the name set on the element in Figma.

Example: Show or hide a panel from an on/off Parameter

// Fires when SustainPedal changes (built-in, MIDI CC 64 by default).
// Repurposed here as a panel visibility toggle for portable testing.
// (Assumes a Component named "MixerPanel" in the instrument UI.)
event SustainPedal(Parameter parameter)
{
    Component mixerPanel = getComponent("MixerPanel");

    mixerPanel.setVisible(parameter.getBoolValue());
}

Visibility & position

FunctionReturnsDescription
setVisible(bool visible) void Shows or hides the Component. true = visible, false = hidden.
setX(int x) void Sets the Component's x position relative to its parent, in design-space units - the same coordinates as the layout canvas, so the position holds as the window is resized.
setY(int y) void Sets the Component's y position relative to its parent, in design-space units.
setXInView(int x) void Sets the Component's x position relative to the whole view rather than to its parent. Useful for a Component nested in a Panel via addComponent, which would otherwise be positioned panel-relative. Leaves y unchanged.
setYInView(int y) void Sets the Component's y position relative to the whole view rather than to its parent. Leaves x unchanged.
setPositionInView(int x, int y) void Sets both axes at once, relative to the whole view. Coordinates are in the same design-space units as the layout canvas and setViewSize, so the position holds as the window is resized. For a Component parented directly to the view this matches setX/setY.
setBoundsInView(Bounds bounds)
setBoundsInView(int x, int y, int width, int height)
void View-relative setBounds: position and size together, both measured in the view. Under a scaled ancestor the Component ends up the requested size as seen in the view.
setAlpha(float alpha) void Sets the Component's opacity. Range: 0.0 (fully transparent) to 1.0 (fully opaque).
setEnabled(bool enabled) void Enables or disables interaction. true = interactive, false = grayed-out and unresponsive.
setTooltip(string tooltip) void Sets the text shown while the mouse hovers over the Component. An empty string removes it. Works on every Component type, and replaces a tooltip the layout gave this Component.
setTextEntryEnabled(bool enabled) void Whether double-clicking a knob or slider opens its type-in value field. On by default. false turns it off, and double-click then resets the control to its default. Cmd/Ctrl+click resets either way. Ignored on other Component types.

Value, text & state

FunctionReturnsDescription
setValue(float value) void Sets a numeric value on the Component. Valid range depends on the bound parameter or element type.
setText(string text) void Sets the text content (for labels, text fields, etc.).
setToggleState(bool state) void Sets the toggle state for buttons or switches. true = on/down/active, false = off/up/inactive.
setMenuSelection(int selection) void Sets the selected item on a menu by 0-based index.
setNumColumns(int columns) void Sets the number of columns for grid-style Components. Must be a positive integer.

Binding

Connect a Component to data sources at runtime: a UI parameter (so the component reflects and controls that parameter) or a panel variant (for Figma multi-variant panels).

FunctionReturnsDescription
setParameter(string parameterName) void Binds the Component to a UI Parameter by name. The Component will now reflect and control that parameter's value.
setPanelVariant(string variantName) void Switches a panel Component to a named Figma variant.

Painting

Draw shapes, text, or images onto a Component at runtime. The vector shapes (Ellipse, Rectangle, Arc, Path) are drawn with fill(...) and stroke(...): each takes the shape plus a Colour or a Gradient. fill fills the shape; stroke outlines it (using the shape's strokeWidth / strokeThickness). They are separate operations. To both fill and outline a shape, call fill and then stroke. Image and Text are drawn with paint(...). Every function draws behind the Component's children; the matching ...Over(...) form draws in front of them.

Not every Component type can be painted on. Paint onto a plain Component (no type set) or a panel; buttons, sliders, labels and animations work too. A menu authored in Figma, a level meter, a table, and an XY pad draw themselves instead, and discard script paint silently - no error, nothing drawn.

Coordinates are measured from the Component's own top-left corner, in the same units as your Figma layout, so a drawing keeps its place and proportions as the plugin is resized. A script can't read a Component's size back, so the numbers you paint with have to match the size the Component has in Figma. Keeping that size in a constant at the top of the script, as below, saves hunting for stray numbers when the layout changes.

What you paint stays on the Component until you clear it. If you repaint every frame from viewRefresh(), call clearCanvas() first. Otherwise each frame's drawing piles on top of the last and the Component fills up with old artwork. A layer that reaches 8192 paint calls takes no more and says so on the console. The usual shape is clear, then draw:

Example: Vector-painted pulse that follows the master level

// A pulse that grows and shifts from green to red with the master bus level.
// (Assumes a plain component named "LevelGlow", 100 x 100 px in Figma.)

const float kSize = 100.0f;      // must match the component's size in Figma (square)
const float kFloorDb = -48.0f;   // the level that maps to the smallest circle
const float kFallRate = 0.15f;   // how fast the circle shrinks back: 0 = frozen, 1 = instant

float displayLevel;              // 0..1, kept between frames so the fall is smooth

event initialize()
{
    setViewRefreshRate(60);      // the fastest UI rate KODA allows
}

event viewRefresh()
{
    Bus master = getMasterBus();
    Levels levels = master.getLevels();

    // Work in decibels. Linear gain spends most of its range close to silence,
    // so decibels spread the audible part across the circle's range.
    float db = levels.getRmsDecibels();                           // RMS of the louder channel, -180 (silence) .. +12, with 0 at unity
    float target = limit((db - kFloorDb) / -kFloorDb, 0.0f, 1.0f);   // -48..0 dB becomes 0..1

    // Follow the level up instantly, then ease back down.
    if(target > displayLevel)
        displayLevel = target;
    else
        displayLevel = displayLevel + (target - displayLevel) * kFallRate;

    Component glow = getComponent("LevelGlow");
    glow.clearCanvas();          // wipe last frame, or the circles stack up

    // Centered circle, growing from 10% to 100% of the component's width
    float diameter = kSize * (0.1f + displayLevel * 0.9f);
    float inset = (kSize - diameter) * 0.5f;
    Ellipse disc = (inset, inset, diameter, diameter, 0.0f);      // last member is strokeWidth

    // Hue sweeps green -> yellow -> red as the level rises; alpha brightens with it
    float hue = 0.33f * (1.0f - displayLevel);   // 0.33 = green, 0.16 = yellow, 0.0 = red
    glow.fill(disc, getColourHSBA(hue, 0.9f, 1.0f, 0.25f + displayLevel * 0.75f));
}
How much one run can paint

Each drawing call reaches the interface as one update, and a Path sends one more for each of its segments. Within one audio block, everything the script runs (event handlers, process() and viewRefresh() together) can send up to 4096 updates; anything past that is dropped, and the script console says so. That is plenty for a frame of ordinary drawing. When a big redraw runs out, spread it over several viewRefresh() calls, or draw curves with fewer, smoother segments (cubicTo rather than many short lineTos).

FunctionReturnsDescription
fill(Rectangle r, Colour|Gradient) void Fills a rectangle with a solid colour or a gradient (behind its children). Same overloads exist for Ellipse and Arc.
stroke(Rectangle r, Colour|Gradient) void Outlines a rectangle (line width = the shape's strokeWidth) with a colour or gradient. Same overloads exist for Ellipse and Arc.
fillPath(Path p, Colour|Gradient) void Fills a Path with a colour or gradient (behind its children).
strokePath(Path p, Colour|Gradient) void Strokes (outlines) a Path with a colour or gradient, using its strokeThickness / jointStyle / endCapStyle.
paint(Image image) void Paints an image onto the Component (behind its children).
paint(Text text) void Paints text onto the Component (behind its children). *** Not implemented yet: draws the placeholder word "Text" and ignores the Text struct. Use a Label Component and setText instead.
paint(Canvas canvas) void Paints a pre-recorded Canvas of paint actions onto the Component. Build a Canvas once, then reuse it across components.
clearCanvas() void Wipes everything previously painted on this Component. Call it at the top of viewRefresh() before redrawing, or each frame's artwork accumulates on the last.
setImageBacked(bool imageBacked) void false (the default) redraws as vectors, staying crisp at any resolution. true keeps the pixels between frames, so you can build an image up over time - a fading trail, for instance. Call before painting.
fillOver / strokeOver(…) void Same as fill / stroke but draws in front of the Component's children (Rectangle, Ellipse, Arc). Paths have fillPathOver / strokePathOver; Image/Text/Canvas have paintOver(...).
clearCanvasOver()
setImageBackedOver(bool imageBacked)
void The in-front-of-children versions of clearCanvas and setImageBacked. The two layers are kept separately, so clearing one leaves the other alone. A Component painted on both sides needs both calls to clear fully.
Technical sidenote

The behind-children and in-front-of-children layers hold independent drawings and independent image-backed settings. On a widget with no children the two look identical, so the choice only matters for containers like Panel, Menu, and ListItemBox.

Animation

For Components that hold animated content (e.g. Lottie or sprite-sheet animations from Figma), these functions control playback. An animation widget does not play on its own. It shows its first frame until the script calls start(), then runs at its Figma frame rate (default 12 fps, looping) or the rate set with setFrameRate(). To show a single frame without playing, call setFrame(). Recompiling or clearing the script stops every animation and returns it to its first frame, so initialize() is where playback is started.

FunctionReturnsDescription
start() void Starts the animation playing.
pause() void Pauses the animation at its current frame.
stop() void Stops the animation.
reset() void Resets the animation to its first frame.
reverse(bool reversed) void Sets the playback direction. true = play backwards, false = play forwards.
setFrameRate(int fps) void Sets the animation frame rate in frames per second. Typical: 24-60 fps.
setFrame(int frame) void Jumps to a specific frame (0-based). Playback continues from there unless the animation is stopped or paused.
setLooping(bool isLooping) void Sets whether the animation loops. true = loop continuously, false = play once and stop.

Example: Drive an animation with a toggle button

// Fires when SustainPedal changes (built-in, MIDI CC 64 by default).
// Repurposed here as an animation play/pause toggle for portable testing.
// (Assumes an animated Component named "Spinner" in the instrument UI.)
event SustainPedal(Parameter parameter)
{
    Component spinner = getComponent("Spinner");

    if(parameter.getBoolValue())
        spinner.start();
    else
        spinner.pause();
}

Bounds, rotation & scale

Position, orient and scale a Component after creation.

FunctionReturnsDescription
setBounds(Bounds bounds)voidSets position and size from a Bounds.
setRotation(float radians)voidRotates about the center; angle in radians (2π = full turn), 0.0 = none. For an angle in degrees, pass degreesToRadians(degrees).
setScale(float scale)voidUniform scale about the center; 1.0 = original.
setScale(float scaleX, float scaleY)voidNon-uniform scale per axis; 1.0 = original on that axis.
bringToFront()voidRaises to the front of its sibling z-order.
getName()stringReturns the Component's control ID.

Text formatting

For Label, value-edit and text-edit Components.

Note: setFont() also applies to a Menu.

FunctionReturnsDescription
setText(float value)voidSets text to a float (2 decimal places).
setText(float value, int numDecimals)voidSets text to a float with N decimals.
setText(int value)voidSets text to an integer.
clearText()voidClears the text.
setSuffix(string suffix)voidAppends a unit suffix to displayed text (e.g. " Hz").
setUnitType(UnitType unitType)voidFormats the value with a unit: UnitType::None, FrequencyHz (auto Hz/kHz above 1000), Decibels (shows "-inf" at silence), Percent, Milliseconds, Pan (100L..C..100R) or NoteName.
setAllowedCharacters(string characters)voidRestricts typeable characters on a text-edit (empty string restores default).
setFont(Font font)voidSets the font from a Font. On a Menu it styles the selected item's name shown while the menu is closed; anything painted with paintOver(menu, ...) replaces that text.

Effects & sprites

Attach visual effects and sprite sheets to a Component.

FunctionReturnsDescription
addEffect(Effect effect)voidAdds a visual effect (see Effect).
removeEffects()voidRemoves all effects.
setSprite(string path, int spriteWidth, int spriteHeight, int numFrames)voidAttaches a sprite sheet (per-frame size + frame count). path is a PNG file name relative to the library's ui/ folder. Only animation, button and slider widgets paint a sprite sheet; on other widgets the call has no visible effect.
setSprite(SpriteSheet sprite)voidAttaches a sprite sheet from a SpriteSheet.

Shaders

A Component can draw itself with a GLSL fragment shader instead of its artwork. The shader file sits in the library's ui/ folder and names the engine values it reads in annotations on its own uniforms (parameters, buses, sounding voices, the keys, the host transport and taps), so most shaders need no script at all. A script can give a Component a shader while it runs, and write the shader's plain uniforms, the ones without an annotation, which read 0 until it does. Knobs, sliders, buttons, panels and plain Components draw a shader; on other types it has no visible effect.

FunctionReturnsDescription
setShader(string path)voidDraws the Component with the shader file at path, relative to the library's ui/ folder, as a layout's Shader property does. An empty path takes the shader off and the artwork shows again. Setting the shader the Component already draws keeps it as it is, with the values the script wrote to its uniforms; only a file saved since it was read is loaded again.
setShaderUniform(string name, float value)voidWrites a plain float uniform of the Component's shader. The value holds until the next write. A plain number such as 0.5 or 1 works too.
setShaderUniform(string name, float<2> value)voidWrites a plain vec2 uniform. Build the value from float literals: float<2> (0.2f, 0.8f).
setShaderUniform(string name, float<4> value)voidWrites a plain vec4 uniform.
triggerShader(string name)voidWrites the time now into a plain float uniform, on the clock the shader's u_time reads, so the shader can animate from that moment: exp(-(u_time - hit) * 6.0) is a flash that fades.

A Tap insert, on a bus, send or Master chain, passes its audio through untouched and lets shaders show it: [[ tap: "Name" ]] reads its levels like a bus, [[ spectrum: "Name" ]], [[ waveform: "Name" ]] and [[ scope: "Name" ]] read a spectrum, a scrolling waveform and an oscilloscope as sampler2D uniforms (read one with koda_tapAt(view, x); on a spectrum koda_spectrumX(hz) gives the position of a frequency). Leave the name out, as in [[ spectrum ]], and the shader reads the tap named by the Component's Tap layout property, so one shader file can show different taps on different Components. The analysis runs on the GUI side, never on the audio thread.

A shader can also start from the Component's own artwork: [[ artwork ]] is what the Component would paint right now (its hover, pressed or on look, the knob frame for its value), and [[ artwork: "On" ]] one of its variants, both drawn at the shader's size so fragCoord / u_resolution lines up with them. [[ image: "noise.png" ]] reads an image file beside the shader, repeating. Read any of them with koda_artwork(texture, uv), which gives straight alpha: a glow around a Figma knob, or a button that fades between its Off and On art instead of snapping.

A write lands with the frame's other GUI changes, so the last write to a uniform within a frame is the one drawn. Write from viewRefresh() or an event handler, not from process(), which runs every few samples and would flood the GUI queue. A write that can't land (no uniform of that name, one fed by an annotation, a built-in such as u_time, or a value of the wrong size) is reported once in the console. Script writes reach the shader only while the host runs audio; values from annotations don't depend on it.

// orb.frag declares two plain uniforms:  uniform float hit;  uniform float level;
float level;                // set by the script elsewhere

event noteOn(NoteData note)
{
    Component orb = getComponent("Orb");
    orb.triggerShader("hit");          // a flash from this moment
    note.start();
}

event viewRefresh()
{
    Component orb = getComponent("Orb");
    orb.setShaderUniform("level", level);
}

Containers & event routing

Nest Components and route their input to script event handlers.

FunctionReturnsDescription
addComponent(Component child)voidRe-parents a child into this (panel) Component so it moves and scales with it. Call on the parent: panel.addComponent(child). The child keeps its bounds numbers, but they are now measured from the panel's top-left corner: give it panel-relative coordinates, or place it with setPositionInView / setBoundsInView, which take view coordinates.
sendMouseEvents(int identifier)voidRoutes this Component's mouse events to a script event handleMouse(MouseEvent mouseEvent) handler; read mouseEvent.getIdentifier() to tell components apart. Every type except Move: see sendMouseMoveEvents. (Works on every widget type. A slider or button still handles the click itself and forwards it too.)
sendMouseMoveEvents(int identifier)voidRoutes pointer motion with no button held (MouseEventType::Move) to the same handleMouse handler. Opt-in on purpose: sendMouseEvents never carries Move, so a click handler is never flooded by hover motion. Call both on a Component to receive the full set.
sendGuiEvents(int identifier)voidRoutes value/selection changes to a script event handleGuiEvent(GuiEvent guiEvent) handler; read guiEvent.getIdentifier() and guiEvent.getValue().

Menu & list items

For Menu and ListItemBox Components.

FunctionReturnsDescription
addItem(string name, int value)voidAdds an item (display label + user int reported on selection).
clearItems()voidRemoves all items.
setListSelection(int index)voidSelects a ListItemBox item by index (−1 clears).
clearMenuSelection()voidClears a Menu's selection (same as setMenuSelection(−1)).
setItemSize(int width, int height)voidPer-item pixel size. On a Menu with no item templates, the height is the row height and the width is the list's minimum width; 0 leaves either as it is.
setItemTextFont(Font font)voidItem text font.
setItemTextBounds(Bounds bounds)voidItem text layout bounds within each item.
setItemTextColour(Colour colour, int state)voidItem text colour per state; MenuItemState:: Normal=0, Hover=1, Selected=2.
setMenuBackgroundColour(Colour colour)voidMenu drop-down background.
setMenuOutlineColour(Colour colour)voidMenu drop-down border colour.
setMenuOutlineThickness(float thickness)voidMenu drop-down border thickness in pixels.

A Menu's drop-down list scales with the instrument GUI. When a GUI is made on a large canvas and shown scaled well down, KODA draws the list larger than the GUI so that its text is never smaller on screen than the default list at full size. To size the list yourself, give a height with setItemSize or a font height with setItemTextFont. The list is then drawn at exactly the GUI's scale. A list built from item templates is always drawn at the GUI's scale.

Preset browser & buttons

A PresetBrowser is a menu that lists the player's saved presets of one preset type and loads the one they pick; subfolders of the type's preset folder appear as submenus. A PresetButton saves the type's current values as a new preset through the save dialog. A PresetNextButton or PresetPreviousButton loads the next or previous preset of the type, in the order the PresetBrowser lists them with every submenu opened, and wraps round at either end. It steps from the preset last loaded or saved through any of these widgets; before there is one, Next loads the first preset and Previous the last. Preset types are set up in the instrument's PRESETS module (Setup page, Instrument level). All of these widgets find their presets by the preset type's name and do the loading and saving themselves: no event reaches the script for any of them.

Style a PresetBrowser with the Menu functions above. On a PresetBrowser they style its drop-down list, which is the kind that can show submenus: setItemSize sets the item height (its width becomes the list's minimum width), setItemTextBounds uses only x and y (the text's inset), setItemTextColour uses MenuItemState::Normal and Hover, and the current preset is marked with a tick. setFont and setText set the closed menu's text, which shows the loaded preset's name, or the setText text until one is loaded. Paint its closed look like any Component. addItem, clearItems and item templates (getItemTemplate) do not apply. Draw a PresetButton, PresetNextButton or PresetPreviousButton like a button, with setSprite or by painting.

FunctionReturnsDescription
setPresetType(string presetType)voidPoints a PresetBrowser, PresetButton, PresetNextButton or PresetPreviousButton, script-created or from the layout, at the preset type with this name (case doesn't matter). Other widgets ignore it.
setMenuHighlightColour(Colour colour)voidFill of the item under the pointer in a PresetBrowser's drop-down list.

The viewRefresh() event

event viewRefresh() fires once per UI "frame" at a configurable rate (default 24 Hz). Use it to update painted UI and animated readouts.

Note

It is not synced to the actual GUI framerate, so don't rely on it for precise timing.

FunctionReturnsDescription
setViewRefreshRate(int hz)voidSets the viewRefresh rate; clamped 12-60 Hz (default 24). Only the instrument-level (root) script's setting takes effect.
getViewRefreshRate()intReturns the current viewRefresh rate in Hz.

Creating Widgets at Runtime


Beyond binding to widgets you laid out in Figma, a script can create widgets at runtime (e.g. in event initialize()). Each create function returns a Component handle you keep and drive like any other. Positions and sizes use a Bounds (x, y, width, height in pixels).

An instrument without a layout file has no view until the script sets the view size: call setViewSize first, in event initialize(), and KODA shows the instrument's UI at that size. An instrument with a layout file already has its size from the layout. You can still call setViewSize(), but it overrides the size set in the layout file and rescales the layout's widgets to the new size.

FunctionReturnsDescription
setViewSize(int width, int height)voidSets the view size: the design size of the whole view, in the same design-space units as the layout canvas and every Bounds. Call it before creating widgets so they are placed in the final coordinate space. KODA clamps each side (width or height) to be between 50 and 4000 pixels. And the width-to-height ratio is clamped to be between 0.5 and 4.0. The sides are clamped first; if the ratio is then out of range, the width is kept and the height is changed to the nearest allowed ratio (4000 x 500 becomes 4000 x 1000).
FunctionReturnsDescription
createButton(string name, Bounds bounds)ComponentCreates a button.
createPanel(string name, Bounds bounds)ComponentCreates a panel; use as a container (addComponent) or a paint surface.
createKnob(string name, Bounds bounds)ComponentCreates a knob, the same widget type as a Knob in the layout.
createRotarySlider(string name, Bounds bounds)ComponentOlder name for createKnob. Prefer createKnob.
createHorizontalSlider(string name, Bounds bounds)ComponentCreates a horizontal slider.
createVerticalSlider(string name, Bounds bounds)ComponentCreates a vertical slider.
createLabel(string name, Bounds bounds, string text)ComponentCreates a text label with initial text.
createXYPad(string name, Bounds bounds, string parameterX, string parameterY)ComponentCreates an XY pad bound to two parameters by name (one per axis).
createMenu(string name, Bounds bounds)ComponentCreates a drop-down menu; populate with addItem().
createPresetBrowser(string name, Bounds bounds, string presetType)ComponentCreates a menu that lists and loads the player's presets of presetType; see Preset browser & buttons.
createPresetButton(string name, Bounds bounds, string presetType)ComponentCreates a button that saves the current values of presetType as a new preset.
createPresetNextButton(string name, Bounds bounds, string presetType)ComponentCreates a button that loads the next preset of presetType, in the PresetBrowser's order.
createPresetPreviousButton(string name, Bounds bounds, string presetType)ComponentCreates a button that loads the previous preset of presetType, in the PresetBrowser's order.
createListItemBox(string name, Bounds bounds)ComponentCreates a scrollable list; populate with addItem(), track with setListSelection().
createSearchField(string name, Bounds bounds)ComponentCreates a text/search entry field.
createStateDisplay(string name, Bounds bounds)ComponentCreates a state-display widget.
createAnimation(string name, Bounds bounds)ComponentCreates an animation widget; drive with the Animation functions (start/pause/setFrame/…).

The name argument is the new Component's control ID (used later with getComponent).

A Component made this way arrives with no artwork, so it is invisible until you give it one, either by attaching a sprite sheet with setSprite or by painting on it. It is also inert until you connect it to something: setParameter links a button to a Parameter, so clicking it drives that Parameter and your handler for it runs. The example below does both. A knob or slider made this way opens its type-in value field on double-click, like one from the layout; setTextEntryEnabled(false) turns that off.

Artwork files live in the library's ui/ folder, next to the layout file. Scripts load raster files only (PNG for sprite sheets, PNG or JPEG for a painted Image); SVG artwork reaches an instrument through the layout file, which references or embeds it. KODA re-reads the artwork when a script is recompiled (sprite sheets and painted images). So after replacing such a file on disk, recompile the script to see the new version. Note: artwork attached by a (Figma) layout file is re-read when the layout reloads.

Example: Build a Play button in the script

// Draws a rectangular green button in the upper left of the GUI
// (Assumes a Parameter named "PlayToggle" in the instrument.)

const float kButtonWidth = 240.0f;
const float kButtonHeight = 80.0f;

Component playButton;      // kept at script scope so later events can repaint it

event initialize()
{
    playButton = createButton("Play", Bounds(10.0f, 10.0f, kButtonWidth, kButtonHeight));
    playButton.setParameter("PlayToggle");   // clicks now drive that Parameter
    paintButton(false);                     // draw the "off" look right away
}

// Fires whenever PlayToggle changes, including the click that changed it
event PlayToggle(Parameter parameter)
{
    paintButton(parameter.isTrue());
}

// Paint coordinates are local to the button, so they start at 0, 0
void paintButton(bool playing)
{
    playButton.clearCanvas();

    // Rectangle members are x, y, width, height, strokeWidth, cornerRadius
    Rectangle body = (0.0f, 0.0f, kButtonWidth, kButtonHeight, 0.0f, 6.0f);
    playButton.fill(body, playing ? colours::limegreen : colours::dimgrey);
}
Bounds are in your UI's own coordinates

The x, y, width and height you pass are in the same coordinate space as your Figma layout, and KODA scales them with the window. On a wide layout, Bounds(10, 10, 80, 30) is a small control in the top-left corner, not a button that fills the screen.

Colour


Colour is the strong ARGB colour type used across the paint API, replacing the raw int32 values used in earlier builds. It has a single member variable value (int32, packed 0xAARRGGBB), but you normally build colours with the colours:: constructors and read or change them with the functions below rather than touching value directly.

Construction

The colours:: constructors are free functions that each return a Colour.

FunctionReturnsDescription
colours::fromRGB(int r, int g, int b)ColourOpaque colour from 8-bit channels (each 0-255).
colours::fromRGBA(int r, int g, int b, int a)ColourFrom 8-bit channels plus alpha (each 0-255). An overload takes a float alpha 0.0-1.0.
colours::fromRGB(int hex)ColourFrom a 24-bit hex RGB literal (e.g. 0xFF7F00), opaque.
colours::fromHex(int64 hex)ColourFrom a 32-bit ARGB literal. Use the _L suffix so an alpha ≥ 0x80 doesn't overflow int32 (e.g. 0xFFFFA500_L).
colours::fromFloat(float r, float g, float b, float a)ColourFrom float channels (each 0.0-1.0). A 3-arg overload omits alpha and returns an opaque colour.
colours::fromHSB(float h, float s, float b)ColourOpaque colour from HSB components (each 0.0-1.0; the hue wraps around). fromHSBA adds an alpha argument. For a hue in degrees, as design tools give it, pass degreesToHue(degrees); a hue far outside 0-1 is a console warning.
colours::fromHSL(float h, float s, float l)ColourOpaque colour from HSL components (each 0.0-1.0). fromHSLA adds an alpha argument.

There are also named constants such as colours::white, colours::black, colours::red, colours::orange, colours::dodgerblue, and colours::transparent, along with the full CSS/JUCE colour-name set, each a const Colour.

KODA Palette

The palette:: namespace holds KODA's own colours, so a script UI can match the app without pasting hex values: 16 accent hues, the gold, the Shade ramp the app is painted with, and a rule for picking readable text on any fill. Each hue comes in two values: one for a dark surface and a deeper one for a light surface. Every hue has at least 4.5:1 contrast with the surface it's meant for.

Function / constantReturnsDescription
palette::hue(int index)ColourThe hue at index, for a dark surface. Any index is valid: it wraps, so hue(16) is hue(0) and hue(-1) is hue(15).
palette::hueOnLight(int index)ColourThe same hue, deepened for a light surface. Wraps like hue.
palette::hueFor(int index, bool lightSurface)ColourhueOnLight(index) when lightSurface is true, otherwise hue(index). Use it when the script has a Dark / Light switch.
palette::numHuesintThe number of hues, 16.
palette::goldColourKODA's accent gold, #CCAA66. The same colour as hue(0).
palette::shade5 … palette::shade100ColourThe Shade ramp: cool neutrals from near-black to near-white, with the same names as the app's own UI. The steps are shade5, 8, 10, 12, 13, 15, 16, 18, 20, 25, 27, 30, 40, 50, 53, 60, 69, 70, 80, 90, 95 and 100. The number is the brightness in percent.
palette::inkFor(Colour fill, bool lightSurface)ColourThe colour for text or an icon on fill: whichever of the surface's dark and light inks has more contrast with it. The inks are shade5 and shade100 on a dark surface, and shade12 and #F7F9FB on a light one. It's computed rather than looked up, so it works for any fill, including your own colours.
palette::contrast(Colour a, Colour b)floatThe WCAG 2 contrast ratio between two colours, from 1.0 (identical) to 21.0 (black on white). Alpha is ignored. 4.5 is the usual minimum for body text; use it to check an accent you picked yourself.

The hues, by index:

IndexNamehue (dark surface)hueOnLight (light surface)
0Gold#CCAA66#7D5E14
1Olive#B4AF58#6C6600
2Lime#96B86C#506F22
3Green#74BF87#287441
4Jade#53C1A5#00775E
5Teal#3EC0C2#007578
6Cyan#49BBD9#00718D
7Azure#66B3EA#136A9C
8Blue#87AAF1#4261A2
9Violet#A5A0ED#5F589F
10Purple#BF98E0#755093
11Orchid#D391CB#864A80
12Pink#E18DB0#924668
13Rose#E88D93#98464D
14Coral#E69277#974A31
15Amber#DD9A5F#8F520E

These values can be retuned in a later KODA version, and a retune reaches every script that uses the names; the release notes will say so. If a colour must never change, write its hex yourself with colours::fromHex.

// One accent for the whole UI
const Colour kAccent = palette::gold;

// A swatch of the chosen hue with a marker that stays readable on either surface
void paintSwatch(int hueIndex, bool lightSurface)
{
    swatch.clearCanvas();

    Colour fill = palette::hueFor(hueIndex, lightSurface);
    Rectangle body = (0.0f, 0.0f, 40.0f, 40.0f, 0.0f, 6.0f);
    swatch.fill(body, fill);

    Rectangle marker = (16.0f, 16.0f, 8.0f, 8.0f, 0.0f, 4.0f);
    swatch.fill(marker, palette::inkFor(fill, lightSurface));
}

Channels & HSB

Read individual channels as 8-bit integers or normalized floats, or pull out HSB components.

FunctionReturnsDescription
getAlpha() / getRed() / getGreen() / getBlue()intChannel value 0-255.
getAlphaFloat() / getRedFloat() / getGreenFloat() / getBlueFloat()floatChannel value 0.0-1.0.
getHue() / getSaturation() / getBrightness()floatHSB component 0.0-1.0.

Transforms

Each transform returns an immutable copy; the original colour is unchanged.

FunctionReturnsDescription
withAlpha(float a)ColourCopy with alpha set (0.0-1.0). A whole number converts, so withAlpha(1) is opaque. An alpha past 1.0 is drawn opaque, and the console says so once.
withAlpha8(int a)ColourCopy with alpha set as 0-255, as in a hex colour.
withMultipliedAlpha(float m)ColourCopy with the current alpha multiplied by m.
brighter(float amt)ColourCopy blended toward white (0.0 = unchanged, 1.0 = white).
darker(float amt)ColourCopy blended toward black (0.0 = unchanged, 1.0 = black).
withHue(float h) / withSaturation(float s) / withBrightness(float b)ColourCopy with one HSB component replaced (each 0.0-1.0).
interpolatedWith(Colour other, float t)ColourLinear blend; t 0.0 = this colour, 1.0 = other.
overlaidOn(Colour background)ColourBlends this colour over a solid background, using its alpha.
// Build a base colour, then derive a translucent, brighter variant.
Colour base    = colours::fromRGB(96, 192, 128);
Colour lighter = base.brighter(0.3f);
Colour overlay = lighter.withAlpha(0.5f);

Paint Primitives


Paint primitives are plain data structs that describe shapes, text, or images to draw onto a Component. The vector shapes (Ellipse, Rectangle, Arc, Path) carry only geometry. Colour is supplied at draw time: construct the shape, set its member variables, then pass it to fill(shape, colour) / stroke(shape, colour) (or fillPath / strokePath for a Path), passing a Colour or a Gradient. Image and Text are drawn with paint(image) / paint(text).

Unlike most KODA types, paint primitives don't expose getters or setters. You read and write their member variables directly. All coordinates are in pixels relative to the Component's origin. All sizes are in pixels.

Colour format

Colours are passed to fill / stroke (and used inside a Gradient's stops) as the strong Colour type. Build one with a colours:: constructor (e.g. colours::fromRGB(96, 192, 128) or colours::fromHex(0xFF60C080_L)) or use a named constant (e.g. colours::aliceblue, colours::black). Use colours::transparent (or any colour with zero alpha) for an invisible draw. See the Colour section for channel getters and transforms.

Target Component setup

Painting onto a Component requires specific widget setup in your instrument's UI. Not every Component type will render paint actions, and Panel-type Components belong to visibility groups managed by the panel-group system. Examples and recipes for setting up a paintable Component will appear here once that workflow is documented. For now, refer to the Component section for known-good binding patterns.

Point & Bounds

Lightweight position and size structs used as building blocks (notably inside Path).

Point - a 2D coordinate
Member VariableTypeDescription
xfloatX coordinate in pixels.
yfloatY coordinate in pixels.
Bounds - a position + size rectangle
Member VariableTypeDescription
xfloatX position of the top-left corner.
yfloatY position of the top-left corner.
widthfloatWidth in pixels.
heightfloatHeight in pixels.

Building shapes

A shape written as a list of numbers is easy to get wrong: in Rectangle r = (0, 0, 100, 40, 6); the 6 is the stroke width, not the corner radius. These build each shape from a Bounds, with every other number named. A built shape's stroke width starts at 1.0; withStrokeWidth changes it.

Bounds b = (0.0f, 0.0f, 100.0f, 40.0f);
panel.fill(makeRoundedRectangle(b, 6.0f), colours::darkslategrey);
panel.stroke(makeEllipse(b).withStrokeWidth(2.0f),
             makeLinearGradient(0.0f, 0.0f, 100.0f, 0.0f, colours::white, colours::grey));
FunctionReturnsDescription
makeRectangle(Bounds b)RectangleA rectangle filling b, square corners.
makeRoundedRectangle(Bounds b, float cornerRadius)RectangleThe same, with rounded corners.
makeEllipse(Bounds b)EllipseAn ellipse filling b.
makeArc(Bounds b, float startAngle, float endAngle)ArcAn arc around b's centre. Angles in radians, 0 at 12 o'clock, clockwise; degreesToRadians converts from degrees.
withStrokeWidth(float strokeWidth)the shapeA copy of a Rectangle, Ellipse or Arc with this outline thickness.
makeLinearGradient(float x1, float y1, float x2, float y2, Colour from, Colour to)GradientFrom from at (x1, y1) to to at (x2, y2). addStop adds more stops.
makeRadialGradient(float centreX, float centreY, float radius, Colour inner, Colour outer)GradientFrom inner at the centre to outer at radius.

Ellipse

An ellipse shape. Draw it with fill(ellipse, …) and/or stroke(ellipse, …), passing a Colour or a Gradient.

Member VariableTypeDescription
xfloatX position of the ellipse's bounding box.
yfloatY position of the ellipse's bounding box.
widthfloatBounding-box width (full diameter on the x-axis).
heightfloatBounding-box height (full diameter on the y-axis).
strokeWidthfloatOutline thickness in pixels, used by stroke().

Rectangle

Same as Ellipse, plus a corner-radius member variable for rounded rectangles. Draw with fill(rectangle, …) / stroke(rectangle, …).

Member VariableTypeDescription
xfloatX position of the top-left corner.
yfloatY position of the top-left corner.
widthfloatWidth in pixels.
heightfloatHeight in pixels.
strokeWidthfloatOutline thickness in pixels, used by stroke().
cornerRadiusfloatRadius for rounded corners in pixels. 0.0 = square corners.

Arc

A circular arc swept between two angles. Useful for knob indicators, ring meters, and pie-style readouts. Draw with fill(arc, …) / stroke(arc, …).

Member VariableTypeDescription
xfloatX position of the arc's bounding box.
yfloatY position of the arc's bounding box.
widthfloatBounding-box width.
heightfloatBounding-box height.
startAnglefloatStart angle in radians. 0 = 12 o'clock; positive = clockwise (0.5 * pi = 3 o'clock, pi = 6 o'clock).
endAnglefloatEnd angle in radians, same origin. The arc sweeps clockwise from start to end; an end smaller than the start sweeps counter-clockwise.
strokeWidthfloatOutline thickness in pixels, used by stroke().

Path

A multi-segment vector outline built from straight lines and Bézier curves. A Rectangle or Ellipse is described by setting its member variables - x, y, width, height. A Path isn't: you build it by calling its segment functions, then draw it with the Component's fillPath(path, colour|gradient) or strokePath(path, colour|gradient).

Build and draw as many Paths as you like in one function. Each draw call carries that path's own points, so paths never interfere with one another, and calling fillPath and then strokePath on the same Path fills it and then outlines it.

A Path holds up to 64 segments: startNewSubPath, lineTo, quadraticTo, cubicTo and close each add one. Segments added past that are dropped, so the shape is drawn cut short, and the script console says so the first time it happens. Draw a longer outline as several Paths. Pieces of one filled shape should overlap by a segment rather than just touch, or a faint seam can show where their edges meet.

Member Variables
Member VariableTypeDescription
strokeThicknessfloatStroke thickness in pixels (for strokePath()).
jointStyleintHow stroked corners join: JointStyle::mitered = 0, curved = 1, beveled = 2.
endCapStyleintHow stroked ends are capped: EndCapStyle::butt = 0, square = 1, rounded = 2.
Build functions
FunctionReturnsDescription
startNewSubPath(float x, float y) void Begins a new sub-path at (x, y) without drawing a line to it. Call before the first segment of a disconnected shape.
lineTo(float x, float y) void Adds a straight line from the current point to (x, y).
quadraticTo(float controlX, float controlY, float x, float y) void Adds a quadratic Bézier curve to (x, y) using one control point.
cubicTo(float control1X, float control1Y, float control2X, float control2Y, float x, float y) void Adds a cubic Bézier curve to (x, y) using two control points.
close() void Closes the current sub-path by drawing a line back to its start point.
clear() void Removes all segments so the Path can be rebuilt.

Example: Paints a triangle onto a Component

// Paints a triangle onto a plain Component named "Canvas" (100 x 100 px in Figma).
event initialize()
{
    Path triangle;
    triangle.strokeThickness = 2.0f;
    triangle.startNewSubPath(10.0f, 10.0f);
    triangle.lineTo(90.0f, 10.0f);
    triangle.lineTo(50.0f, 80.0f);
    triangle.close();

    Component canvas = getComponent("Canvas");
    canvas.strokePath(triangle, colours::red);
}

Gradient

A multi-stop colour gradient. Pass a Gradient in place of a Colour to any fill / stroke / fillPath / strokePath to fill or outline a shape with a gradient. Build it by setting the type and endpoints, then adding up to 16 colour stops with addStop(position, colour).

Gradient types

Set type to one of GradientType::Linear (0), GradientType::Radial (1), GradientType::Angular (2), or GradientType::Diamond (3). Only Linear and Radial render today. Angular and Diamond are reserved for a future JUCE version and currently draw nothing (a one-time warning is logged to the script console). For Linear the gradient runs along the axis from (x1,y1) to (x2,y2); for Radial it runs from the center (x1,y1) out to (x2,y2). Coordinates are in pixels relative to the Component's origin.

Member Variables
Member VariableTypeDescription
typeintGradientType::Linear / Radial / Angular / Diamond. Default 0 = Linear.
x1floatX of the gradient start point (center for Radial).
y1floatY of the gradient start point (center for Radial).
x2floatX of the gradient end point (edge for Radial).
y2floatY of the gradient end point (edge for Radial).
Functions
FunctionReturnsDescription
addStop(float position, Colour colour) void Adds a colour stop at position (0.0 = start, 1.0 = end). Up to 16 stops; extra calls are ignored.
clear() void Removes all stops so the Gradient can be rebuilt.

Example: Paints a gradient-filled rectangle

// Fills a plain Component named "Canvas" (100 x 100 px in Figma) with a 3-stop linear gradient.
event initialize()
{
    Rectangle r = (0.0f, 0.0f, 100.0f, 100.0f, 0.0f, 0.0f);   // x, y, width, height, strokeWidth, cornerRadius

    Gradient g;
    g.type = GradientType::Linear;
    g.x1 = 0.0f; g.y1 = 0.0f;       // top
    g.x2 = 0.0f; g.y2 = 100.0f;     // bottom
    g.addStop(0.0f, colours::dodgerblue);
    g.addStop(0.5f, colours::white);
    g.addStop(1.0f, colours::black);

    Component canvas = getComponent("Canvas");
    canvas.fill(r, g);
}

Image

Paints an image file into a rectangular region. The file lives in the library's ui/ folder, next to the layout file (typically exported alongside the Figma UI), and must be a raster image (PNG or JPEG); SVG artwork can only come in through the layout file.

Member VariableTypeDescription
imagestringFile name of the image, relative to the library's ui/ folder (e.g. logo.png or art/logo.png).
xfloatX position of the top-left corner.
yfloatY position of the top-left corner.
widthfloatDisplay width in pixels.
heightfloatDisplay height in pixels.

Text

Paints a string of text. Use for runtime-generated labels, value readouts, or status indicators where the text changes based on parameter values.

*** Not implemented yet. Painting a Text draws a placeholder and ignores every member below. For text that changes at runtime, use a Label Component and setText.

Member VariableTypeDescription
textstringThe string to render.
fontstringFont family name (e.g. "Inter"). Must be available to the instrument.
xfloatX position of the text's bounding box.
yfloatY position of the text's bounding box.
widthfloatBounding-box width (text wraps if it overflows).
heightfloatBounding-box height.
fontSizefloatFont size in points.
fontColourColourText colour (ARGB).

Font

A font spec for label-style widgets and Menus, passed to setFont() / setItemTextFont().

Font - a label/value font spec
Member VariableTypeDescription
namestringFont family name (e.g. "Inter"): a font built into KODA, or one in the library's fonts folder. A name KODA doesn't have draws in Inter, with a warning in the console.
stylestringStyle name: "Regular", "Bold", "Italic", "Bold Italic", etc.
heightfloatPoint height. A value ≤ 0 keeps the widget's current height.
justificationintText alignment, one of the Justification constants: Justification::Keep (no change, the default), Left, Center, Right (horizontal only), or TopLeft, TopCenter, TopRight, CenterLeft, Centered, CenterRight, BottomLeft, BottomCenter, BottomRight. Use the names: another number is a console warning.
kerningfloatExtra inter-character spacing factor (0.0 = default).
colourColourText colour. An alpha of 0 keeps the current colour.

Effect

A visual effect added to a Component via addEffect().

Effect - a component visual effect
Member VariableTypeDescription
typeintEffect kind; EffectType:: constants: Blur=0 (blurs the component's own content), BackgroundBlur=1 (frosted-glass blur of what's behind it), DropShadow=2 (offset shadow), Glow=3 (centered halo).
radiusfloatBlur/spread radius in pixels.
tintColourShadow/glow colour (DropShadow/Glow) or tint.
offsetXfloatHorizontal shadow offset in pixels (DropShadow).
offsetYfloatVertical shadow offset in pixels (DropShadow).

Canvas

A Canvas records a list of paint actions you build once and then draw onto one or more Components with paint(Canvas) / paintOver(Canvas). Use it to avoid re-issuing the same paint calls per component. Declare one with Canvas myCanvas;.

FunctionReturnsDescription
fill(Rectangle r, Colour|Gradient)boolRecords a filled rectangle. Same overloads for Ellipse and Arc. Returns false if the canvas is full.
stroke(Rectangle r, Colour|Gradient)boolRecords a stroked rectangle. Same overloads for Ellipse and Arc. Returns false if the canvas is full.
fillPath(Path p, Colour|Gradient)boolRecords a filled path. Returns false if the canvas is full.
strokePath(Path p, Colour|Gradient)boolRecords a stroked path. Returns false if the canvas is full.
paint(Text text)boolRecords text. Returns false if the canvas is full. *** Not implemented yet: draws a placeholder and ignores the Text struct.
paint(Image image)boolRecords an image. Returns false if the canvas is full.
clear()voidClears all recorded actions.

Example: Paints a prebuilt Canvas onto a Component

// Builds the artwork once, then draws it onto a plain Component named "Canvas" (100 x 100 px in Figma).
event initialize()
{
    Canvas artwork;

    Rectangle r = (0.0f, 0.0f, 100.0f, 100.0f, 0.0f, 0.0f);   // x, y, width, height, strokeWidth, cornerRadius
    artwork.fill(r, colours::dodgerblue);

    Component canvas = getComponent("Canvas");
    canvas.paint(artwork);
}

SpriteSheet

Describes a sprite sheet passed to setSprite() for animated Components. A sheet is one image holding all frames in a single row or a single column, every frame of the same size; width, height and frames describe them. KODA compares the image's width with frames x width and its height with frames x height and reads the frames along the axis that matches (a tie picks the column). With frames = 0 it takes the longer side of the image and divides it by the frame size to get the count. Frames are numbered from 0, starting at the top of a column or the left of a row.

SpriteSheet - a sprite-sheet definition
Member VariableTypeDescription
pathstringFile name of the sprite sheet (PNG), relative to the library's ui/ folder. A sheet with one frame shows a still image (on an animation, button or slider).
widthintPer-frame width in pixels.
heightintPer-frame height in pixels.
framesintTotal number of frames in the sheet.

MouseEvent


A MouseEvent is passed to your script when the user interacts with a Component that has a mouse event declared. You handle one by writing event <Name>(MouseEvent mouseEvent) { ... }, where <Name> matches the event name set on the Component in Figma. The event tells you where the mouse was (x, y), which modifier keys were held, and what kind of mouse action occurred.

Target widget setup

Every widget type forwards its mouse events to the script alongside its own handling. A knob still turns when dragged and still opens its value field on double-click, and the script receives the same Down, Drag, Up and DoubleClick. Attach the "MouseEvent" property to the Component in Figma, or call sendMouseEvents on it from the script.

Event names follow the same rule as Parameter names: a Cmajor identifier that is neither a keyword nor a name this reference already uses.

Example: Logging a double-click on a knob

// Needs a knob or slider in the layout whose component name is "Slider".
Component knob = getComponent("Slider");

event initialize()
{
    setLogEnabled(true);
    knob.sendMouseEvents(1);                  // send this widget's mouse events to handleMouse, tagged 1
}

event handleMouse(MouseEvent mouseEvent)      // one handler for every widget that calls sendMouseEvents
{
    if (mouseEvent.isDoubleClick())
        debug.log("double-click, id", mouseEvent.getIdentifier());   // the tag tells widgets apart
}

Member Variables

Member VariableTypeDescription
xintX position of the mouse relative to the Component's origin.
yintY position of the mouse relative to the Component's origin.
modsintBitfield of held modifier keys. Compare with MouseModifiers::Command, ::Shift, ::Alt, or use the isCommandDown() / isShiftDown() / isAltDown() helpers below.
rightClickintNon-zero when the press is a right-click. Prefer isRightClick() / isLeftClick().
typeMouseEventTypeWhat kind of mouse action this is. One of Down, Up, Enter, Exit, DoubleClick, StartDrag, Drag, DragEnter, DragExit, Drop, Move. It is an enum: compare it with == against MouseEventType::Down and so on, or use the is...() helpers below. Move (pointer motion with no button held) is opt-in: it only reaches a handler declared with the "MouseMoveEvent" property (with an optional "MouseMoveEventId") or a Component tagged with sendMouseMoveEvents; the catch-all "MouseEvent" property and sendMouseEvents never carry it. Give "MouseEvent" and "MouseMoveEvent" the same handler name to receive the full set. Move and Drag are dropped while the script's mouse queue is more than half full, which only happens when the host is not processing audio; every other type is always queued.
identifierintThe tag of the source Component: the number passed to sendMouseEvents(identifier), or the identifier set on the widget in the layout, so one shared handler can tell components apart.

Functions

FunctionReturnsDescription
getIdentifier()intReturns the event's identifier member variable.

Modifier-key helpers

FunctionReturnsDescription
isCommandDown()booltrue if Command (⌘ on macOS, Ctrl on Windows) was held during the event.
isShiftDown()booltrue if Shift was held.
isAltDown()booltrue if Alt / Option was held.

Event-type helpers

FunctionReturnsDescription
isLeftClick()booltrue on a left-button press (Down event, non-right-click).
isRightClick()booltrue on a right-button press (Down event, right-click).
isDown()booltrue if type is Down.
isUp()booltrue if type is Up.
isEnter()booltrue if the mouse entered the Component's bounds.
isExit()booltrue if the mouse left the Component's bounds.
isDoubleClick()booltrue on a double-click.
isStartDrag()booltrue when a drag operation starts.
isDrag()booltrue if this is a drag event (mouse moved while a button is held).
isDragEnter()booltrue when a drag enters the Component's bounds.
isDragExit()booltrue when a drag leaves the Component's bounds.
isDrop()booltrue when a dragged item is dropped on the Component.
isMove()booltrue when the pointer moved over the Component with no button held. Only delivered to "MouseMoveEvent" / sendMouseMoveEvents handlers.

KeyEvent


A KeyEvent is passed to your script when a keyboard key is pressed while a Component is focused. Handle one by writing event <Name>(KeyEvent keyEvent) { ... }, where <Name> matches the event name set in Figma.

Feature not yet end-to-end verified

In the current build, KeyEvent handlers don't have a verified delivery path. Every widget type we tested either doesn't intercept keyboard input at the script-reachable level (Label, Animation, Default), or it intercepts at an inner JUCE child (TextEdit's inner editor, Slider's inner slider) which prevents the script's keyPressed hook from firing.

The script-side declaration syntax (event <Name>(KeyEvent keyEvent)) is documented above, and the kdui side ("KeyEvent": "<Name>" property on a Component) compiles cleanly. A worked example will appear here once the source-side delivery path is verified for a specific widget type.

Event names follow the same rule as Parameter names: a Cmajor identifier that is neither a keyword nor a name this reference already uses.

Member Variables

Member VariableTypeDescription
keyCodeintRaw key code. Compare with constants in the Qwerty namespace (e.g. Qwerty::SpaceBar, Qwerty::Enter, Qwerty::UpArrow) or use the helpers below.
modsintBitfield of held modifier keys. Use isCommandDown() / isShiftDown() / isAltDown().
identifierintThe tag of the source Component, set on the widget in the layout, so one shared handler can tell components apart.

Key helpers

FunctionReturnsDescription
getIdentifier()intReturns the event's identifier member variable.
getKeyCode()intReturns the raw key code.
isSpaceBar()booltrue if the event fired from the space bar.
isEnter()booltrue if the event fired from Enter / Return.
isTab()booltrue if the event fired from Tab.
isDelete()booltrue if the event fired from the Delete key.
isBackspace()booltrue if the event fired from Backspace.
isUpArrow()booltrue if the event fired from the up-arrow key.
isDownArrow()booltrue if the event fired from the down-arrow key.
isLeftArrow()booltrue if the event fired from the left-arrow key.
isRightArrow()booltrue if the event fired from the right-arrow key.
isCharacterKey(string character)booltrue if the event matches the printable character passed in (e.g. "a", "$", " ").

Modifier-key helpers

FunctionReturnsDescription
isCommandDown()booltrue if Command / Ctrl was held during the keypress.
isShiftDown()booltrue if Shift was held.
isAltDown()booltrue if Alt / Option was held.

GuiEvent


A GuiEvent is passed to your script when a GUI control with a declared GuiEvent fires - typically used by widgets to send a value plus an identifier. Handle one by writing event <Name>(GuiEvent guiEvent) { ... }, where <Name> matches the event name declared in Figma.

Required UI declaration

Before event <Name>(GuiEvent ...) will compile, the same name must be declared in your Figma export. Add a "GuiEvent": "<Name>" property to a Component in your kdui. Without the declaration, the script compiler reports Event handler '<Name>' does not match an event input.

Event names follow the same rule as Parameter names: a Cmajor identifier that is neither a keyword nor a name this reference already uses.

identifier is there so one handler can tell several Components apart, and it only carries a value when a script tags the Component with sendGuiEvents(component, identifier). Components declared through the Figma property alone report 0.

For a Menu, value is the selected item's own value, which is not always its position. Items defined in Figma are numbered from 1 in list order, so there the two match. Items added from a script with addItem(name, value) report whatever value you gave them.

Example: React to a menu selection

// Clears a menu, populates new items, and logs the selected item's value
// (Assumes a Menu named "MyMenu" in your kdui, with property "GuiEvent" set to "MenuChoice".)
event initialize()
{
    setLogEnabled(true);       // Without this, debug.log() output is silent

    Component menu = getComponent("MyMenu");
    menu.clearItems();          // drop the items defined in Figma first
    menu.addItem("Alpha", 100);
    menu.addItem("Beta", 250);
}

event MenuChoice(GuiEvent guiEvent)
{
    debug.log("Menu item value:", int(guiEvent.getValue()));   // 100 or 250, not 1 or 2
}

Member Variables

Member VariableTypeDescription
valuefloatThe value carried by the event.
identifierintThe tag of the source Component: the number passed to sendGuiEvents(identifier), or the identifier set on the widget in the layout, so one shared handler can tell components apart.

Functions

FunctionReturnsDescription
getValue()floatReturns the event's value member variable.
getIdentifier()intReturns the event's identifier member variable.

KeyRange


A KeyRange describes a span of MIDI notes with a name, colour, and tooltip - used to highlight regions of the GUI piano. There are two kinds of range a script can work with:

  • Script-drawn ranges - construct a KeyRange, then addKeyRange() draws it and removeKeyRange() / clearKeyRanges() take it down. These are transient overlays owned by the script (matched by name); they are cleared on every recompile and never saved with the instrument.
  • Ranges authored in the KEY RANGES module (Setup page) - showKeyRange() / hideKeyRange() toggle the visibility of an existing range whose display name matches the KeyRange.name you pass (every match, at instrument and articulation scope). Only name is read; the other members are ignored. The per-articulation mapped range (the drawn-on-demand span of every note the articulation's zones cover) answers to the name "Playable Range", so a script can hide or show it the same way.
Two different jobs

addKeyRange() creates a new highlight from your KeyRange, colour and all. removeKeyRange() and clearKeyRanges() manage the ranges you made this way.

showKeyRange() and hideKeyRange() do something else entirely: they toggle the visibility of a range already authored in your instrument, matched by name. Every other member variable is ignored, so calling showKeyRange() on a range your UI doesn't already contain does nothing at all.

Example: Highlight keys C3 to B3 on startup

event initialize()
{
    KeyRange octave3;
    octave3.startNote = 60;          // C3
    octave3.endNote = 71;            // B3
    octave3.name = "Octave 3";
    octave3.colour = colours::cornflowerblue;
    octave3.tooltip = "Middle C through B above";

    addKeyRange(octave3);          // script-drawn overlay

    KeyRange mapped;
    mapped.name = "Playable Range";
    hideKeyRange(mapped);           // hide every articulation's mapped range
}

Member Variables

Member VariableTypeDescription
startNoteintFirst MIDI note in the range (inclusive). Range: 0-127.
endNoteintLast MIDI note in the range (inclusive). Range: 0-127.
namestringDisplay name shown on or near the highlighted region.
colourColourHighlight colour shown on the GUI piano. Build with a colours:: constructor or use a named constant (e.g. colours::orange).
tooltipstringTooltip text shown when the user hovers over the highlighted region.

Functions

Highlight regions of the GUI piano. All of these are also available on the Keyboard struct returned by getKeyboard().

FunctionReturnsDescription
addKeyRange(KeyRange range)voidDraws a script-owned range on the GUI piano, on top of the ranges authored in your instrument (keyed by range.name; adding the same name again replaces it).
removeKeyRange(KeyRange range)voidRemoves the script-owned range with this name.
clearKeyRanges()voidRemoves every script-owned range. Ranges authored in your instrument are left alone.
showKeyRange(KeyRange range)voidMakes every KEY RANGES-module range whose display name equals range.name visible in PLAY mode; every other member variable is ignored, and nothing happens if no authored range has that name. "Playable Range" targets each articulation's mapped range. Also available as show(KeyRange). To create a range from a script, use addKeyRange().
hideKeyRange(KeyRange range)voidThe opposite of showKeyRange(). Also available as hide(KeyRange). Both are recorded in the instrument (they survive a save), so prefer addKeyRange() for transient highlights.
setKeyHeld(int note, bool held)voidPaints a key as held on the GUI piano without sounding it - e.g. to mirror a keyswitch from event CurrentArticulation, since keyswitch keys are consumed before noteOn and never reach the script.
clearHeldKeys()voidClears every key painted by setKeyHeld().
clearPlayableRanges()voidRemoves every mapped-range highlight shown via a container's showPlayableRange() (all Articulations, Variations, and Groups at once). Distinct from clearKeyRanges(), which clears script-drawn KeyRange overlays.
clearAllKeyRanges()voidReserved - not currently honoured by KODA (the event is ignored). Use clearKeyRanges() and hideKeyRange().
setPlayableRange(int startNote, int endNote[, Colour colour])voidReserved - not currently honoured by KODA (the event is ignored). The playable span is derived from the mapped zones; see Keyboard highlight.

Pattern


A Pattern is a note sequencer that lives in your script: fill it with NoteData events placed at beat positions, give it a length in beats, and it plays them back - once, or looping. Everything about a Pattern is musical time: positions, the loop length, and note gates are all beats, converted to samples against the live host tempo as the notes fire. A Pattern follows the host's tempo, not its position: change the DAW tempo mid-loop and the pattern follows, with no reference tempo to declare anywhere, but it counts its beats from when you start it, whether or not the transport is playing. To play one in time with the song, see Running free or in time with the song.

Declare Patterns at the top level of the script (they're big - see Large object scope), and give each one its per-block pulse by calling update() from event process(). That call is the one piece of wiring every Pattern needs: a script that declares a Pattern and never calls update() on one gets a warning when it compiles. Call it once per block, too: each call advances the Pattern by a block, so two calls play it at double speed.

The smallest useful Pattern is a one-note repeater - hold a key and it retriggers every beat:

Pattern repeater;

event initialize() { setIgnoreNoteOns(true); }

event noteOn (NoteData note)
{
    repeater.setTarget(getCurrentArticulation());   // route fired notes to the current articulation
    repeater.repeat(note, 1.0);                      // loop the held note every beat
}

event noteOff (NoteData note) { repeater.stop(); }

event process() { repeater.update(); }

Building

Add events with addNote() - each call copies the NoteData you pass in, so one NoteData variable can be reused to lay down every step (see the melody example below). A Pattern holds up to 1024 events; additions beyond that are ignored and addNote returns -1.

Read at fire time

A Pattern bakes nothing in when you add notes. The length, looping flag, transposition and target are consulted at the moment each note fires, so the order you call setters in doesn't matter - and you can change any of them while the pattern is playing. The melody example below re-keys a running loop by calling setTransposition() from noteOn.

This is also why building a pattern in initialize() is safe even though the tempo still reads 0 there: beats are stored as beats and only become samples during playback.

FunctionReturnsDescription
addNote(NoteData note, float64 beat) int Adds a copy of the note at a beat position. Valid positions run from 0 up to (but not including) the pattern length - an event at or beyond the length never fires. Returns the index the note landed at (see Editing in place), or -1 when the pattern is full.
addNote(NoteData note, float64 beat, float64 lengthInBeats) int As above, and releases the note lengthInBeats beats after it starts. The gate is converted to time against the tempo in effect when the note fires, and it lands even when it falls past the loop wrap. Returns the index as above.
addNote(NoteData note) int Adds the note at beat 0. Returns the index as above.
setLengthInBeats(float64 lengthInBeats) void Sets the pattern length - the loop point - in beats.
setLooping(bool looping) void true = wrap at the pattern length and keep going. false = play once, then stop (releasing anything still sounding).
setTransposition(int semitones) void Transposes every note the pattern fires. Applied at fire time - change it mid-loop to re-key what's already queued.
setTarget(Articulation target) void Routes every fired note to the given container. Also accepts a Variation or Group. Set it once, before or after adding notes. Without a target, each note keeps the routing it was created with (e.g. from createNoteData()). A handle that names nothing leaves the target as it was.
clearTarget() void Removes the target; fired notes fall back to their own routing.
setInitialOffset(int offsetSamples) void Extra delay in audio samples added to every fired note.
clear() void Removes all events and rewinds to beat 0. Length, looping, target and transposition are kept.
Three kinds of note length

A note inside a pattern can get its length three ways. addNote's lengthInBeats argument is musical and keeps tracking tempo - the gate is resolved when the note fires, every time it fires. setLengthBeats() on the NoteData is musical but a snapshot - converted to absolute time at the moment you call it. setLengthMS() / setLengthSeconds() are absolute wall-clock lengths - a fixed 200 ms pluck stays 200 ms at any tempo.

The pattern never touches a length the note already carries - it only writes one when you pass addNote a gate argument.

Editing in place

A pattern doesn't have to be rebuilt to change one step. Every note has an index - its position in beat order, 0 up to getNumNotes() - 1 - which is the order the notes fire in and, for a pattern laid down step by step, the order you added them in. addNote() returns the index its note landed at, so you can keep it. Read a note back with getNote(), change the copy, and write it back with setNote(); move it with setBeat(); drop it with removeNote().

When an index changes

An index is stable until a beat changes or a note is removed. setBeat() re-sorts the pattern and returns the note's new index (a note moved onto a beat that already has notes lands after them), and removeNote() moves every later note down by one. Nothing here touches playback: an edit is picked up by the next update(), and a note that has already fired keeps its own length. Out-of-range indices are ignored by the setters; the getters return a blank NoteData or -1.

FunctionReturnsDescription
getNumNotes() int How many notes the pattern holds.
hasNote(int index) bool true when index names a note.
getNote(int index) NoteData A copy of the note at index. Edit the copy and write it back with setNote().
setNote(int index, NoteData note) void Replaces the note at index, keeping its beat and length.
getBeat(int index) float64 The note's beat position.
setBeat(int index, float64 beat) int Moves the note to another beat and returns its new index.
getNoteLength(int index) float64 The note's length in beats, as passed to addNote; 0 when it has none.
setNoteLength(int index, float64 lengthInBeats) void Sets the note's length in beats. 0 removes it, so the note keeps whatever length it carries itself.
removeNote(int index) void Removes the note; every later note moves down one index.

A step sequencer that edits one step from the GUI while it loops. The steps go in beat order, so a step's index is its step number:

Pattern steps;

const int kNumSteps = 8;

event initialize()
{
    setIgnoreNoteOns(true);

    var art = getCurrentArticulation();
    NoteData step = art.createNoteData();
    step.setMidiVelocity(100);
    step.setNoteNumber(60);

    for (int i = 0; i < kNumSteps; i++)
        steps.addNote(step, float64(i) * 0.5, 0.25);   // eighth-note grid, quarter-beat gate

    steps.setLengthInBeats(4);
    steps.setLooping(true);
}

event noteOn (NoteData note)  { steps.start(); }
event noteOff (NoteData note) { steps.stop(); }

// A step's pitch changed on the GUI: the step number rides in the identifier,
// the new note number in the value. Only that step changes; the loop keeps running.
event handleGuiEvent (GuiEvent e)
{
    NoteData n = steps.getNote(e.getIdentifier());
    n.setNoteNumber(int(e.getValue()));
    steps.setNote(e.getIdentifier(), n);
}

event process() { steps.update(); }

Playback

FunctionReturnsDescription
start() void Rewinds to beat 0 and starts playback. Beat 0 is the moment of the event that calls it: in noteOn and noteOff, the note's own sample, so the first hit plays with the key.
start(int initialOffsetSamples) void As above, with an extra sample delay applied to every fired note. start(getNextBeat()) in noteOn puts the first hit on the song's next beat: see Running free or in time with the song.
startLooping(float64 lengthInBeats) void setLengthInBeats() + setLooping(true) + start() in one call.
repeat(NoteData note, float64 lengthInBeats) void Clears the pattern, adds the note at beat 0, and starts looping every lengthInBeats beats - the one-line note repeater.
repeat(NoteData note, float64 lengthInBeats, float64 gateInBeats) void As above, releasing each hit gateInBeats beats after it starts.
stop() void Stops playback, rewinds, and sends a note-off for everything the pattern may have started.
update() void The per-block pulse - call it from event process(). Fires the events that fall inside the current audio block, sample-accurately; does nothing while the pattern is inactive.
isActive() bool true between start() and stop(). A non-looping pattern stops itself when it reaches the end.
isLooping() bool Returns the looping flag.
getLengthInBeats() float64 Returns the pattern length in beats.
getPlayPositionBeats() float64 Current playback position in beats - handy for driving UI.
Events past the loop point

An event at or beyond the pattern length stays in the queue but never fires. If you shrink the length below an existing event's position, that step simply goes silent until the length grows past it again - nothing is removed.

Running free or in time with the song

A Pattern runs on its own clock: it is at beat 0 when you call start() and counts beats at the host's tempo from there. It never reads the host's position, so it plays the same whether the transport is playing or stopped. That suits a player trying a pattern out with the transport stopped: it starts the moment they press the key.

To play in time with the song instead, put the first hit on the song's next beat or bar. In noteOn, getNextBeat() and getNextBar() count from the note's own sample, as start() does, so start(getNextBeat()) lands the first hit on the beat and the rest follow the tempo from there. Check getIsPlaying() first: with the transport stopped, those helpers count from wherever the playhead is parked, so every note would wait the same arbitrary time. One script can do both:

Pattern repeater;

event initialize() { setIgnoreNoteOns(true); }

event noteOn (NoteData note)
{
    repeater.setTarget(getCurrentArticulation());
    repeater.clear();
    repeater.addNote(note, 0.0);
    repeater.setLengthInBeats(1.0);
    repeater.setLooping(true);

    if (getIsPlaying())
        repeater.start(getNextBeat());   // in time with the song: the first hit on the next beat
    else
        repeater.start();                // transport stopped: the first hit with the key
}

event noteOff (NoteData note) { repeater.stop(); }

event process() { repeater.update(); }

A Pattern started this way stays in time when the tempo changes, but it does not follow the playhead: when the user moves it, or the DAW loops back, the Pattern carries on from where it was. To line it up again, stop() it and start it the same way, from event transportStarted() for instance. For a grid finer than a beat, work the offset out from the position: with float64 ppq = getPpqPosition();, the samples to the next 16th note are int((ceil(ppq * 4.0) / 4.0 - ppq) * getBeat() + 0.5).

Example: A melody sequencer

One NoteData lays down every step, and the pattern re-keys itself to whatever key is held. Because positions and gates are beats, this is safe to build in initialize() and rescales to any host tempo:

Pattern melody;

const int kRoot = 60;   // the melody is written around middle C

event initialize()
{
    setIgnoreNoteOns(true);

    var art = getCurrentArticulation();
    NoteData step = art.createNoteData();   // a blank note, routed to this articulation
    step.setMidiVelocity(100);

    // note number            position (beats)  length (beats)
    step.setNoteNumber(60);  melody.addNote(step, 0, 0.5);
    step.setNoteNumber(64);  melody.addNote(step, 1, 0.5);
    step.setNoteNumber(67);  melody.addNote(step, 2, 0.5);
    step.setNoteNumber(64);  melody.addNote(step, 3, 0.5);

    melody.setLengthInBeats(4);
    melody.setLooping(true);
}

event noteOn (NoteData note)
{
    melody.setTransposition(note.getNoteNumber() - kRoot);   // play it in the held key
    melody.start();
}

event noteOff (NoteData note) { melody.stop(); }

event process() { melody.update(); }

Explicit note-off events are also possible for cases where an off shouldn't be tied to its own on: add a note with setIsNoteOff(true) at any beat before the pattern length and it fires as a note-off. For ordinary melodic gates, prefer the length argument - it stays correct across the loop wrap.

Saving & Restoring State


Mark a variable persist and KODA keeps its value. It is written into the instrument when you save, restored when you load, and carried across a hot reload while you are working on the script.

persist int   playCount;
persist float lastVelocity = 0.5f;

persist
{
    float[8] stepLevels;
    Pattern  phrase;
}

Both forms declare ordinary variables. The block is a grouping, not a scope, so what you declare inside is reachable from anywhere in the script exactly as if you had written it at the top level. You can use as many blocks as you like and mix them with single declarations.

The script editor tints persisted lines. That is worth glancing at, because everything you mark goes into every save file: a Pattern is not small, and a large array swept into a block by accident is a large blob in every instrument you save from then on.

What you can persist

Anything with a fixed size and a spelled-out type: numbers, bool, structs (KODA's or your own), fixed-size arrays and vectors of those. An array can take its size from your own constants. The compiler tells you at your own line when something cannot be kept.

struct Step { int note; float level; }
const int kSteps = 16;

persist Step[kSteps] steps;
persist float[kSteps * 2] levels;
Not allowedWhy
persist const x A persisted variable has to be writable to restore into.
persist let x = 1; and persist var x = 1; The type has to be written out; it is part of the saved layout.
persist string name; A Cmajor string is a handle that only means anything inside one session.
persist int[] values; A slice refers to another array rather than holding anything.
A struct with a string member The same reason as persist string: the string doesn't survive the session.
persist wrap<8> step; and clamp<> Persist an int, and wrap or clamp it where you read it.
persist inside a function or another block Persisted variables live at the top level of the script.

Restoring happens before initialize()

The restore lands first, so initialize() runs with the values that came back. That order is what makes the feature useful, and also the one thing that catches people out: if initialize() assigns a persisted variable unconditionally, it overwrites what was just restored.

wasStateRestored() is how you tell the two apart.

persist float phase = 0.0f;

event initialize()
{
    if (! wasStateRestored())
        phase = 0.0f;          // a genuinely fresh start
}

It reports false on a first load, and whenever nothing at all came back, so the guarded branch runs exactly when the script needs to set itself up from scratch.

To ask about one variable, pass its name. wasStateRestored("steps") is false for a variable added since the session was saved, and for one whose saved value no longer fits (see below), even when everything else came back. Guard each variable that initialize() sets up this way, and a variable you add in an update gets its setup in sessions saved before it existed. A name that is not one of your persist variables is a warning when the script compiles.

persist float phase = 0.0f;
persist int[16] steps;   // added in version 2

event initialize()
{
    if (! wasStateRestored("steps"))
        resetSteps();   // also runs in a session saved by version 1
}

When you edit the script

Editing is the point of a hot reload, so the saved values and the variables you now declare will not always line up. Each variable is reconciled on its own:

  • Unchanged - the saved value comes back.
  • Newly added - there is nothing saved for it, so it keeps the initializer you gave it. This is not an error and does not stop anything else restoring.
  • Deleted - the saved value is ignored.
  • Changed type - numbers convert between widths, so float to float64 or int to int64 carries.
  • Resized array - the elements that still fit come back.
  • A struct you changed - its untouched fields still come back; only what genuinely no longer fits is lost.
A value that no longer fits costs that variable alone

If something was saved that can no longer be reconciled at all, that variable keeps its initializer and everything else still comes back. wasStateRestored("name") is false for it, and the console prints a warning naming it. A struct that lost a field this way keeps its other fields but also reads as not restored, so a guarded setup puts the whole struct back in order. A restore whose layout moved without losing anything just prints a line naming what is new.

Renaming a variable reads as deleting one and adding another, so its value does not follow the new name.

Snapshots and snapshotLoaded()

A player can save a snapshot of an instrument and load it again later. Every snapshot carries the instrument's Parameter values and every script's persist variables; an instrument whose developer chose the Full scope also carries its mix, envelopes, effects and modulation settings. Loading a snapshot sets those values on the running instrument. It does not recompile your script, and initialize() does not run again.

Your script sees a load in this order, all in the next audio block:

  1. An event for each Parameter the snapshot changed, exactly as if the player had moved it.
  2. Your persist variables take the snapshot's values. wasStateRestored() and wasStateRestored("name") now describe this load.
  3. event snapshotLoaded() runs.

A snapshot that loads before your script has finished compiling (the instrument has just opened, or the last compile failed) is held for the compile, and so is one that arrives in the moment a hot reload swaps your program in. Its values are in place before initialize() runs, wasStateRestored() returns true there, and snapshotLoaded() does not run, since initialize() does.

snapshotLoaded() runs on every load, in every script of the instrument, even when your script persists nothing - it is the place to bring anything you derive from Parameters or persisted values back in line, such as labels or a drawn display:

persist int selectedPage;

void refreshDisplay()
{
    // show selectedPage and the current Parameter values
}

event initialize()     { refreshDisplay(); }
event snapshotLoaded() { refreshDisplay(); }

Your persist variables are reconciled as they are after an edit (above), with one difference: a variable the snapshot did not save - one you added since - keeps the value it holds right now, because the script is already running. A value that no longer fits costs that variable alone: it keeps its current value, the others take the snapshot's, the console names it, and snapshotLoaded() still runs.

A snapshot load is one undo step. Undoing it puts your persist variables back to the values they held before the load, along with the Parameters, and redoing it applies the snapshot's values again. Each time, snapshotLoaded() runs once more after your variables change, so the same refresh covers undo and redo.

Advanced Topics


You can script KODA without anything in this section. These topics start to matter as scripts grow - more data, code you want to reuse across instruments, and the failure modes that only show up at scale. Each topic stands alone, so dip in as needed.

Passing by value vs reference

Assigning a value or passing it to a function makes a copy - structs and arrays included. Changes to the copy never reach the original, which is also why editing a NoteData after starting the note has no effect (see Note vs NoteData).

To let a function change what the caller passed in, mark the parameter with &:

// ✗ By value - boost() changes its own copy
event initialize() { setLogEnabled(true); }

void boost (float value) { value += 0.2f; }

event noteOn (NoteData note)
{
    float v = 0.5f;
    boost(v);
    debug.log("v", v);   // still 0.5
}
// ✓ By reference - boost() changes the caller's v
event initialize() { setLogEnabled(true); }

void boost (float& value) { value += 0.2f; }

event noteOn (NoteData note)
{
    float v = 0.5f;
    boost(v);
    debug.log("v", v);   // now 0.7
}

& works in one place only: parameters being passed into a function. A function cannot return a reference - returning always hands back a copy - and there are no reference variables. So a function that should give the caller a changed value either returns the copy for the caller to assign, or writes into a & parameter as above. Copying is fine for small values; for big ones, see the next topic.

Large object scope

Declare big arrays and structs at the top level of the script, not inside functions. Top-level variables live for the lifetime of the instrument and are shared by every function; function locals are copied around and limited in size. Pass a big object to your own helper with & so the helper works on it in place:

// A big lookup table: declared at the top level, filled in place through a & parameter
float[1024] table;                     // top level - lives with the instrument

void fill (float[1024]& t)             // & - fills the caller's table, no copy
{
    for (wrap<1024> i)
        t[i] = float(i) / 1023.0f;
}

event initialize()
{
    setLogEnabled(true);
    fill(table);
    debug.log("table.at(512)", table.at(512));   // 0.500489
}

Index lookup tables with wrap<N> or .at() as described in Cmajor patterns you'll see.

Generics (functions, namespaces)

A generic function is written once and works for every type you call it with - the compiler builds a version per type. Put <Type> after the name, then use Type as a placeholder. The built-in limit() works this way, which is why it accepts int and float alike.

// One generic function serving two types: int and float
event initialize() { setLogEnabled(true); }

Type highest<Type> (Type a, Type b)
{
    static_assert (Type.isPrimitive, "highest() needs a numeric type");
    return a > b ? a : b;
}

event noteOn (NoteData note)
{
    debug.log("int", highest(3, 7));                        // 7
    debug.log("float", highest(note.getVelocity(), 0.5f));   // at least 0.5
}

static_assert is a check that runs at compile time: if its condition is false, compilation stops and its message becomes the error. Here it's optional but worth the keystrokes - without it, calling the function with a type it can't handle fails with a confusing compiler error instead of your own message. Namespaces can be parameterised the same way - see the Cmajor language documentation.

Designing your own structs

A struct groups related values under one name, and every member variable starts at zero - there are no member initialisers, so a struct needs no constructor. If a member should start at some other value, set it in initialize(). Functions declared inside the struct refer to it as this, and calling them follows the same two spellings as everything else (see dot or no dot).

If you're coming from an OOP language, a struct is the closest thing to a class, with one big difference up front: there is no inheritance. A struct cannot extend another, so build bigger structs by composition - one struct as a member of the next. Otherwise the shape is familiar: member variables plus the functions that work on them, called with dot syntax. Two smaller differences: a struct is a plain value - assigning or passing one copies it (see Passing by value vs reference), where a class object in most languages is shared by reference - and there is no constructor, so every struct starts zeroed, every time.

// A struct that accumulates a running average across noteOn calls
struct VelocityStats
{
    float total;
    int   count;

    void  add (float v) { this.total += v; this.count++; }
    float average()     { return this.count == 0 ? 0.0f : this.total / float(this.count); }
}

VelocityStats stats;                    // top level, zero-initialised

event initialize() { setLogEnabled(true); }

event noteOn (NoteData note)
{
    stats.add(note.getVelocity());
    debug.log("average velocity", stats.average());
}

Using Constants (properties) and parameters to make templates

Constants let one script serve many instruments: instead of hard-coding numbers, the script reads named values authored per-instrument in the GROUP VARIABLES section of the Setup tab. The script side calls them properties - the property getters on Articulation, Variation, and Group read them by name. Despite the name, a Constant has nothing to do with the const keyword: it is constant from the script's point of view because only the instrument author can change it, and your script reads it into an ordinary variable.

A name that isn't authored on the instrument reads as "", 0, or false rather than erroring. That silence is what lets one script load everywhere, but it means a template should check and log its fallbacks, so an instrument builder can see what's missing. Read Constants once in initialize() and keep the values in top-level variables:

// Read a per-instrument Constant (property) with a logged fallback when it's missing
int transposeSemitones;                 // read once at startup

event initialize()
{
    setLogEnabled(true);

    Articulation art = getCurrentArticulation();

    if (art.getProperty("Transpose") == "")
        debug.log("No 'Transpose' Constant - using 0");

    transposeSemitones = art.getIntProperty("Transpose");
    debug.log("transposeSemitones", transposeSemitones);
}

Avoiding infinite loops

Everything your script does - noteOn, process, every event - runs inside KODA's audio engine, where there is no room to wait: a loop that never exits would stall the engine itself. KODA cuts one short before that happens (see below), but a loop that was cut short has not done its job, so a runaway is still a bug you have to fix. The compiler rejects loops it can prove never exit (a bare loop {} fails with "The function contains at least one infinite loop"), but it cannot catch a loop whose exit depends on a value that never arrives. Floats are the classic trap: stepping by 0.1f never lands exactly on 1.0f, so a != test stays true forever.

// ✗ Compiles cleanly, then runs away on the first note
event noteOn (NoteData note)
{
    float t = 0.0f;
    while (t != 1.0f)      // never exactly 1.0
        t += 0.1f;
}
// ✓ Bounded by construction
event noteOn (NoteData note)
{
    float t = 0.0f;
    loop (10)               // runs exactly 10 times
        t += 0.1f;
}

Prefer loops that are bounded by construction: the counted loop (n) form, for loops with fixed bounds, and < comparisons rather than != when the condition involves a float.

KODA stops runaway loops

A loop that never ends no longer freezes KODA. The loops you write share a budget of 20,000 steps per block of audio, spread across every handler that runs in that block; once it is spent, each of them stops where it stands and the console names the line, with the exact limit in the message. Calls into KODA's own functions do not count against it, so something like getHeldNotes() or stopAllNotes() costs you nothing however much work it does internally.

This keeps the audio alive; it does not make the script correct. The loop stopped partway through, so whatever it was in the middle of is left half-done, and the symptoms often surface somewhere else entirely - a note that never starts, a parameter left at the wrong value. Treat the message as a bug to fix, not a limit to work against.

Avoiding NaN

NaN - "not a number" - is what float maths produces when an operation has no answer, like 0.0f / 0.0f or the square root of a negative. It spreads: any arithmetic that touches a NaN yields NaN, and every comparison against NaN is false, so range checks and clamps wave it through, and a != loop condition holding a NaN never exits (see Avoiding infinite loops).

The place scripts usually meet one, or its cousin infinity: dividing by the tempo inside initialize(), before any audio is flowing. getBPM() still reads 0 there, so 60.0 / getBPM() is infinity and 0.0 / getBPM() is NaN. Check the denominator, or the result with isnan() and isinf(), before a value like that reaches a setter:

// Where infinity shows up, and how to stop it before it reaches a setter
event initialize()
{
    setLogEnabled(true);
    debug.log("beat seconds", 60.0 / getBPM());   // logs inf - no tempo yet
}

event noteOn (NoteData note)
{
    float64 bpm = getBPM();

    if (bpm <= 0.0)
        return;                                       // check the denominator before dividing

    debug.log("beat seconds", 60.0 / bpm);         // real value, e.g. 0.5
}

An unguarded NaN fails silently: fed into setInstrumentGainLinear, the instrument simply goes quiet - no error, no log message, just no sound until the script is fixed and the instrument reloaded. If a value could ever come from a division, check the denominator or check the result with isnan() (and isinf() for its cousin) before using it.