FabGL2 2.0.0
Graphics, audio, GUI and retro-computing library for the ESP32 (ESP-IDF)
Loading...
Searching...
No Matches
DrumMachine

FabGL Drum: a sample based drum machine in the style of the classic early eighties drum machines, the LinnDrum and its modern recreation, the Behringer LM Drum. 16 instruments with level faders, tuning and decay, a 32 step sequencer with three velocities and swing, real time recording with quantization, pattern chaining and song mode. It comes with 8 factory kits (a recorded acoustic kit and kits in the style of the TR-808, TR-909, CR-78, LM-1, LinnDrum LM-2 and DMX) and 32 factory patterns; user sounds (WAV files) are loaded from the micro SD card.

Screenshots

Main screen: faders and pads of the 16 instruments, the step grid of pattern 01 ROCK 1 and the FD-16 kit
Playing: the highlighted column follows the sequencer step
LOAD WAV: loads a user sound, or a whole kit folder, from the SD card

Screen

A black panel with wooden end cheeks, cream legends and red seven segment displays:

  • Header: the KIT selector (under the logo, the arrows or F4 select the factory kit). The displays show the playing pattern, the tempo (BPM) and the playing step. Below them a status line: song position, queued pattern, REC, ERASE. Knobs: TEMPO (30-300 BPM) and SWING (50-75 %) of the selected pattern, master VOLUME. Transport pads: PLAY (green led while playing), STOP, REC (red led while recording)
  • Mixer: one strip for each instrument: a level fader and a pad. Clicking a pad plays the instrument and selects it (VOICE panel). Pads light up when their instrument plays. Every pad shows its key (1...8, Q...I, and SPC, F1, F2, F3 on the transport and mode pads)
  • Step grid: one row for each instrument, 16 steps (a page: 1-16 or 17-32). Empty cells are gray (every other beat a darker shade), hits are dark red (soft), red (normal) or orange (accent). The playing step is framed in yellow. Steps after the pattern length are black. The row labels show the selected instrument, the activity (orange mark) and the muted instruments (dim label, red mark)
  • Pattern: number and name of the selected pattern (a * follows the name when it has been changed), the arrow buttons select the previous / next pattern. Buttons: SAVE, CLEAR (removes all hits), SONG (song editor), INIT (factory reset)
  • Length: number of steps of the pattern (1-32). Steps: shows steps 1-16 or 17-32 in the grid
  • METRO: metronome (a click on every beat, accented on the first step). SONG: song mode (plays the song instead of the selected pattern)
  • Voice: the selected instrument, its sound (the kit name or the user file name, duration), LOAD WAV and KIT SND (back to the sound of the selected kit), TUNE (-12..+12 semitones) and DECAY (FULL = the whole sound, lower values fade it out faster)

Knobs: drag up or down with the mouse button pressed, or use the mouse wheel; double click restores the initial value. Faders: drag the cap or click the slot, mouse wheel; double click restores the initial level.

Grid editing

Mouse Action
Click an empty cell Adds a normal hit. Drag with the button pressed to add more hits
Click a hit Removes it. Drag to remove more hits
Right click or wheel on a hit Changes its velocity: soft, normal, accent
Click an instrument name Selects the instrument and plays it
Right click an instrument name Mutes / unmutes the instrument (the sequencer skips it, pads still play it)

Keys

Key Action
1 ... 8 Pads 1-8: BASS, SNARE, RIM, CLAPS, CLOSED HAT, OPEN HAT, CRASH, RIDE
Q W E R T Y U I Pads 9-16: HI TOM, MID TOM, LO TOM, HI CONGA, LO CONGA, COWBELL, TAMB, CABASA
SHIFT / CTRL + pad key Accented / soft hit
SPACE Play / stop
F1 Record on / off
F2 Song mode on / off
F3 Metronome on / off
F4 Next factory kit
PGUP / PGDN Previous / next pattern
LEFT / RIGHT Steps 1-16 / 17-32
+ / - Tempo
BACKSPACE + pad key While recording: erases the instrument while the playhead passes (keep both keys pressed)

Playing and recording

PLAY starts the selected pattern from the first step (in song mode: the song from the first entry). Selecting another pattern while playing queues it: it starts at the end of the current pattern (the status line shows NEXT nn), so patterns can be chained live, like on the hardware drum machines.

Record mode (REC or F1): while playing, every pad hit (mouse or keyboard) is written in the pattern at the nearest 1/16 step (quantization) and played immediately; a hit recorded just before a step is not played twice. Turn on the metronome to hear the beats. Hold BACKSPACE and a pad key to erase that instrument as the playhead passes. The grid follows the recording.

Swing delays the even 1/16 notes (the second and the fourth of every beat): 50 % is straight, 66 % is a triplet feel. Tempo and swing are stored in each pattern. The shuffle patterns are programmed in 1/8 notes at half tempo.

The hi-hats are a choke group: the closed hi-hat stops the open hi-hat, like on a real hi-hat.

Patterns and kit settings

64 pattern slots: the first 32 contain the factory patterns, the others are empty. Changes are kept in memory while the application runs (a * marks the changed patterns) and are stored by SAVE:

  • SAVE opens a dialog: choose the destination slot (by default the current one) and type the name (up to 15 characters, stored in upper case). Saving to another slot copies the pattern there, and the original pattern goes back to its stored version. SAVE also stores the kit settings: levels, tuning, decay, mutes, master volume, metronome and the user sounds.
  • INIT restores the factory patterns, the factory song and the factory kit (the stored data is erased).

Everything is stored in the NVS flash partition (namespace drums) and survives power off. Erasing the flash (idf.py erase-flash) also restores the factory data.

# Patterns
01-05 ROCK 1, ROCK 2, ROCK RIDE, HARD ROCK, ROCK FILL
06-08 POP 1, POP 2, BALLAD
09-13 DISCO 1, DISCO 2, FUNK 1, FUNK 2, FUNK 3
14-16 NEW WAVE, SYNTH POP, ELECTRO
17-19 HIP HOP 1, HIP HOP 2, R&B
20-22 SHUFFLE, BLUES, REGGAE
23-27 BOSSA NOVA, SAMBA, SALSA, CHA CHA, LATIN PERC
28-30 MOTOWN, MARCH, DANCE
31-32 TOM FILL, SNARE ROLL

The factory patterns are defined as text in main/patterns.h (one string per instrument, . = no hit, - = soft, x = normal, X = accent).

Song

A song is a list of up to 64 patterns. SONG opens the editor: select a pattern with the arrows and INSERT it before the selected entry, REPLACE the selected entry or DELETE it; OK stores the song. In song mode (SONG pad or F2) PLAY plays the song once from the beginning; the selected pattern follows the song, so the grid shows the playing pattern. The factory song plays ROCK 1 (3 times), ROCK FILL, ROCK 2 (3 times), TOM FILL, ROCK RIDE (3 times) and SNARE ROLL.

Sounds

Every factory kit has the 16 instruments of the classic kit: bass drum, snare, rimshot, claps, closed and open hi-hat, crash, ride, three toms, two congas, cowbell, tambourine and cabasa. Where a machine didn't have an instrument, the kit has the closest sound of that machine (for example maracas and claves on the TR-808).

# Kit Sounds
1 FD-16 Synthesized, in the style of the early eighties sampling drum machines (LinnDrum, LM Drum)
2 ACOUSTIC Recorded acoustic kit: close and overhead microphones mixed, auxiliary percussion
3 TR-808 Synthesized like the Roland TR-808 analog circuits: long bass drum, snappy snare, six oscillator metallic hi-hats and cymbal, cowbell, claps, maracas (TAMB), claves (CABASA)
4 TR-909 Synthesized analog drums like the Roland TR-909 (bass drum with a fast pitch sweep, noisy snare), hi-hats and cymbals sampled at 6 bit like on the original
5 CR-78 Synthesized like the Roland CompuRhythm CR-78: short soft drums, bongos and conga on the toms, cowbell, tambourine, maracas
6 LM-1 Recorded drums processed in the style of the Linn LM-1: tuned, tight, band limited, deep toms, big claps
7 LM-2 Recorded drums processed in the style of the LinnDrum LM-2: snare with gated room, full cymbals
8 DMX Recorded drums processed in the style of the Oberheim DMX: compressed and saturated, gated snare

The kits only recall those machines: no sample of the original machines is used. The selected kit is stored by SAVE; the instruments with a user sound keep it when the kit changes (KIT SND restores the sound of the kit).

The kits (main/kit.h) are generated by tools/make_kit.py and stored at 22050 Hz as 16 bit samples (3 MB of flash: the example has its own partition table, partitions.csv, with a 3.9 MB app partition on the 4 MB flash; flashing takes about 80 seconds). The recorded kits use samples of Virtuosity Drums by Versilian Studios and Karoryfer Samples (CC0 1.0, public domain). To change the kits: tools/fetch_samples.sh <dir> downloads the 31 files used (12 MB), python3 tools/make_kit.py --samples <dir> writes main/kit.h (it needs sox; --wav <dir> also writes every sound as a WAV file, --kits fd16,tr808 generates only some kits, --mulaw makes 8 bit mu-law kits: half the size, but the quantization noise is audible on the tails).

The drum machine mixes with 16 bit resolution and the sound generator runs the DAC at 352.8 kHz (16 times the sample rate) with a noise shaper: the DAC has only 8 bits, and without it the quiet tails of the sounds get a buzzing distortion at their pitch.

User sounds from the micro SD card

LOAD WAV opens a file browser on the SD card (/sdcard):

  • LOAD SOUND (or double click a file) loads the selected WAV file into the selected instrument
  • LOAD FOLDER AS KIT loads, from the current folder, every file named like an instrument:
Instrument File Instrument File
BASS kick.wav TOM HI tomhi.wav
SNARE snare.wav TOM MID tommid.wav
RIMSHOT rimshot.wav TOM LO tomlo.wav
CLAPS clap.wav CONGA HI congahi.wav
CL HAT closedhat.wav CONGA LO congalo.wav
OP HAT openhat.wav COWBELL cowbell.wav
CRASH crash.wav TAMB tambourine.wav
RIDE ride.wav CABASA cabasa.wav

Instruments without a file keep their sound. Any WAV file works: PCM 8, 16, 24 or 32 bit, 32 bit float, mono or stereo (mixed to mono), any sample rate (converted to 22050 Hz). Sounds are normalized and truncated to 4 seconds. They are loaded into PSRAM when the board has it (without PSRAM only short sounds fit in memory). The file names are stored with the kit settings and the sounds are loaded again at startup (when the SD card is present); KIT SND restores the sound of the selected kit.

What it demonstrates

Hardware

  • VGA output (default pins)
  • Audio output on GPIO25
  • PS/2 keyboard on port 0 and PS/2 mouse on port 1
  • Micro SD card (optional, user sounds). Default connections (TTGO VGA32 slot): MISO = GPIO16 (2 on PICO-D4 boards), MOSI = GPIO17 (12 on PICO-D4), CLK = GPIO14, CS = GPIO13
  • PSRAM (optional, for user sounds longer than a few hundred milliseconds)

Build

See Building the examples.

Source code

Main file of the example, main/DrumMachine.cpp. The complete project is in the examples/VGA/DrumMachine folder.

1/*
2 Created by Fabrizio Di Vittorio (fdivitto2013@gmail.com) - <http://www.fabgl.com>
3 Copyright (c) 2019-2026 Fabrizio Di Vittorio.
4 All rights reserved.
5
6
7* Please contact fdivitto2013@gmail.com if you need a commercial license.
8
9
10* This library and related software is available under GPL v3.
11
12 FabGL is free software: you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation, either version 3 of the License, or
15 (at your option) any later version.
16
17 FabGL is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with FabGL. If not, see <http://www.gnu.org/licenses/>.
24 */
25
26
27/*
28 * FabGL Drum: a sample based drum machine in the style of the classic early eighties drum machines
29 * (LinnDrum and its modern recreation, the Behringer LM Drum): 16 instruments with level faders, tuning and decay,
30 * a 32 step sequencer with three velocities, swing, real time recording with quantization, pattern chaining and
31 * song mode, 32 factory patterns and a factory kit. User sounds (WAV files) are loaded from the micro SD card.
32 *
33 * Keyboard:
34 *
35 * 1 2 3 4 5 6 7 8 : instruments 1..8 (BASS .. RIDE) + SHIFT: accent, + CTRL: soft
36 * Q W E R T Y U I : instruments 9..16 (TOMS .. CABASA)
37 * SPACE : play / stop
38 * F1 : record on / off
39 * F2 : song mode on / off
40 * F3 : metronome on / off
41 * PGUP / PGDN : previous / next pattern (while playing: at the end of the current pattern)
42 * LEFT / RIGHT : steps 1-16 / 17-32
43 * + / - : tempo
44 * BACKSPACE + pad : while recording, erases the instrument while the playhead passes
45 *
46 * Mouse: faders, pads, knobs; grid: click = hit on/off (drag to paint), right click or wheel = velocity,
47 * click on the instrument name = select, right click = mute.
48 *
49 * The sound is produced by fabgl::DrumMachine (16 bit samples, sequencer inside the sound generator). The interface
50 * uses the FabGL controls uiFader, uiPad, uiSegmentDisplay, uiStepGrid, uiKnob, uiStepper, uiTileSelector, themed
51 * by a uiStyle and a custom 16-color palette.
52 */
53
54
55#include <ctype.h>
56#include <string.h>
57#include <stdio.h>
58#include <sys/stat.h>
59
60#include "fabgl.h"
61#include "fabui.h"
62
63#include "kit.h"
64#include "patterns.h"
65
66
67using fabgl::uiStyle;
68using fabgl::uiObject;
69using fabgl::uiWindow;
70using fabgl::iclamp;
71using fabgl::imax;
72
73
74fabgl::VGA16Controller DisplayController;
75fabgl::PS2Controller PS2Controller;
76SoundGenerator soundGenerator(KIT_SAMPLE_RATE, GPIO_AUTO, SoundGenMethod::DAC);
77DrumMachine drums;
78
79
80static constexpr int INSTRUMENTS = DrumMachine::INSTRUMENTS;
81static constexpr int PATTERNS = 64; // pattern slots (factory patterns in the first ones)
82static constexpr int PAGE_STEPS = 16; // steps shown by the grid
83static constexpr char SDCARD_PATH[] = "/sdcard";
84static constexpr int MAX_SAMPLE_LEN = KIT_SAMPLE_RATE * 4; // user sounds: at most 4 seconds
85static constexpr char PREFS_NAMESPACE[] = "drums";
86static constexpr int PREFS_VERSION = 1; // bump when DrumPattern, KitSettings or the song change
87static constexpr int PATH_SIZE = 96;
88
89
90
92// Instruments
93
94
95struct InstrumentDef {
96 char const * name; // grid label and voice panel
97 char const * padText; // pad text (lines separated by \n)
98 char const * file; // file name of the kit folders (<file>.wav)
99 uint8_t choke; // choke group
100 int8_t level; // default fader level
101};
102
103
104static const InstrumentDef Instruments[INSTRUMENTS] = {
105 { "BASS", "BASS", "kick", 0, 90 },
106 { "SNARE", "SNARE", "snare", 0, 85 },
107 { "RIMSHOT", "RIM", "rimshot", 0, 70 },
108 { "CLAPS", "CLAPS", "clap", 0, 75 },
109 { "CL HAT", "CLOSED\nHAT", "closedhat", 1, 62 },
110 { "OP HAT", "OPEN\nHAT", "openhat", 1, 62 },
111 { "CRASH", "CRASH", "crash", 0, 68 },
112 { "RIDE", "RIDE", "ride", 0, 62 },
113 { "TOM HI", "HI\nTOM", "tomhi", 0, 75 },
114 { "TOM MID", "MID\nTOM", "tommid", 0, 75 },
115 { "TOM LO", "LO\nTOM", "tomlo", 0, 78 },
116 { "CONGA HI", "HI\nCONGA", "congahi", 0, 70 },
117 { "CONGA LO", "LO\nCONGA", "congalo", 0, 70 },
118 { "COWBELL", "COW\nBELL", "cowbell", 0, 58 },
119 { "TAMB", "TAMB", "tambourine", 0, 60 },
120 { "CABASA", "CABASA", "cabasa", 0, 60 },
121};
122
123
124// keys of the pads (labels of the pads, see keyToInstrument())
125static const char PadKeys[INSTRUMENTS + 1] = "12345678QWERTYUI";
126
127
128// mixer settings, saved to NVS
129struct KitSettings {
130 int8_t level[INSTRUMENTS];
131 int8_t tune[INSTRUMENTS]; // semitones
132 int8_t decay[INSTRUMENTS]; // 0..100
133 uint16_t mute; // bit mask
134 int8_t volume; // master volume (0..100)
135 int8_t metronome;
136};
137
138
139static constexpr int MAX_SONG = DrumMachine::MAX_SONG_STEPS;
140
141struct SongData {
142 uint8_t length;
143 uint8_t steps[MAX_SONG]; // pattern indexes
144};
145
146
147
149// Theme
150//
151// The display has 16 colors (VGA16Controller) and every palette slot is reprogrammed with a theme color.
152// Canvas colors are RGB888 values that the driver maps to a palette slot through a table built from the
153// default palette (setPaletteItem() doesn't rebuild it). So a theme color is selected with the default
154// color of its slot: see ink(). Colors are on the VGA grid (0, 85, 170, 255).
155
156
157enum class Ink {
158 Black, // slot 0 stays black: the mouse pointer uses it
159 Maroon, // wood grain, unlit segments
160 Wood,
161 Edge, // lines, empty cells
162 Gray, // pads
163 Cream, // legends
164 Red, // leds
165 RedDim,
166 Orange, // accent
167 Yellow,
168 Green,
169 GreenDim,
170 Charcoal, // panel strips
171 Steel,
172 Silver,
173 White, // slot 15 stays white: the mouse pointer uses it
174};
175
176
177static const RGB888 InkColors[16] = {
178 RGB888( 0, 0, 0), // Black
179 RGB888( 85, 0, 0), // Maroon
180 RGB888(170, 85, 0), // Wood
181 RGB888( 85, 85, 85), // Edge
182 RGB888(170, 170, 170), // Gray
183 RGB888(255, 255, 170), // Cream
184 RGB888(255, 0, 0), // Red
185 RGB888(170, 0, 0), // RedDim
186 RGB888(255, 170, 0), // Orange
187 RGB888(255, 255, 0), // Yellow
188 RGB888( 0, 255, 0), // Green
189 RGB888( 0, 85, 0), // GreenDim
190 RGB888( 85, 85, 85), // Charcoal (same as Edge: panel strips)
191 RGB888( 85, 85, 170), // Steel
192 RGB888(255, 255, 255), // Silver (bevels)
193 RGB888(255, 255, 255), // White
194};
195
196
197static RGB888 ink(Ink value)
198{
199 return RGB888((Color) value);
200}
201
202
203static void setupPalette()
204{
205 for (int i = 0; i < 16; ++i)
206 DisplayController.setPaletteItem(i, InkColors[i]);
207}
208
209
210static fabgl::FontInfo const * const TinyFont = &fabgl::FONT_6x8;
211static fabgl::FontInfo const * const SmallFont = &fabgl::FONT_std_12;
212static fabgl::FontInfo const * const MediumFont = &fabgl::FONT_std_17;
213static fabgl::FontInfo const * const BigFont = &fabgl::FONT_std_24;
214
215
216// style classes (last parameter of the control constructors)
217enum StyleClass {
218 STYLE_NONE,
219 STYLE_KNOB,
220 STYLE_FADER,
221 STYLE_PAD, // instrument pads
222 STYLE_TRANSPORT, // PLAY, STOP, REC (led at the top)
223 STYLE_MODE, // SONG, METRO (led at the left)
224 STYLE_DISPLAY,
225 STYLE_GRID,
226 STYLE_STEPPER,
227 STYLE_TILES,
228 STYLE_BUTTON,
229 STYLE_VOICE_NAME,
230 STYLE_INFO, // small text on the panel
231 STYLE_DIALOG,
232 STYLE_DIALOG_LABEL,
233 STYLE_EDIT, // name edit box (focusable)
234 STYLE_LIST, // file browser, song list (focusable)
235};
236
237
238struct DrumStyle : uiStyle {
239
240 void setStyle(uiObject * object, uint32_t styleClassID)
241 {
242 // keyboard events go to the main frame (it plays the pads), except in the dialogs
243 ((uiWindow *) object)->windowProps().focusable = styleClassID == STYLE_EDIT || styleClassID == STYLE_LIST;
244
245 switch (styleClassID) {
246
247 case STYLE_KNOB:
248 {
249 auto & s = ((uiKnob *) object)->knobStyle();
250 s.backgroundColor = ink(Ink::Black);
251 s.labelFont = TinyFont;
252 s.labelColor = ink(Ink::Cream);
253 s.valueFont = TinyFont;
254 s.valueColor = ink(Ink::Orange);
255 s.activeValueColor = ink(Ink::Yellow);
256 s.ringColor = ink(Ink::Orange);
257 s.ringBackgroundColor = ink(Ink::Edge);
258 s.bodyColor = ink(Ink::Edge);
259 s.capColor = ink(Ink::Black);
260 s.pointerColor = ink(Ink::Cream);
261 break;
262 }
263
264 case STYLE_FADER:
265 {
266 auto fader = (uiFader *) object;
267 auto & s = fader->faderStyle();
268 s.backgroundColor = ink(Ink::Black);
269 s.slotColor = ink(Ink::Edge);
270 s.levelColor = ink(Ink::RedDim);
271 s.tickColor = ink(Ink::Edge);
272 s.capColor = ink(Ink::Black);
273 s.capEdgeColor = ink(Ink::Gray);
274 s.capLineColor = ink(Ink::Cream);
275 s.activeCapLineColor = ink(Ink::Orange);
276 auto & p = fader->faderProps();
277 p.capLength = 12;
278 p.capWidth = 18;
279 p.slotWidth = 2;
280 p.ticks = 11;
281 break;
282 }
283
284 case STYLE_PAD:
285 case STYLE_TRANSPORT:
286 case STYLE_MODE:
287 {
288 auto pad = (uiPad *) object;
289 auto & s = pad->padStyle();
290 s.backgroundColor = ink(Ink::Black);
291 s.padColor = ink(Ink::Gray);
292 s.padBevelColor = ink(Ink::Silver);
293 s.padShadowColor = ink(Ink::Edge);
294 s.mouseOverPadColor = ink(Ink::Cream);
295 s.pressedPadColor = ink(Ink::Orange);
296 s.litPadColor = ink(Ink::Orange);
297 s.textFont = TinyFont;
298 s.textColor = ink(Ink::Black);
299 s.pressedTextColor = ink(Ink::Black);
300 s.ledOnColor = styleClassID == STYLE_TRANSPORT ? ink(Ink::Red) : ink(Ink::Green);
301 s.ledOffColor = styleClassID == STYLE_TRANSPORT ? ink(Ink::Maroon) : ink(Ink::GreenDim);
302 s.keyLabelColor = ink(Ink::Maroon); // keyboard shortcut
303 auto & p = pad->padProps();
304 p.led = styleClassID == STYLE_TRANSPORT ? uiPadLed::Top : (styleClassID == STYLE_MODE ? uiPadLed::Left : uiPadLed::None);
305 p.ledSize = 5;
306 p.keyLabelPos = styleClassID == STYLE_TRANSPORT ? uiPadKeyLabel::BottomRight : (styleClassID == STYLE_MODE ? uiPadKeyLabel::Right : uiPadKeyLabel::TopRight);
307 break;
308 }
309
310 case STYLE_DISPLAY:
311 {
312 auto display = (uiSegmentDisplay *) object;
313 auto & s = display->segmentDisplayStyle();
314 s.backgroundColor = ink(Ink::Black);
315 s.segmentColor = ink(Ink::Red);
316 s.offSegmentColor = ink(Ink::Maroon);
317 display->segmentDisplayProps().slant = 2;
318 display->windowStyle().borderSize = 1;
319 display->windowStyle().borderColor = ink(Ink::Edge);
320 break;
321 }
322
323 case STYLE_GRID:
324 {
325 auto grid = (uiStepGrid *) object;
326 auto & s = grid->stepGridStyle();
327 s.backgroundColor = ink(Ink::Black);
328 s.cellColors[0] = ink(Ink::Edge);
329 s.cellColors[1] = ink(Ink::RedDim);
330 s.cellColors[2] = ink(Ink::Red);
331 s.cellColors[3] = ink(Ink::Orange);
332 s.groupCellColor = ink(Ink::Maroon);
333 s.disabledCellColor = ink(Ink::Black);
334 s.playheadColor = ink(Ink::Yellow);
335 s.playheadCellColor = ink(Ink::Gray);
336 s.labelFont = SmallFont;
337 s.labelBackgroundColor = ink(Ink::Black);
338 s.labelColor = ink(Ink::Cream);
339 s.mutedLabelColor = ink(Ink::Edge);
340 s.mutedMarkColor = ink(Ink::RedDim);
341 s.selectedLabelBackgroundColor = ink(Ink::Edge);
342 s.selectedLabelColor = ink(Ink::Yellow);
343 s.activeLabelColor = ink(Ink::Orange);
344 s.headerColor = ink(Ink::Edge);
345 s.beatHeaderColor = ink(Ink::Cream);
346 s.cursorColor = ink(Ink::Yellow);
347 auto & p = grid->stepGridProps();
348 p.labelWidth = 66;
349 p.cellGap = 1;
350 p.groupSize = 4;
351 p.groupGap = 4;
352 p.levels = 4;
353 p.clickValue = 2;
354 p.headerHeight = 12;
355 break;
356 }
357
358 case STYLE_STEPPER:
359 {
360 auto & s = ((uiStepper *) object)->stepperStyle();
361 s.backgroundColor = ink(Ink::Black);
362 s.buttonBackgroundColor = ink(Ink::Gray);
363 s.mouseDownButtonBackgroundColor = ink(Ink::Orange);
364 s.buttonBorderColor = ink(Ink::Edge);
365 s.arrowColor = ink(Ink::Black);
366 s.mouseDownArrowColor = ink(Ink::Black);
367 s.textFont = SmallFont;
368 s.textColor = ink(Ink::Orange);
369 break;
370 }
371
372 case STYLE_TILES:
373 {
374 auto & s = ((uiTileSelector *) object)->tileSelectorStyle();
375 s.backgroundColor = ink(Ink::Black);
376 s.tileBackgroundColor = ink(Ink::Black);
377 s.tileBorderColor = ink(Ink::Edge);
378 s.selectedTileBorderColor = ink(Ink::Orange);
379 s.textFont = TinyFont;
380 s.textColor = ink(Ink::Edge);
381 s.selectedTextColor = ink(Ink::Orange);
382 ((uiTileSelector *) object)->tileSelectorProps().tileGap = 3;
383 break;
384 }
385
386 case STYLE_BUTTON:
387 {
388 auto button = (uiButton *) object;
389 button->windowStyle().borderColor = ink(Ink::Edge);
390 button->windowStyle().activeBorderColor = ink(Ink::Edge);
391 button->windowStyle().focusedBorderColor = ink(Ink::Edge);
392 button->windowStyle().borderSize = 1;
393 auto & s = button->buttonStyle();
394 s.backgroundColor = ink(Ink::Black);
395 s.mouseOverBackgroundColor = ink(Ink::Edge);
396 s.mouseDownBackgroundColor = ink(Ink::Orange);
397 s.downBackgroundColor = ink(Ink::Orange);
398 s.textColor = ink(Ink::Cream);
399 s.mouseOverTextColor = ink(Ink::Yellow);
400 s.downTextColor = ink(Ink::Black);
401 s.textFont = TinyFont;
402 break;
403 }
404
405 case STYLE_VOICE_NAME:
406 {
407 auto & s = ((uiLabel *) object)->labelStyle();
408 s.backgroundColor = ink(Ink::Black);
409 s.textFont = MediumFont;
410 s.textColor = ink(Ink::Orange);
411 break;
412 }
413
414 case STYLE_INFO:
415 {
416 auto & s = ((uiLabel *) object)->labelStyle();
417 s.backgroundColor = ink(Ink::Black);
418 s.textFont = TinyFont;
419 s.textColor = ink(Ink::Gray);
420 break;
421 }
422
423 case STYLE_DIALOG:
424 {
425 auto frame = (uiFrame *) object;
426 frame->windowStyle().borderColor = ink(Ink::Orange);
427 frame->windowStyle().activeBorderColor = ink(Ink::Orange);
428 frame->windowStyle().focusedBorderColor = ink(Ink::Orange);
429 frame->windowStyle().borderSize = 1;
430 auto & s = frame->frameStyle();
431 s.backgroundColor = ink(Ink::Black);
432 s.titleBackgroundColor = ink(Ink::Maroon);
433 s.activeTitleBackgroundColor = ink(Ink::Maroon);
434 s.titleColor = ink(Ink::Cream);
435 s.activeTitleColor = ink(Ink::Cream);
436 s.titleFont = SmallFont;
437 break;
438 }
439
440 case STYLE_DIALOG_LABEL:
441 {
442 auto & s = ((uiStaticLabel *) object)->labelStyle();
443 s.backgroundColor = ink(Ink::Black);
444 s.textColor = ink(Ink::Cream);
445 s.textFont = SmallFont;
446 break;
447 }
448
449 case STYLE_EDIT:
450 {
451 auto edit = (uiTextEdit *) object;
452 edit->windowStyle().borderColor = ink(Ink::Edge);
453 edit->windowStyle().activeBorderColor = ink(Ink::Edge);
454 edit->windowStyle().focusedBorderColor = ink(Ink::Orange);
455 edit->windowStyle().borderSize = 1;
456 auto & s = edit->textEditStyle();
457 s.backgroundColor = ink(Ink::Black);
458 s.mouseOverBackgroundColor = ink(Ink::Black);
459 s.focusedBackgroundColor = ink(Ink::Black);
460 s.textColor = ink(Ink::Orange);
461 s.textFont = MediumFont;
462 break;
463 }
464
465 case STYLE_LIST:
466 {
467 auto list = (uiCustomListBox *) object;
468 list->windowStyle().borderColor = ink(Ink::Edge);
469 list->windowStyle().activeBorderColor = ink(Ink::Edge);
470 list->windowStyle().focusedBorderColor = ink(Ink::Orange);
471 list->windowStyle().borderSize = 1;
472 auto & sc = list->scrollableControlStyle();
473 sc.scrollBarBackgroundColor = ink(Ink::Black);
474 sc.scrollBarForegroundColor = ink(Ink::Edge);
475 sc.mouseOverScrollBarForegroundColor = ink(Ink::Gray);
476 auto & s = list->listBoxStyle();
477 s.backgroundColor = ink(Ink::Black);
478 s.focusedBackgroundColor = ink(Ink::Black);
479 s.selectedBackgroundColor = ink(Ink::Edge);
480 s.focusedSelectedBackgroundColor = ink(Ink::RedDim);
481 s.textColor = ink(Ink::Cream);
482 s.selectedTextColor = ink(Ink::Yellow);
483 s.textFont = SmallFont;
484 s.itemHeight = 16;
485 break;
486 }
487
488 default:
489 break;
490 }
491 }
492
493} drumStyle;
494
495
496
498// Drawing helpers
499
500
501enum class Align { Left, Center, Right };
502
503static void drawText(Canvas * cv, fabgl::FontInfo const * font, Ink color, int x, int y, char const * text, Align align = Align::Left, bool bold = false)
504{
505 int width = cv->textExtent(font, text) + (bold ? strlen(text) : 0);
506 if (align == Align::Center)
507 x -= width / 2;
508 else if (align == Align::Right)
509 x -= width;
510 cv->setGlyphOptions(GlyphOptions().FillBackground(false).Bold(bold));
511 cv->setPenColor(ink(color));
512 cv->drawText(font, x, y, text);
513}
514
515static void fillRect(Canvas * cv, Ink color, Rect const & rect)
516{
517 cv->setBrushColor(ink(color));
518 cv->fillRectangle(rect);
519}
520
521static void drawLine(Canvas * cv, Ink color, int x1, int y1, int x2, int y2)
522{
523 cv->setPenColor(ink(color));
524 cv->drawLine(x1, y1, x2, y2);
525}
526
527// wooden end cheek: base color with darker grain lines
528static void drawWood(Canvas * cv, int x1, int x2, int y1, int y2)
529{
530 fillRect(cv, Ink::Wood, Rect(x1, y1, x2, y2));
531 cv->setPenColor(ink(Ink::Maroon));
532 int w = x2 - x1 + 1;
533 for (int k = 0; k < 3; ++k) {
534 int base = x1 + 2 + k * (w - 4) / 3;
535 int px = base, py = y1;
536 for (int y = y1; y <= y2; y += 6) {
537 int x = base + ((y * (k + 3) / 11 + k * 7) % 5 == 0 ? 1 : 0) + ((y / 37 + k) % 3 == 0 ? 1 : 0);
538 cv->drawLine(px, py, x, y);
539 px = x;
540 py = y;
541 }
542 }
543 drawLine(cv, Ink::Maroon, x2, y1, x2, y2);
544}
545
546
547
549// Main frame
550//
551// +-------------------------------------------------------------------+
552// | FabGL DRUM [PATTERN][TEMPO][STEP] TEMPO SWING VOL PLAY STOP REC |
553// | 16 channel strips: fader + pad |
554// | step grid (16 instruments x 16 steps) |
555// | PATTERN LENGTH STEPS METRO SONG | VOICE: name, sample, TUNE DECAY |
556// +-------------------------------------------------------------------+
557
558
559class DrumFrame : public uiFrame {
560
561public:
562
563 DrumFrame(uiWindow * parent)
564 : uiFrame(parent, "", Point(0, 0), parent->clientSize())
565 {
566 frameProps().resizeable = false;
567 frameProps().moveable = false;
568 frameProps().hasCloseButton = false;
569 frameProps().hasMaximizeButton = false;
570 frameProps().hasMinimizeButton = false;
571 frameStyle().backgroundColor = ink(Ink::Black);
572 windowStyle().borderSize = 0;
573
574 onPaint = [&]() { paintBackground(); };
575
576 createHeader();
577 createMixer();
578 createGrid();
579 createBottom();
580
581 onTimer = [&](uiTimerHandle) { update(); };
582 onKeyDown = [&](uiKeyEventInfo const & key) { keyDown(key); };
583 onKeyUp = [&](uiKeyEventInfo const & key) { keyUp(key); };
584 }
585
586 ~DrumFrame()
587 {
588 drums.stop();
589 for (int i = 0; i < INSTRUMENTS; ++i)
590 drums.setSample(i, nullptr);
591 }
592
593 // loads patterns, kit settings, song and user sounds (NVS and SD card)
594 void init()
595 {
596 for (int i = 0; i < INSTRUMENTS; ++i) {
597 for (int k = 0; k < FACTORY_KITS; ++k)
598 m_kitSamples[k][i] = new DrumSample(FactoryKits[k].sounds[i].data, FactoryKits[k].sounds[i].length, KIT_SAMPLE_RATE);
599 m_userSamples[i] = new DrumSample;
600 m_samplePaths[i][0] = 0;
601 drums.setSample(i, kitSample(i));
602 drums.setChokeGroup(i, Instruments[i].choke);
603 }
604
605 for (int i = 0; i < PATTERNS; ++i)
606 loadFactoryPattern(i);
607 m_song.length = sizeof(FactorySong);
608 memcpy(m_song.steps, FactorySong, sizeof(FactorySong));
609
610 KitSettings kit;
611 defaultKit(kit);
612
613 fabgl::Preferences prefs;
614 if (prefs.begin(PREFS_NAMESPACE, true)) {
615 if (prefs.getInt("version", 0) == PREFS_VERSION) {
616 for (int i = 0; i < PATTERNS; ++i) {
617 char key[8];
618 snprintf(key, sizeof(key), "p%02d", i);
619 DrumPattern pattern;
620 if (prefs.getBytes(key, &pattern, sizeof(DrumPattern)) == sizeof(DrumPattern)) {
621 pattern.name[DrumPattern::NAME_LENGTH] = 0;
622 m_patterns[i] = pattern;
623 }
624 }
625 KitSettings stored;
626 if (prefs.getBytes("kit", &stored, sizeof(KitSettings)) == sizeof(KitSettings))
627 kit = stored;
628 m_kit = iclamp(prefs.getInt("kitno", 0), 0, FACTORY_KITS - 1);
629 SongData song;
630 if (prefs.getBytes("song", &song, sizeof(SongData)) == sizeof(SongData) && song.length <= MAX_SONG)
631 m_song = song;
632 for (int i = 0; i < INSTRUMENTS; ++i) {
633 char key[8];
634 snprintf(key, sizeof(key), "s%02d", i);
635 if (prefs.getString(key, m_samplePaths[i], PATH_SIZE) == 0)
636 m_samplePaths[i][0] = 0;
637 }
638 }
639 prefs.end();
640 }
641
642 applyKit(kit);
643 selectKit(m_kit);
644
645 // user sounds assigned in a previous session
646 bool anyUser = false;
647 for (int i = 0; i < INSTRUMENTS; ++i)
648 anyUser |= m_samplePaths[i][0] != 0;
649 if (anyUser && mountSDCard(false))
650 for (int i = 0; i < INSTRUMENTS; ++i)
651 if (m_samplePaths[i][0] && m_userSamples[i]->loadWAV(m_samplePaths[i], KIT_SAMPLE_RATE, MAX_SAMPLE_LEN) == DrumSampleError::None)
652 drums.setSample(i, m_userSamples[i]);
653
654 updateSong();
655 selectPattern(0, false);
656 selectInstrument(0, true);
657 updateTransport();
658 }
659
660
661private:
662
664
665 static constexpr int WOOD_W = 10;
666 static constexpr int LEFT = 16;
667 static constexpr int STRIP_W = 38;
668 static constexpr int HEADER_Y = 0;
669 static constexpr int MIXER_Y = 74;
670 static constexpr int GRID_Y = 184;
671 static constexpr int GRID_H = 220;
672 static constexpr int BOTTOM_Y = 412;
673
674
676
677 void createHeader()
678 {
679 m_patternDisplay = new uiSegmentDisplay(this, Point(190, 18), Size(46, 32), 2, true, STYLE_DISPLAY);
680 m_tempoDisplay = new uiSegmentDisplay(this, Point(242, 18), Size(64, 32), 3, true, STYLE_DISPLAY);
681 m_stepDisplay = new uiSegmentDisplay(this, Point(312, 18), Size(46, 32), 2, true, STYLE_DISPLAY);
682 m_status = new uiLabel(this, "", Point(190, 55), Size(170, 12), true, STYLE_INFO);
683
684 // factory kit
685 m_kitStepper = new uiStepper(this, Point(20, 50), Size(162, 20), true, STYLE_STEPPER);
686 m_kitStepper->onStep = [&](int delta) { selectKit((m_kit + delta + FACTORY_KITS) % FACTORY_KITS); };
687
688 // tempo and swing belong to the selected pattern
689 m_tempoKnob = addKnob(368, 2, "TEMPO", DrumMachine::MIN_TEMPO, DrumMachine::MAX_TEMPO, 120, [&](uiKnob * k) {
690 currentPattern().tempo = k->position();
691 if (drums.pattern() == &currentPattern())
692 drums.setTempo(k->position());
693 m_tempoDisplay->setNumber(k->position());
694 k->setValueTextFmt("%d", k->position());
695 });
696 m_tempoKnob->knobProps().dragPixels = 240;
697 m_swingKnob = addKnob(422, 2, "SWING", 50, 75, 50, [&](uiKnob * k) {
698 currentPattern().swing = k->position();
699 if (drums.pattern() == &currentPattern())
700 drums.setSwing(k->position());
701 k->setValueTextFmt("%d%%", k->position());
702 });
703 m_volumeKnob = addKnob(476, 2, "VOLUME", 0, 100, 80, [&](uiKnob * k) {
704 drums.channel().setVolume(k->position() * 127 / 100);
705 k->setValueTextFmt("%d", k->position());
706 });
707
708 m_playPad = new uiPad(this, "PLAY", Point(534, 10), Size(28, 46), true, STYLE_TRANSPORT);
709 m_playPad->onPress = [&]() { play(); };
710 m_playPad->setKeyLabel("SPC");
711 m_stopPad = new uiPad(this, "STOP", Point(564, 10), Size(28, 46), true, STYLE_TRANSPORT);
712 m_stopPad->onPress = [&]() { stop(); };
713 m_stopPad->setKeyLabel("SPC");
714 m_recPad = new uiPad(this, "REC", Point(594, 10), Size(28, 46), true, STYLE_TRANSPORT);
715 m_recPad->onPress = [&]() { setRecord(!m_record); };
716 m_recPad->setKeyLabel("F1");
717 }
718
719 // "apply" is called when the value changes
720 template <typename Apply>
721 uiKnob * addKnob(int x, int y, char const * label, int min, int max, int value, Apply apply, int width = 52, int height = 66)
722 {
723 auto knob = new uiKnob(this, label, Point(x, y), Size(width, height), true, STYLE_KNOB);
724 knob->onChange = [=]() { apply(knob); };
725 knob->setup(min, max, value);
726 return knob;
727 }
728
729
731
732 void createMixer()
733 {
734 for (int i = 0; i < INSTRUMENTS; ++i) {
735 int x = LEFT + i * STRIP_W;
736 auto fader = new uiFader(this, Point(x + 7, MIXER_Y + 2), Size(24, 72), true, STYLE_FADER);
737 fader->onChange = [=]() { drums.setLevel(i, fader->position()); };
738 fader->setup(0, 100, Instruments[i].level);
739 m_faders[i] = fader;
740
741 auto pad = new uiPad(this, Instruments[i].padText, Point(x + 1, MIXER_Y + 76), Size(36, 28), true, STYLE_PAD);
742 pad->onPress = [=, this]() {
743 selectInstrument(i);
744 hit(i, 2);
745 };
746 char key[2] = { PadKeys[i], 0 };
747 pad->setKeyLabel(key);
748 m_pads[i] = pad;
749 }
750 }
751
752
754
755 void createGrid()
756 {
757 m_grid = new uiStepGrid(this, Point(LEFT, GRID_Y), Size(INSTRUMENTS * STRIP_W, GRID_H), INSTRUMENTS, PAGE_STEPS, true, STYLE_GRID);
758 for (int i = 0; i < INSTRUMENTS; ++i)
759 m_grid->setRowLabel(i, Instruments[i].name);
760 m_grid->onCellChange = [&](int row, int column) {
761 currentPattern().set(m_page * PAGE_STEPS + column, row, m_grid->cell(row, column));
762 setModified();
763 };
764 m_grid->onLabelClick = [&](int row, int button) {
765 if (button == 3)
766 setMute(row, !drums.mute(row));
767 else {
768 selectInstrument(row);
769 drums.trigger(row, 2);
770 }
771 };
772 }
773
774
776
777 void createBottom()
778 {
779 int y = BOTTOM_Y + 14;
780
781 // pattern selector and buttons
782 m_patternStepper = new uiStepper(this, Point(LEFT, y), Size(190, 22), true, STYLE_STEPPER);
783 m_patternStepper->onStep = [&](int delta) { selectPattern(m_patternIndex + delta, true); };
784 addButton(LEFT, y + 28, 46, "SAVE", [&]() { savePatternDialog(); });
785 addButton(LEFT + 48, y + 28, 46, "CLEAR", [&]() { clearPattern(); });
786 addButton(LEFT + 96, y + 28, 46, "SONG", [&]() { songDialog(); });
787 addButton(LEFT + 144, y + 28, 46, "INIT", [&]() { initDialog(); });
788
789 // length
790 m_lengthStepper = new uiStepper(this, Point(214, y), Size(62, 22), true, STYLE_STEPPER);
791 m_lengthStepper->onStep = [&](int delta) { setLength(currentPattern().length + delta); };
792
793 // steps page
794 m_pageTiles = new uiTileSelector(this, Point(282, y), Size(64, 22), true, STYLE_TILES);
795 m_pageTiles->items().append("");
796 m_pageTiles->items().append("");
797 m_pageTiles->onPaintTile = [&](int index, Rect const & r, bool selected) {
798 drawText(m_pageTiles->canvas(), TinyFont, selected ? Ink::Orange : Ink::Edge, (r.X1 + r.X2 + 1) / 2, r.Y1 + (r.height() - 8) / 2, index ? "17+" : "1+", Align::Center);
799 };
800 m_pageTiles->onChange = [&]() { selectPage(m_pageTiles->selectedItem()); };
801 m_pageTiles->selectItem(0);
802
803 // modes
804 m_metroPad = new uiPad(this, "METRO", Point(214, y + 28), Size(62, 20), true, STYLE_MODE);
805 m_metroPad->onPress = [&]() { setMetronome(!drums.metronome()); };
806 m_metroPad->setKeyLabel("F3");
807 m_songPad = new uiPad(this, "SONG", Point(282, y + 28), Size(64, 20), true, STYLE_MODE);
808 m_songPad->onPress = [&]() { setSongMode(!m_songMode); };
809 m_songPad->setKeyLabel("F2");
810
811 // voice (selected instrument)
812 int vx = 364;
813 m_voiceName = new uiLabel(this, "", Point(vx, y - 2), Size(116, 20), true, STYLE_VOICE_NAME);
814 m_sampleInfo = new uiLabel(this, "", Point(vx, y + 18), Size(116, 10), true, STYLE_INFO);
815 addButton(vx, y + 32, 56, "LOAD WAV", [&]() { loadDialog(); });
816 addButton(vx + 60, y + 32, 56, "KIT SND", [&]() { restoreFactorySound(m_selected); });
817 m_tuneKnob = addKnob(vx + 124, BOTTOM_Y - 2, "TUNE", -12, 12, 0, [&](uiKnob * k) {
818 drums.setTune(m_selected, k->position() * 100);
819 k->setValueTextFmt("%+d ST", k->position());
820 }, 66, 66);
821 m_decayKnob = addKnob(vx + 192, BOTTOM_Y - 2, "DECAY", 0, 100, 100, [&](uiKnob * k) {
822 drums.setDecay(m_selected, k->position());
823 if (k->position() >= 100)
824 k->setValueText("FULL");
825 else
826 k->setValueTextFmt("%d", k->position());
827 }, 66, 66);
828 }
829
830 template <typename Action>
831 uiButton * addButton(int x, int y, int width, char const * text, Action action)
832 {
833 auto button = new uiButton(this, text, Point(x, y), Size(width, 18), uiButtonKind::Button, true, STYLE_BUTTON);
834 button->onClick = action;
835 return button;
836 }
837
838
840
841 void paintBackground()
842 {
843 auto cv = canvas();
844 int W = 640, H = 480;
845
846 drawWood(cv, 0, WOOD_W - 1, 0, H - 1);
847 drawWood(cv, W - WOOD_W, W - 1, 0, H - 1);
848
849 // logo
850 int x = 20;
851 drawText(cv, BigFont, Ink::Cream, x, 8, "FabGL", Align::Left, true);
852 x += cv->textExtent(BigFont, "FabGL") + 10;
853 drawText(cv, BigFont, Ink::Orange, x, 8, "DRUM", Align::Left, true);
854 int logoEnd = x + cv->textExtent(BigFont, "DRUM") + 4;
855 fillRect(cv, Ink::Orange, Rect(20, 37, logoEnd, 38));
856
857 // display legends
858 drawText(cv, TinyFont, Ink::Cream, 213, 7, "PATTERN", Align::Center);
859 drawText(cv, TinyFont, Ink::Cream, 274, 7, "TEMPO", Align::Center);
860 drawText(cv, TinyFont, Ink::Cream, 335, 7, "STEP", Align::Center);
861
862 // sections
863 drawLine(cv, Ink::Edge, LEFT, MIXER_Y - 3, W - LEFT - 1, MIXER_Y - 3);
864 for (int i = 1; i < INSTRUMENTS; ++i) {
865 int sx = LEFT + i * STRIP_W - 1;
866 drawLine(cv, Ink::Maroon, sx, MIXER_Y + 2, sx, MIXER_Y + 72);
867 }
868 drawLine(cv, Ink::Edge, LEFT, GRID_Y - 4, W - LEFT - 1, GRID_Y - 4);
869 drawLine(cv, Ink::Edge, LEFT, BOTTOM_Y - 4, W - LEFT - 1, BOTTOM_Y - 4);
870
871 // bottom legends
872 drawText(cv, TinyFont, Ink::Cream, LEFT, BOTTOM_Y + 2, "PATTERN");
873 drawText(cv, TinyFont, Ink::Edge, LEFT + 190, BOTTOM_Y + 2, "PGUP/PGDN", Align::Right);
874 drawText(cv, TinyFont, Ink::Cream, 214, BOTTOM_Y + 2, "LENGTH");
875 drawText(cv, TinyFont, Ink::Cream, 282, BOTTOM_Y + 2, "STEPS");
876 drawLine(cv, Ink::Edge, 355, BOTTOM_Y + 2, 355, H - 6);
877 }
878
879
881
882 DrumPattern & currentPattern() { return m_patterns[m_patternIndex]; }
883
884 void loadFactoryPattern(int index)
885 {
886 auto & p = m_patterns[index];
887 p.clear();
888 if (index < FACTORY_PATTERNS) {
889 auto const & f = FactoryPatterns[index];
890 p.setName(f.name);
891 p.tempo = f.tempo;
892 p.swing = f.swing;
893 p.length = f.length;
894 for (auto row = f.rows; row->instrument >= 0; ++row)
895 p.setRow(row->instrument, row->steps);
896 } else {
897 p.setName("EMPTY");
898 }
899 m_modified[index] = false;
900 }
901
902 // queue: when playing, the pattern starts at the end of the current one
903 void selectPattern(int index, bool queue)
904 {
905 index = (index + PATTERNS) % PATTERNS;
906 m_patternIndex = index;
907 if (!m_songMode) {
908 if (queue && drums.playing())
909 drums.queuePattern(&m_patterns[index]);
910 else
911 drums.setPattern(&m_patterns[index]);
912 }
913 showPattern();
914 }
915
916 // updates the controls showing the selected pattern
917 void showPattern()
918 {
919 auto & p = currentPattern();
920 m_tempoKnob->setPosition(p.tempo);
921 m_swingKnob->setPosition(p.swing);
922 m_tempoDisplay->setNumber(p.tempo);
923 updatePatternName();
924 m_lengthStepper->setText(lengthText(p.length));
925 if (m_page * PAGE_STEPS >= p.length)
926 selectPage(0);
927 else
928 loadGrid();
929 }
930
931 static char const * lengthText(int length)
932 {
933 static char text[8];
934 snprintf(text, sizeof(text), "%d", length);
935 return text;
936 }
937
938 void updatePatternName()
939 {
940 char text[32];
941 snprintf(text, sizeof(text), "%02d %s%s", m_patternIndex + 1, currentPattern().name, m_modified[m_patternIndex] ? " *" : "");
942 m_patternStepper->setText(text);
943 }
944
945 void setModified()
946 {
947 if (!m_modified[m_patternIndex]) {
948 m_modified[m_patternIndex] = true;
949 updatePatternName();
950 }
951 }
952
953 // copies the visible page of the pattern to the grid
954 void loadGrid()
955 {
956 auto & p = currentPattern();
957 // the cells are changed without repaint, then the grid is repainted once
958 bool changed = false;
959 for (int row = 0; row < INSTRUMENTS; ++row)
960 for (int col = 0; col < PAGE_STEPS; ++col) {
961 int v = p.get(m_page * PAGE_STEPS + col, row);
962 if (v != m_grid->cell(row, col)) {
963 m_grid->setCell(row, col, v, false);
964 changed = true;
965 }
966 }
967 int active = iclamp(p.length - m_page * PAGE_STEPS, 0, PAGE_STEPS);
968 if (active != m_grid->activeColumns()) {
969 m_grid->setActiveColumns(active);
970 changed = false; // already repainted
971 }
972 if (changed)
973 m_grid->repaint();
974 }
975
976 void selectPage(int page)
977 {
978 if (page < 0 || page > 1 || page * PAGE_STEPS >= currentPattern().length)
979 page = 0;
980 bool changed = page != m_page;
981 m_page = page;
982 m_pageTiles->selectItem(page);
983 m_grid->stepGridProps().firstNumber = page * PAGE_STEPS + 1;
984 loadGrid();
985 if (changed)
986 m_grid->repaint(); // header numbers
987 }
988
989 void setLength(int length)
990 {
991 length = iclamp(length, 1, DrumPattern::MAX_STEPS);
992 auto & p = currentPattern();
993 if (length != p.length) {
994 p.length = length;
995 m_lengthStepper->setText(lengthText(length));
996 setModified();
997 selectPage(m_page);
998 }
999 }
1000
1001 void clearPattern()
1002 {
1003 currentPattern().clearSteps();
1004 setModified();
1005 loadGrid();
1006 }
1007
1008 void savePatternDialog()
1009 {
1010 static constexpr int W = 300, H = 160;
1011 auto dialog = new uiFrame(app()->rootWindow(), "SAVE PATTERN AND KIT", Point((640 - W) / 2, 140), Size(W, H), false, STYLE_DIALOG);
1012 dialog->frameProps().resizeable = false;
1013 dialog->frameProps().hasMaximizeButton = false;
1014 dialog->frameProps().hasMinimizeButton = false;
1015
1016 new uiStaticLabel(dialog, "DESTINATION", Point(14, 28), true, STYLE_DIALOG_LABEL);
1017 int slot = m_patternIndex;
1018 auto slotStepper = new uiStepper(dialog, Point(14, 44), Size(W - 28, 24), true, STYLE_STEPPER);
1019 auto updateSlot = [=, this](int value) {
1020 char text[32];
1021 snprintf(text, sizeof(text), "%02d %s", value + 1, m_patterns[value].name);
1022 slotStepper->setText(text);
1023 };
1024 updateSlot(slot);
1025 slotStepper->onStep = [&, updateSlot](int delta) {
1026 slot = (slot + delta + PATTERNS) % PATTERNS;
1027 updateSlot(slot);
1028 };
1029
1030 new uiStaticLabel(dialog, "NAME", Point(14, 76), true, STYLE_DIALOG_LABEL);
1031 auto edit = new uiTextEdit(dialog, currentPattern().name, Point(14, 92), Size(W - 28, 24), true, STYLE_EDIT);
1032
1033 auto ok = new uiButton(dialog, "SAVE", Point(W - 14 - 140 - 8, H - 30), Size(70, 20), uiButtonKind::Button, true, STYLE_BUTTON);
1034 ok->onClick = [=]() { dialog->exitModal(1); };
1035 auto cancel = new uiButton(dialog, "CANCEL", Point(W - 14 - 70, H - 30), Size(70, 20), uiButtonKind::Button, true, STYLE_BUTTON);
1036 cancel->onClick = [=]() { dialog->exitModal(0); };
1037
1038 app()->setFocusedWindow(edit);
1039 if (app()->showModalWindow(dialog) == 1) {
1040 char name[DrumPattern::NAME_LENGTH + 1] = { };
1041 int len = 0;
1042 for (auto c = edit->text(); *c && len < DrumPattern::NAME_LENGTH; ++c)
1043 name[len++] = toupper(*c);
1044 while (len > 0 && name[len - 1] == ' ')
1045 name[--len] = 0;
1046 savePattern(slot, len ? name : "NONAME");
1047 }
1048 app()->destroyWindow(dialog);
1049 app()->setFocusedWindow(this);
1050 }
1051
1052 // saves the current pattern to a slot (a copy when the slot is another one), and the kit settings
1053 void savePattern(int slot, char const * name)
1054 {
1055 DrumPattern pattern = currentPattern();
1056 pattern.setName(name);
1057 m_patterns[slot] = pattern;
1058 fabgl::Preferences prefs;
1059 if (prefs.begin(PREFS_NAMESPACE)) {
1060 char key[8];
1061 snprintf(key, sizeof(key), "p%02d", slot);
1062 prefs.putBytes(key, &pattern, sizeof(DrumPattern));
1063 saveKit(prefs);
1064 prefs.putInt("version", PREFS_VERSION);
1065 prefs.end();
1066 }
1067 m_modified[slot] = false;
1068 // saved to another slot ("save as"): the source pattern goes back to its stored version
1069 if (slot != m_patternIndex)
1070 reloadStoredPattern(m_patternIndex);
1071 selectPattern(slot, true);
1072 }
1073
1074 // the stored version of a pattern (NVS, or factory)
1075 void reloadStoredPattern(int index)
1076 {
1077 loadFactoryPattern(index);
1078 fabgl::Preferences prefs;
1079 if (prefs.begin(PREFS_NAMESPACE, true)) {
1080 char key[8];
1081 snprintf(key, sizeof(key), "p%02d", index);
1082 DrumPattern pattern;
1083 if (prefs.getInt("version", 0) == PREFS_VERSION && prefs.getBytes(key, &pattern, sizeof(DrumPattern)) == sizeof(DrumPattern)) {
1084 pattern.name[DrumPattern::NAME_LENGTH] = 0;
1085 m_patterns[index] = pattern;
1086 }
1087 prefs.end();
1088 }
1089 }
1090
1091 void initDialog()
1092 {
1093 auto r = app()->messageBox("INIT", "Restore factory patterns, song and kit? User data is erased.", "Restore", "Cancel", nullptr, uiMessageBoxIcon::None);
1094 if (r != uiMessageBoxResult::Button1)
1095 return;
1096 stop();
1097 setSongMode(false);
1098 fabgl::Preferences prefs;
1099 if (prefs.begin(PREFS_NAMESPACE)) {
1100 prefs.clear();
1101 prefs.end();
1102 }
1103 for (int i = 0; i < PATTERNS; ++i)
1104 loadFactoryPattern(i);
1105 m_song.length = sizeof(FactorySong);
1106 memcpy(m_song.steps, FactorySong, sizeof(FactorySong));
1107 updateSong();
1108 m_kit = 0;
1109 for (int i = 0; i < INSTRUMENTS; ++i)
1110 restoreFactorySound(i, false);
1111 KitSettings kit;
1112 defaultKit(kit);
1113 applyKit(kit);
1114 selectKit(0);
1115 selectPattern(0, false);
1116 selectInstrument(m_selected, true);
1117 }
1118
1119
1121
1122 void defaultKit(KitSettings & kit)
1123 {
1124 for (int i = 0; i < INSTRUMENTS; ++i) {
1125 kit.level[i] = Instruments[i].level;
1126 kit.tune[i] = 0;
1127 kit.decay[i] = 100;
1128 }
1129 kit.mute = 0;
1130 kit.volume = 80;
1131 kit.metronome = 0;
1132 }
1133
1134 void applyKit(KitSettings const & kit)
1135 {
1136 for (int i = 0; i < INSTRUMENTS; ++i) {
1137 m_faders[i]->setPosition(kit.level[i]);
1138 drums.setLevel(i, kit.level[i]);
1139 drums.setTune(i, iclamp(kit.tune[i], -12, 12) * 100);
1140 drums.setDecay(i, kit.decay[i]);
1141 setMute(i, kit.mute & (1 << i));
1142 }
1143 m_volumeKnob->setPosition(kit.volume);
1144 setMetronome(kit.metronome);
1145 selectInstrument(m_selected, true);
1146 }
1147
1148 void saveKit(fabgl::Preferences & prefs)
1149 {
1150 KitSettings kit;
1151 kit.mute = 0;
1152 for (int i = 0; i < INSTRUMENTS; ++i) {
1153 kit.level[i] = drums.level(i);
1154 kit.tune[i] = drums.tune(i) / 100;
1155 kit.decay[i] = drums.decay(i);
1156 if (drums.mute(i))
1157 kit.mute |= 1 << i;
1158 }
1159 kit.volume = m_volumeKnob->position();
1160 kit.metronome = drums.metronome();
1161 prefs.putBytes("kit", &kit, sizeof(KitSettings));
1162 prefs.putInt("kitno", m_kit);
1163 for (int i = 0; i < INSTRUMENTS; ++i) {
1164 char key[8];
1165 snprintf(key, sizeof(key), "s%02d", i);
1166 prefs.putString(key, m_samplePaths[i]);
1167 }
1168 }
1169
1170 // force: refresh the voice controls even when the instrument is already selected
1171 void selectInstrument(int index, bool force = false)
1172 {
1173 if (index == m_selected && !force)
1174 return;
1175 m_selected = index;
1176 m_grid->selectRow(index);
1177 m_voiceName->setText(Instruments[index].name);
1178 m_tuneKnob->setPosition(drums.tune(index) / 100);
1179 m_decayKnob->setPosition(drums.decay(index));
1180 // the knobs don't call onChange when the position doesn't change: refresh the texts
1181 m_tuneKnob->setValueTextFmt("%+d ST", m_tuneKnob->position());
1182 if (m_decayKnob->position() >= 100)
1183 m_decayKnob->setValueText("FULL");
1184 else
1185 m_decayKnob->setValueTextFmt("%d", m_decayKnob->position());
1186 updateSampleInfo();
1187 }
1188
1189 void updateSampleInfo()
1190 {
1191 auto sample = drums.sample(m_selected);
1192 char text[40];
1193 if (sample && sample == m_userSamples[m_selected]) {
1194 // file name without the path
1195 auto name = strrchr(m_samplePaths[m_selected], '/');
1196 snprintf(text, sizeof(text), "%.12s %dMS", name ? name + 1 : m_samplePaths[m_selected], sample->durationMS());
1197 } else
1198 snprintf(text, sizeof(text), "%s %dMS", FactoryKits[m_kit].name, sample ? sample->durationMS() : 0);
1199 for (auto c = text; *c; ++c)
1200 *c = toupper(*c);
1201 m_sampleInfo->setText(text);
1202 }
1203
1204 void setMute(int instrument, bool value)
1205 {
1206 drums.setMute(instrument, value);
1207 m_grid->setRowMuted(instrument, value);
1208 }
1209
1210 void restoreFactorySound(int instrument, bool saveSettings = true)
1211 {
1212 drums.setSample(instrument, kitSample(instrument));
1213 m_userSamples[instrument]->clear();
1214 m_samplePaths[instrument][0] = 0;
1215 if (saveSettings)
1216 saveKitSettings();
1217 if (instrument == m_selected)
1218 updateSampleInfo();
1219 }
1220
1221 DrumSample * kitSample(int instrument)
1222 {
1223 return m_kitSamples[m_kit][instrument];
1224 }
1225
1226 // selects a factory kit: the instruments with a user sound keep it (KIT SND restores the kit sound)
1227 void selectKit(int index)
1228 {
1229 m_kit = index;
1230 for (int i = 0; i < INSTRUMENTS; ++i)
1231 if (drums.sample(i) != m_userSamples[i])
1232 drums.setSample(i, kitSample(i));
1233 char text[24];
1234 snprintf(text, sizeof(text), "KIT %d %s", m_kit + 1, FactoryKits[m_kit].name);
1235 m_kitStepper->setText(text);
1236 updateSampleInfo();
1237 }
1238
1239 void saveKitSettings()
1240 {
1241 fabgl::Preferences prefs;
1242 if (prefs.begin(PREFS_NAMESPACE)) {
1243 saveKit(prefs);
1244 prefs.putInt("version", PREFS_VERSION);
1245 prefs.end();
1246 }
1247 }
1248
1249
1251
1252 bool mountSDCard(bool showError)
1253 {
1254 if (!m_sdMounted)
1255 m_sdMounted = FileBrowser::mountSDCard(false, SDCARD_PATH, 8);
1256 if (!m_sdMounted && showError)
1257 app()->messageBox("SD CARD", "SD card not found", "OK", nullptr, nullptr, uiMessageBoxIcon::None);
1258 return m_sdMounted;
1259 }
1260
1261 static char const * errorText(DrumSampleError error)
1262 {
1263 switch (error) {
1264 case DrumSampleError::OpenFailed: return "Cannot open the file";
1265 case DrumSampleError::InvalidFormat: return "Not a valid WAV file";
1266 case DrumSampleError::Unsupported: return "Unsupported WAV encoding";
1267 case DrumSampleError::OutOfMemory: return "Not enough memory";
1268 case DrumSampleError::ReadError: return "Read error";
1269 default: return "";
1270 }
1271 }
1272
1273 // loads a WAV file in the user sound of an instrument
1274 DrumSampleError loadSound(int instrument, char const * path)
1275 {
1276 // the instrument plays the kit sound while its user sound is replaced
1277 drums.setSample(instrument, kitSample(instrument));
1278 auto result = m_userSamples[instrument]->loadWAV(path, KIT_SAMPLE_RATE, MAX_SAMPLE_LEN);
1279 if (result == DrumSampleError::None) {
1280 drums.setSample(instrument, m_userSamples[instrument]);
1281 strlcpy(m_samplePaths[instrument], path, PATH_SIZE);
1282 } else
1283 m_samplePaths[instrument][0] = 0;
1284 return result;
1285 }
1286
1287 static bool isWAV(char const * name)
1288 {
1289 int len = strlen(name);
1290 return len > 4 && strcasecmp(name + len - 4, ".wav") == 0;
1291 }
1292
1293 // file browser: a WAV file for the selected instrument, or a folder with a whole kit (<instrument file>.wav)
1294 void loadDialog()
1295 {
1296 if (!mountSDCard(true))
1297 return;
1298
1299 static constexpr int W = 400, H = 300;
1300 char title[40];
1301 snprintf(title, sizeof(title), "LOAD SOUND: %s", Instruments[m_selected].name);
1302 auto dialog = new uiFrame(app()->rootWindow(), title, Point((640 - W) / 2, 90), Size(W, H), false, STYLE_DIALOG);
1303 dialog->frameProps().resizeable = false;
1304 dialog->frameProps().hasMaximizeButton = false;
1305 dialog->frameProps().hasMinimizeButton = false;
1306
1307 auto browser = new uiFileBrowser(dialog, Point(10, 28), Size(W - 20, H - 92), true, STYLE_LIST);
1308 browser->setDirectory(m_lastDir[0] ? m_lastDir : SDCARD_PATH);
1309 if (!browser->content().directory() || strncmp(browser->directory(), SDCARD_PATH, strlen(SDCARD_PATH)))
1310 browser->setDirectory(SDCARD_PATH);
1311
1312 new uiStaticLabel(dialog, "KIT FOLDER FILES: KICK.WAV, SNARE.WAV, ...", Point(10, H - 56), true, STYLE_DIALOG_LABEL);
1313
1314 auto loadFile = new uiButton(dialog, "LOAD SOUND", Point(10, H - 32), Size(110, 22), uiButtonKind::Button, true, STYLE_BUTTON);
1315 loadFile->onClick = [=]() { dialog->exitModal(1); };
1316 auto loadKit = new uiButton(dialog, "LOAD FOLDER AS KIT", Point(126, H - 32), Size(150, 22), uiButtonKind::Button, true, STYLE_BUTTON);
1317 loadKit->onClick = [=]() { dialog->exitModal(2); };
1318 auto cancel = new uiButton(dialog, "CANCEL", Point(W - 10 - 80, H - 32), Size(80, 22), uiButtonKind::Button, true, STYLE_BUTTON);
1319 cancel->onClick = [=]() { dialog->exitModal(0); };
1320 browser->onDblClick = [=]() {
1321 if (!browser->isDirectory() && isWAV(browser->filename()))
1322 dialog->exitModal(1);
1323 };
1324
1325 app()->setFocusedWindow(browser);
1326 int result = app()->showModalWindow(dialog);
1327
1328 char dir[PATH_SIZE];
1329 strlcpy(dir, browser->directory(), sizeof(dir));
1330 char file[PATH_SIZE * 2] = { };
1331 if (browser->filename() && !browser->isDirectory())
1332 snprintf(file, sizeof(file), "%s/%s", dir, browser->filename());
1333 strlcpy(m_lastDir, dir, sizeof(m_lastDir));
1334 app()->destroyWindow(dialog);
1335 app()->setFocusedWindow(this);
1336
1337 if (result == 1) {
1338 if (!file[0] || !isWAV(file)) {
1339 app()->messageBox("LOAD SOUND", "Select a WAV file", "OK", nullptr, nullptr, uiMessageBoxIcon::None);
1340 return;
1341 }
1342 auto error = loadSound(m_selected, file);
1343 if (error != DrumSampleError::None)
1344 app()->messageBox("LOAD SOUND", errorText(error), "OK", nullptr, nullptr, uiMessageBoxIcon::None);
1345 saveKitSettings();
1346 updateSampleInfo();
1347 drums.trigger(m_selected, 2);
1348 } else if (result == 2) {
1349 int loaded = 0;
1350 DrumSampleError lastError = DrumSampleError::None;
1351 for (int i = 0; i < INSTRUMENTS; ++i) {
1352 char path[PATH_SIZE + 16];
1353 snprintf(path, sizeof(path), "%s/%s.wav", dir, Instruments[i].file);
1354 struct stat st;
1355 if (stat(path, &st) != 0)
1356 continue;
1357 auto error = loadSound(i, path);
1358 if (error == DrumSampleError::None)
1359 ++loaded;
1360 else
1361 lastError = error;
1362 }
1363 saveKitSettings();
1364 updateSampleInfo();
1365 char msg[80];
1366 if (lastError != DrumSampleError::None)
1367 snprintf(msg, sizeof(msg), "%d sounds loaded. Some files failed: %s", loaded, errorText(lastError));
1368 else
1369 snprintf(msg, sizeof(msg), "%d sounds loaded", loaded);
1370 app()->messageBox("LOAD KIT", msg, "OK", nullptr, nullptr, uiMessageBoxIcon::None);
1371 }
1372 }
1373
1374
1376
1377 void updateSong()
1378 {
1379 DrumPattern * list[MAX_SONG];
1380 for (int i = 0; i < m_song.length; ++i)
1381 list[i] = &m_patterns[m_song.steps[i] % PATTERNS];
1382 drums.setSong(list, m_song.length, true);
1383 }
1384
1385 void songDialog()
1386 {
1387 static constexpr int W = 340, H = 320;
1388 auto dialog = new uiFrame(app()->rootWindow(), "SONG", Point((640 - W) / 2, 80), Size(W, H), false, STYLE_DIALOG);
1389 dialog->frameProps().resizeable = false;
1390 dialog->frameProps().hasMaximizeButton = false;
1391 dialog->frameProps().hasMinimizeButton = false;
1392
1393 SongData song = m_song;
1394 auto list = new uiListBox(dialog, Point(10, 28), Size(200, H - 72), true, STYLE_LIST);
1395
1396 auto refresh = [=, this, &song](int select) {
1397 list->items().clear();
1398 for (int i = 0; i < song.length; ++i)
1399 list->items().appendFmt("%02d %02d %s", i + 1, song.steps[i] + 1, m_patterns[song.steps[i] % PATTERNS].name);
1400 list->items().append("-- END");
1401 list->selectItem(iclamp(select, 0, song.length));
1402 list->repaint();
1403 };
1404 refresh(0);
1405
1406 int bx = 220, bw = W - bx - 10;
1407 new uiStaticLabel(dialog, "PATTERN", Point(bx, 28), true, STYLE_DIALOG_LABEL);
1408 int pattern = m_patternIndex;
1409 auto patternStepper = new uiStepper(dialog, Point(bx, 44), Size(bw, 22), true, STYLE_STEPPER);
1410 auto updatePattern = [=, this, &pattern]() {
1411 char text[32];
1412 snprintf(text, sizeof(text), "%02d %s", pattern + 1, m_patterns[pattern].name);
1413 patternStepper->setText(text);
1414 };
1415 updatePattern();
1416 patternStepper->onStep = [&, updatePattern](int delta) {
1417 pattern = (pattern + delta + PATTERNS) % PATTERNS;
1418 updatePattern();
1419 };
1420
1421 auto insert = new uiButton(dialog, "INSERT", Point(bx, 74), Size(bw, 20), uiButtonKind::Button, true, STYLE_BUTTON);
1422 insert->onClick = [&, refresh]() {
1423 int pos = imax(0, list->firstSelectedItem());
1424 if (song.length < MAX_SONG) {
1425 memmove(song.steps + pos + 1, song.steps + pos, song.length - pos);
1426 song.steps[pos] = pattern;
1427 ++song.length;
1428 refresh(pos + 1);
1429 }
1430 };
1431 auto replace = new uiButton(dialog, "REPLACE", Point(bx, 98), Size(bw, 20), uiButtonKind::Button, true, STYLE_BUTTON);
1432 replace->onClick = [&, refresh]() {
1433 int pos = list->firstSelectedItem();
1434 if (pos >= 0 && pos < song.length) {
1435 song.steps[pos] = pattern;
1436 refresh(pos);
1437 }
1438 };
1439 auto remove = new uiButton(dialog, "DELETE", Point(bx, 122), Size(bw, 20), uiButtonKind::Button, true, STYLE_BUTTON);
1440 remove->onClick = [&, refresh]() {
1441 int pos = list->firstSelectedItem();
1442 if (pos >= 0 && pos < song.length) {
1443 memmove(song.steps + pos, song.steps + pos + 1, song.length - pos - 1);
1444 --song.length;
1445 refresh(pos);
1446 }
1447 };
1448 auto clear = new uiButton(dialog, "CLEAR ALL", Point(bx, 146), Size(bw, 20), uiButtonKind::Button, true, STYLE_BUTTON);
1449 clear->onClick = [&, refresh]() {
1450 song.length = 0;
1451 refresh(0);
1452 };
1453
1454 auto ok = new uiButton(dialog, "OK", Point(W - 10 - 140 - 8, H - 32), Size(70, 22), uiButtonKind::Button, true, STYLE_BUTTON);
1455 ok->onClick = [=]() { dialog->exitModal(1); };
1456 auto cancel = new uiButton(dialog, "CANCEL", Point(W - 10 - 70, H - 32), Size(70, 22), uiButtonKind::Button, true, STYLE_BUTTON);
1457 cancel->onClick = [=]() { dialog->exitModal(0); };
1458
1459 app()->setFocusedWindow(list);
1460 if (app()->showModalWindow(dialog) == 1) {
1461 bool wasSong = drums.playingSong();
1462 if (wasSong)
1463 stop();
1464 m_song = song;
1465 updateSong();
1466 fabgl::Preferences prefs;
1467 if (prefs.begin(PREFS_NAMESPACE)) {
1468 prefs.putBytes("song", &m_song, sizeof(SongData));
1469 prefs.putInt("version", PREFS_VERSION);
1470 prefs.end();
1471 }
1472 if (m_song.length == 0)
1473 setSongMode(false);
1474 }
1475 app()->destroyWindow(dialog);
1476 app()->setFocusedWindow(this);
1477 }
1478
1479
1481
1482 void play()
1483 {
1484 drums.setErase(0);
1485 if (m_songMode && m_song.length > 0)
1486 drums.playSong(0);
1487 else {
1488 drums.setPattern(&currentPattern());
1489 drums.play();
1490 }
1491 updateTransport();
1492 }
1493
1494 void stop()
1495 {
1496 drums.stop();
1497 drums.setPattern(&currentPattern());
1498 m_grid->setPlayhead(-1);
1499 updateTransport();
1500 }
1501
1502 void setRecord(bool value)
1503 {
1504 m_record = value;
1505 if (!value)
1506 drums.setErase(m_eraseMask = 0);
1507 updateTransport();
1508 }
1509
1510 void setSongMode(bool value)
1511 {
1512 if (value && m_song.length == 0)
1513 value = false;
1514 if (value != m_songMode) {
1515 bool wasPlaying = drums.playing();
1516 if (wasPlaying)
1517 stop();
1518 m_songMode = value;
1519 if (!value)
1520 drums.setPattern(&currentPattern());
1521 }
1522 updateTransport();
1523 }
1524
1525 void setMetronome(bool value)
1526 {
1527 drums.setMetronome(value);
1528 m_metroPad->setLed(value);
1529 }
1530
1531 void updateTransport()
1532 {
1533 m_playPad->setLed(drums.playing());
1534 m_recPad->setLed(m_record);
1535 m_songPad->setLed(m_songMode);
1536 }
1537
1538 // plays an instrument (recorded when recording and playing)
1539 void hit(int instrument, int velocity)
1540 {
1541 if (m_record && drums.playing()) {
1542 int step = drums.recordHit(instrument, velocity);
1543 if (step >= 0 && drums.pattern() == &currentPattern()) {
1544 setModified();
1545 if (step / PAGE_STEPS == m_page)
1546 m_grid->setCell(instrument, step % PAGE_STEPS, velocity);
1547 }
1548 } else
1549 drums.trigger(instrument, velocity);
1550 }
1551
1552
1554
1555 // pads keys: 1..8 and Q..I
1556 static int keyToInstrument(VirtualKey vk)
1557 {
1558 using namespace fabgl;
1559 switch (vk) {
1560 case VK_1: return 0;
1561 case VK_2: return 1;
1562 case VK_3: return 2;
1563 case VK_4: return 3;
1564 case VK_5: return 4;
1565 case VK_6: return 5;
1566 case VK_7: return 6;
1567 case VK_8: return 7;
1568 case VK_q: case VK_Q: return 8;
1569 case VK_w: case VK_W: return 9;
1570 case VK_e: case VK_E: return 10;
1571 case VK_r: case VK_R: return 11;
1572 case VK_t: case VK_T: return 12;
1573 case VK_y: case VK_Y: return 13;
1574 case VK_u: case VK_U: return 14;
1575 case VK_i: case VK_I: return 15;
1576 default: return -1;
1577 }
1578 }
1579
1580 void keyDown(uiKeyEventInfo const & key)
1581 {
1582 int instrument = keyToInstrument(key.VK);
1583 if (instrument >= 0) {
1584 if (m_padKeys & (1 << instrument))
1585 return; // auto repeat
1586 m_padKeys |= 1 << instrument;
1587 if (m_eraseKey && m_record && drums.playing()) {
1588 m_eraseMask |= 1 << instrument;
1589 drums.setErase(m_eraseMask);
1590 } else {
1591 selectInstrument(instrument);
1592 hit(instrument, key.SHIFT ? 3 : (key.CTRL ? 1 : 2));
1593 }
1594 m_pads[instrument]->setLit(true);
1595 return;
1596 }
1597 switch (key.VK) {
1598 case fabgl::VK_SPACE:
1599 if (drums.playing())
1600 stop();
1601 else
1602 play();
1603 break;
1604 case fabgl::VK_F1:
1605 setRecord(!m_record);
1606 break;
1607 case fabgl::VK_F2:
1608 setSongMode(!m_songMode);
1609 break;
1610 case fabgl::VK_F3:
1611 setMetronome(!drums.metronome());
1612 break;
1613 case fabgl::VK_F4:
1614 selectKit((m_kit + 1) % FACTORY_KITS);
1615 break;
1616 case fabgl::VK_PAGEUP:
1617 selectPattern(m_patternIndex - 1, true);
1618 break;
1619 case fabgl::VK_PAGEDOWN:
1620 selectPattern(m_patternIndex + 1, true);
1621 break;
1622 case fabgl::VK_LEFT:
1623 selectPage(0);
1624 break;
1625 case fabgl::VK_RIGHT:
1626 selectPage(1);
1627 break;
1628 case fabgl::VK_PLUS:
1629 case fabgl::VK_KP_PLUS:
1630 m_tempoKnob->setPosition(m_tempoKnob->position() + 1);
1631 break;
1632 case fabgl::VK_MINUS:
1633 case fabgl::VK_KP_MINUS:
1634 m_tempoKnob->setPosition(m_tempoKnob->position() - 1);
1635 break;
1637 m_eraseKey = true;
1638 break;
1639 default:
1640 break;
1641 }
1642 }
1643
1644 void keyUp(uiKeyEventInfo const & key)
1645 {
1646 int instrument = keyToInstrument(key.VK);
1647 if (instrument >= 0) {
1648 m_padKeys &= ~(1 << instrument);
1649 if (m_eraseMask & (1 << instrument)) {
1650 m_eraseMask &= ~(1 << instrument);
1651 drums.setErase(m_eraseMask);
1652 }
1653 m_pads[instrument]->setLit(false);
1654 } else if (key.VK == fabgl::VK_BACKSPACE) {
1655 m_eraseKey = false;
1656 drums.setErase(m_eraseMask = 0);
1657 }
1658 }
1659
1660
1662
1663 void update()
1664 {
1665 // song mode: the selected pattern follows the song
1666 auto playing = drums.pattern();
1667 if (drums.playingSong() && playing && playing != &currentPattern()) {
1668 m_patternIndex = playing - m_patterns;
1669 showPattern();
1670 }
1671 // pattern mode: a queued pattern has started
1672 if (!m_songMode && drums.playing() && playing && playing != &currentPattern() && !drums.queuedPattern()) {
1673 m_patternIndex = playing - m_patterns;
1674 showPattern();
1675 }
1676 if (!drums.playing() && m_playPad->led())
1677 updateTransport(); // the song ended
1678
1679 // playhead and step display
1680 int step = drums.step();
1681 bool visible = step >= 0 && playing == &currentPattern() && step / PAGE_STEPS == m_page;
1682 m_grid->setPlayhead(visible ? step % PAGE_STEPS : -1);
1683 if (step >= 0)
1684 m_stepDisplay->setNumber(step + 1);
1685 else
1686 m_stepDisplay->setText("--");
1687 m_patternDisplay->setNumber((playing ? playing - m_patterns : m_patternIndex) + 1, true);
1688 if (playing)
1689 m_tempoDisplay->setNumber(playing->tempo);
1690
1691 // status line
1692 char status[40] = "";
1693 if (drums.playingSong())
1694 snprintf(status, sizeof(status), "SONG %02d/%02d", drums.songPosition() + 1, m_song.length);
1695 else if (drums.queuedPattern())
1696 snprintf(status, sizeof(status), "NEXT %02d", (int) (drums.queuedPattern() - m_patterns) + 1);
1697 else if (m_songMode)
1698 snprintf(status, sizeof(status), "SONG MODE %d PATTERNS", m_song.length);
1699 if (m_record)
1700 strlcat(status, status[0] ? " REC" : "REC", sizeof(status));
1701 if (m_eraseMask)
1702 strlcat(status, " ERASE", sizeof(status));
1703 if (strcmp(status, m_status->text()))
1704 m_status->setText(status);
1705
1706 // pads and grid labels flash when an instrument plays
1707 for (int i = 0; i < INSTRUMENTS; ++i) {
1708 uint8_t count = drums.hitCount(i);
1709 if (count != m_hitCount[i]) {
1710 m_hitCount[i] = count;
1711 m_flash[i] = 3; // 120 ms
1712 } else if (m_flash[i] > 0)
1713 --m_flash[i];
1714 bool lit = m_flash[i] > 0;
1715 m_grid->setRowActive(i, lit);
1716 if (!(m_padKeys & (1 << i)) && !m_pads[i]->pressed())
1717 m_pads[i]->setLit(lit);
1718 }
1719
1720 // recording (and erasing) changes the pattern inside the sound generator: refresh the grid
1721 if (m_record && playing == &currentPattern()) {
1722 auto & p = currentPattern();
1723 bool changed = false;
1724 for (int row = 0; row < INSTRUMENTS; ++row)
1725 for (int col = 0; col < PAGE_STEPS; ++col) {
1726 int v = p.get(m_page * PAGE_STEPS + col, row);
1727 if (v != m_grid->cell(row, col)) {
1728 m_grid->setCell(row, col, v);
1729 changed = true;
1730 }
1731 }
1732 if (changed)
1733 setModified();
1734 }
1735 }
1736
1737
1738 uiSegmentDisplay * m_patternDisplay;
1739 uiSegmentDisplay * m_tempoDisplay;
1740 uiSegmentDisplay * m_stepDisplay;
1741 uiLabel * m_status;
1742 uiKnob * m_tempoKnob;
1743 uiKnob * m_swingKnob;
1744 uiKnob * m_volumeKnob;
1745 uiKnob * m_tuneKnob;
1746 uiKnob * m_decayKnob;
1747 uiPad * m_playPad;
1748 uiPad * m_stopPad;
1749 uiPad * m_recPad;
1750 uiPad * m_metroPad;
1751 uiPad * m_songPad;
1752 uiFader * m_faders[INSTRUMENTS];
1753 uiPad * m_pads[INSTRUMENTS];
1754 uiStepGrid * m_grid;
1755 uiStepper * m_patternStepper;
1756 uiStepper * m_lengthStepper;
1757 uiTileSelector * m_pageTiles;
1758 uiLabel * m_voiceName;
1759 uiLabel * m_sampleInfo;
1760
1761 DrumPattern m_patterns[PATTERNS];
1762 bool m_modified[PATTERNS] = { };
1763 int m_patternIndex = 0;
1764 int m_page = 0;
1765 int m_selected = 0;
1766 bool m_record = false;
1767 bool m_songMode = false;
1768 SongData m_song = { };
1769 DrumSample * m_kitSamples[FACTORY_KITS][INSTRUMENTS];
1770 int m_kit = 0; // selected factory kit
1771 uiStepper * m_kitStepper;
1772 DrumSample * m_userSamples[INSTRUMENTS];
1773 char m_samplePaths[INSTRUMENTS][PATH_SIZE];
1774 char m_lastDir[PATH_SIZE] = "";
1775 bool m_sdMounted = false;
1776 uint8_t m_hitCount[INSTRUMENTS] = { };
1777 uint8_t m_flash[INSTRUMENTS] = { };
1778 uint32_t m_padKeys = 0; // pad keys held down
1779 bool m_eraseKey = false;
1780 uint32_t m_eraseMask = 0;
1781};
1782
1783
1784
1786// Application
1787
1788
1789class DrumApp : public uiApp {
1790
1791 void init()
1792 {
1793 soundGenerator.setVolume(127); // full scale
1794 soundGenerator.setOversampling(16); // DAC at 352.8 kHz with noise shaping: 16 bit resolution on the 8 bit DAC
1795 drums.begin(&soundGenerator);
1796
1797 setStyle(&drumStyle);
1798 auto & dlg = appProps().dialogStyleClasses; // message boxes
1799 dlg.frame = STYLE_DIALOG;
1800 dlg.label = STYLE_DIALOG_LABEL;
1801 dlg.button = STYLE_BUTTON;
1802 dlg.textEdit = STYLE_EDIT;
1803
1804 auto frame = new DrumFrame(rootWindow());
1805 frame->init();
1806 showWindow(frame, true);
1807 setActiveWindow(frame);
1808 setFocusedWindow(frame);
1809
1810 setTimer(frame, 40); // playhead, displays, pads activity
1811 }
1812
1813} app;
1814
1815
1816extern "C" void app_main()
1817{
1819
1820 DisplayController.begin();
1821 DisplayController.setResolution(VGA_640x480_60Hz);
1822 setupPalette();
1823
1824 // adjust this to center screen in your monitor
1825 //DisplayController.moveScreen(20, -2);
1826
1827 while (true)
1828 app.run(&DisplayController);
1829}
void fillRectangle(int X1, int Y1, int X2, int Y2)
Fills a rectangle using the current brush color.
Definition canvas.cpp:278
void setBrushColor(uint8_t red, uint8_t green, uint8_t blue)
Sets the brush (background) color from its color components.
Definition canvas.cpp:214
int textExtent(FontInfo const *fontInfo, char const *text)
Calculates the width of a text, in pixels.
Definition canvas.cpp:453
void drawLine(int X1, int Y1, int X2, int Y2)
Draws a line between the specified start and end coordinates.
Definition canvas.cpp:256
void setPenColor(uint8_t red, uint8_t green, uint8_t blue)
Sets the pen (foreground) color from its color components.
Definition canvas.cpp:193
void drawText(int X, int Y, char const *text, bool wrap=false)
Draws a string at the specified position.
Definition canvas.cpp:401
void setGlyphOptions(GlyphOptions options)
Sets drawing options for the next glyphs.
Definition canvas.cpp:358
Provides a set of drawing methods.
Definition canvas.h:73
void setTempo(int bpm)
Sets the tempo of the playing pattern.
void setDecay(int instrument, int value)
Sets the decay of an instrument.
void setTune(int instrument, int cents)
Sets the tuning of an instrument.
int decay(int instrument)
Gets the decay of an instrument (0..100).
uint8_t hitCount(int instrument)
Counts the hits of an instrument (live and sequencer), to show the activity.
void setSwing(int percent)
Sets the swing of the playing pattern.
void setSong(DrumPattern *const *patterns, int count, bool loop=true)
Sets the song: a list of patterns played in sequence by playSong().
WaveformGenerator & channel()
Gets the sound generator channel that plays the drum machine.
void setSample(int instrument, DrumSample const *sample)
Sets the sound of an instrument.
static constexpr int MAX_TEMPO
Maximum tempo (BPM).
bool playingSong()
Determines whether the sequencer is playing the song.
void setPattern(DrumPattern *pattern)
Sets the pattern to play (now).
static constexpr int INSTRUMENTS
Number of instruments.
void playSong(int position=0)
Starts playing the song.
bool mute(int instrument)
Determines whether an instrument is muted.
int step()
Gets the step that is playing (-1 = stopped).
int tune(int instrument)
Gets the tuning of an instrument in cents.
void play()
Starts playing the pattern from the first step.
bool metronome()
Determines whether the metronome is enabled.
bool playing()
Determines whether the sequencer is playing.
void stop()
Stops the sequencer (the sounds play until they end).
int recordHit(int instrument, int velocity=2)
Records a hit in the playing pattern, quantized to the nearest step, and plays it.
DrumPattern * pattern()
Gets the playing pattern.
int level(int instrument)
Gets the level of an instrument (0..100).
void setErase(uint32_t mask)
Erases the hits of instruments while the playhead passes them.
DrumPattern * queuedPattern()
Gets the queued pattern, nullptr if none.
void trigger(int instrument, int velocity=2)
Plays an instrument now.
static constexpr int MIN_TEMPO
Minimum tempo (BPM).
int songPosition()
Gets the song entry that is playing (-1 = not playing the song).
void setMute(int instrument, bool value)
Mutes an instrument: the sequencer doesn't play it (trigger() still does).
void setChokeGroup(int instrument, int group)
Sets the choke group of an instrument.
void setMetronome(bool value, int volume=60)
Enables the metronome: a click on every quarter note, accented on the first beat.
void queuePattern(DrumPattern *pattern)
Sets the pattern to play at the end of the current one (immediately when stopped).
static constexpr int MAX_SONG_STEPS
Maximum number of entries of a song.
DrumSample const * sample(int instrument)
Gets the sound of an instrument.
void begin(SoundGenerator *soundGenerator)
Attaches the drum machine to the sound generator and starts the sound generator.
void setLevel(int instrument, int value)
Sets the level of an instrument.
A sample based drum machine with a step sequencer.
DrumSample()
Creates an empty sample.
static bool mountSDCard(bool formatOnFail, char const *mountPath, size_t maxFiles=4, int allocationUnitSize=16 *1024, int MISO=16, int MOSI=17, int CLK=14, int CS=13)
Mounts the filesystem of the SD Card.
SoundGenerator handles audio output.
Definition soundgen.h:393
static void begin(gpio_num_t port0_clkGPIO, gpio_num_t port0_datGPIO, gpio_num_t port1_clkGPIO=GPIO_UNUSED, gpio_num_t port1_datGPIO=GPIO_UNUSED)
Initializes the PS/2 device controller.
PS/2 device controller.
size_t getString(char const *key, char *value, size_t maxLen)
Gets a string.
bool clear()
Removes all keys of the namespace.
void end()
Commits changes and closes the namespace.
bool begin(char const *name, bool readOnly=false)
Opens the specified namespace.
void setPaletteItem(int index, RGB888 const &color)
Sets the color of the specified palette item.
VGA bitmapped display controller with 16 colors.
void begin(gpio_num_t redGPIO, gpio_num_t greenGPIO, gpio_num_t blueGPIO, gpio_num_t HSyncGPIO, gpio_num_t VSyncGPIO)
Initializer for 8 colors (5 GPIOs).
void setVolume(int value)
Sets the volume of this generator.
Definition soundgen.h:142
Base class of all UI elements like windows and controls.
Definition fabui.h:315
Base class for all visible UI elements (Frames and Controls).
Definition fabui.h:452
Represents the whole application base class.
Definition fabui.h:5167
uiButton(uiWindow *parent, char const *text, const Point &pos, const Size &size, uiButtonKind kind=uiButtonKind::Button, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:2696
uiFader(uiWindow *parent, const Point &pos, const Size &size, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:6839
uiFileBrowser(uiWindow *parent, const Point &pos, const Size &size, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:4512
uiFrame(uiWindow *parent, char const *title, const Point &pos, const Size &size, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:2058
A frame is a window with a title bar, maximize/minimize/close buttons and that is resizable or movabl...
Definition fabui.h:889
void setValueTextFmt(const char *format,...)
Sets the text shown below the knob, using printf like formatting.
Definition fabui.cpp:5684
uiKnob(uiWindow *parent, char const *label, const Point &pos, const Size &size, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:5607
void setValueText(char const *value)
Sets the text shown below the knob.
Definition fabui.cpp:5676
int position()
Determines the knob position.
Definition fabui.h:3204
uiLabel(uiWindow *parent, char const *text, const Point &pos, const Size &size=Size(0, 0), bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:3347
uiListBox(uiWindow *parent, const Point &pos, const Size &size, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:4455
uiPad(uiWindow *parent, char const *text, const Point &pos, const Size &size, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:7123
uiSegmentDisplay(uiWindow *parent, const Point &pos, const Size &size, int digits, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:7366
uiStaticLabel(uiWindow *parent, char const *text, const Point &pos, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:3463
uiStepGrid(uiWindow *parent, const Point &pos, const Size &size, int rows, int columns, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:7582
uiStepper(uiWindow *parent, const Point &pos, const Size &size, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:6183
uiTextEdit(uiWindow *parent, char const *text, const Point &pos, const Size &size, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:2858
uiTileSelector(uiWindow *parent, const Point &pos, const Size &size, bool visible=true, uint32_t styleClassID=0)
Creates an instance of the object.
Definition fabui.cpp:6310
DrumSampleError
Result of DrumSample::loadWAV().
Definition drummachine.h:52
Color
Named colors.
VirtualKey
Represents each possible real or derived (SHIFT + real) key.
Definition fabutils.h:1381
Single include file of the FabGL library.
#define VGA_640x480_60Hz
Definition fabglconf.h:246
This file contains all classes related to FabGL Graphical User Interface.
@ Bold
Definition terminal.h:723
@ VK_PAGEUP
Definition fabutils.h:1536
@ VK_SPACE
Definition fabutils.h:1384
@ VK_F2
Definition fabutils.h:1551
@ VK_F1
Definition fabutils.h:1550
@ VK_PAGEDOWN
Definition fabutils.h:1538
@ VK_F3
Definition fabutils.h:1552
@ VK_BACKSPACE
Definition fabutils.h:1522
@ VK_MINUS
Definition fabutils.h:1465
@ VK_LEFT
Definition fabutils.h:1544
@ VK_KP_MINUS
Definition fabutils.h:1466
@ VK_RIGHT
Definition fabutils.h:1546
@ VK_F4
Definition fabutils.h:1553
@ VK_PLUS
Definition fabutils.h:1467
@ VK_KP_PLUS
Definition fabutils.h:1468
void setName(char const *value)
Sets the name (truncated to NAME_LENGTH characters).
static constexpr int NAME_LENGTH
Maximum name length (terminator not included).
void clear()
Removes all hits and sets the defaults: 16 steps, 120 BPM, no swing, no name.
static constexpr int MAX_STEPS
Maximum number of steps.
char name[NAME_LENGTH+1]
Represents a 24-bit RGB color.
Represents a rectangle.
Definition fabutils.h:282
Describes a bitmapped font.
Definition fabutils.h:363
Base class for application styles.
Definition fabui.h:5060
uint8_t SHIFT
Definition fabui.h:172
VirtualKey VK
Definition fabui.h:167
uint8_t CTRL
Definition fabui.h:171
Base class for application styles.
Definition fabui.h:5060
Specifies glyph painting options.