Add basic sounds and bloops for NetDeck

- Add SoundEngine I2S audio renderer (TONE/SWEEP/NOISE)
- Add gameplay sounds: unit hit, unit death, door open/close, laser fire
- Add network sounds: ICE cracking, trace progress, link severed
- Add UI sounds: click confirm, key presses, view switch, FRENZY/BLIND
- Add network state sounds: node select, link build, ICE cracking
- Emulator: default to 960x720 window (3x scaling)
- Update STATUS.md with M4 done

All 21 tests pass (14 unit + 7 integration, 0 failures).
This commit is contained in:
Dejvino
2026-11-14 19:01:50 +01:00
parent 21d37486cf
commit 3cf17a9a5f
7 changed files with 465 additions and 19 deletions
+6 -4
View File
@@ -73,17 +73,19 @@ smoke: $(EMU)
# --- tests -----------------------------------------------------------------
# fast layer: unit + integration (deterministic, sim stepped directly)
SOUND_SRC := $(wildcard $(APP_DIR)/sound_engine.cpp)
$(APP)-tests: tests/test_main.cpp tests/shim_globals.cpp tests/harness.h \
tests/sim_helpers.h tests/unit_tests.h tests/integration_tests.h \
$(SHIMS) $(SKETCH_SRCS)
$(SHIMS) $(SKETCH_SRCS) $(SOUND_SRC)
$(CXX) $(CXXFLAGS) $(SDLFLAGS) $(TESTS_INC) $(DEFS) \
tests/shim_globals.cpp tests/test_main.cpp -o $@ $(LIBS)
tests/shim_globals.cpp tests/test_main.cpp $(SOUND_SRC) -o $@ $(LIBS)
# slow layer: E2E journeys through the real loop() + input pipeline (own build)
$(APP)-e2e: tests/e2e_tests.cpp tests/shim_globals.cpp tests/harness.h \
tests/sim_helpers.h $(SHIMS) $(SKETCH_SRCS)
tests/sim_helpers.h $(SHIMS) $(SKETCH_SRCS) $(SOUND_SRC)
$(CXX) $(CXXFLAGS) $(SDLFLAGS) $(TESTS_INC) $(DEFS) \
tests/shim_globals.cpp tests/e2e_tests.cpp -o $@ $(LIBS)
tests/shim_globals.cpp tests/e2e_tests.cpp $(SOUND_SRC) -o $@ $(LIBS)
test-unit: $(APP)-tests
./$(APP)-tests unit
+1 -1
View File
@@ -134,7 +134,7 @@ int main(int argc, char **argv)
TTF_Init();
SDL_Window *win = SDL_CreateWindow("T-Deck emulator — " APP_NAME,
640, 480, SDL_WINDOW_RESIZABLE);
960, 720, SDL_WINDOW_RESIZABLE);
SDL_Renderer *ren = SDL_CreateRenderer(win, NULL);
if (!ren) ren = SDL_CreateRenderer(win, "software"); // fallback (headless)
SDL_SetRenderLogicalPresentation(ren, emuGfx::W, emuGfx::H,
+3 -3
View File
@@ -116,7 +116,7 @@ TEST(integration/daemon_gating_messages)
handleKey('p');
clickNode(N_JUNC); stepTicks(LINK_TICKS);
clickNode(N_HIVE); stepTicks(ICE_TICKS);
handleKey('1'); // HIVE online -> armed
EXPECT_EQ(strcmp(msgText, "M4 PENDING"), 0); // payload lands in M4
EXPECT(test::serialHas("daemon 1 armed"));
handleKey('1'); // HIVE online -> FRENZY.EXE activated
EXPECT_EQ(strcmp(msgText, "FRENZY ACTIVE"), 0); // FRENZY effect lands in M4
EXPECT(test::serialHas("[key] frenzy"));
}
+164 -10
View File
@@ -45,6 +45,7 @@
#include "utilities.h"
#include "TouchDrvGT911.hpp"
#include "nd_layout.h"
#include "sound_engine.h"
// ---------------------------------------------------------------------------
// Hardware + full-frame rendering (M1 anti-flicker pattern)
@@ -53,6 +54,8 @@ TFT_eSPI tft;
TouchDrvGT911 touch;
static bool touchAvail = false;
static SoundEngine sound;
#ifndef EMULATOR
static TFT_eSprite fb(&tft); // full-frame 320x240x16 buffer (PSRAM)
static TFT_eSprite *const GFXP = &fb;
@@ -198,6 +201,9 @@ static int traceProg = 0; // 0..TRACE_TICKS
// deck thermal: >0 = OVERHEAT lockout (ticks remaining, shown as %)
static int heatT = 0;
// FRENZY.EXE: >0 = droids attack each other (ticks @ 50ms, 6s = 300)
static int frenzyT = 0;
// feedback spike queues a reinforcement droid (spawned by the combat layer)
static bool reinforcePending = false;
@@ -217,6 +223,109 @@ static void flashMsg(const char *t)
Serial.printf("[msg] %s\n", t);
}
static void playBleep(uint16_t freq, uint16_t durMs = 50, uint16_t amp = 16000)
{
SndEvent e = {SND_TONE, freq, 0, durMs, amp};
sound.play(e);
}
static void playLaser()
{
// Quick laser beam sound - rising sweep
SndEvent e = {SND_SWEEP, 400, 800, 30, 12000};
sound.play(e);
}
static void playFeedback()
{
// Feedback spike - noisy burst
SndEvent e = {SND_NOISE, 0, 0, 80, 8000};
sound.play(e);
}
static void playBreachSuccess()
{
// Triumphant ascending tone
SndEvent e = {SND_SWEEP, 200, 800, 200, 12000};
sound.play(e);
}
static void playSquadKia()
{
// descending thud
SndEvent e = {SND_SWEEP, 800, 200, 150, 10000};
sound.play(e);
}
static void playUnitHit()
{
// Short impact bleep when unit is hit
SndEvent e = {SND_TONE, 600, 0, 20, 14000};
sound.play(e);
}
static void playUnitDeath()
{
// Low thud when unit dies
SndEvent e = {SND_NOISE, 0, 0, 60, 6000};
sound.play(e);
}
static void playDoorOpen()
{
// Open chord-like sound
SndEvent e = {SND_SWEEP, 300, 500, 50, 12000};
sound.play(e);
}
static void playDoorClose()
{
// Close descending tone
SndEvent e = {SND_SWEEP, 600, 200, 50, 10000};
sound.play(e);
}
static void playNodeSelect()
{
// Node selection click
playBleep(800, 20);
}
static void playLinkBuild()
{
// Link building confirmation
SndEvent e = {SND_TONE, 500, 0, 30, 13000};
sound.play(e);
}
static void playLinkActive()
{
// Link established - steady tone
SndEvent e = {SND_TONE, 400, 0, 10, 12000};
sound.play(e);
}
static void playLinkSevered()
{
// Link cut - short burst
SndEvent e = {SND_NOISE, 0, 0, 40, 8000};
sound.play(e);
}
static void playIceCrack()
{
// ICE cracking progress - ascending tone
SndEvent e = {SND_SWEEP, 300, 600, 50, 11000};
sound.play(e);
}
static void playTraceProgress()
{
// Trace pulse proximity - descending sweep
SndEvent e = {SND_SWEEP, 600, 200, 30, 10000};
sound.play(e);
}
// ---------------------------------------------------------------------------
// Sub-net logic
// ---------------------------------------------------------------------------
@@ -270,6 +379,8 @@ static void tryLink(int node)
if (nodeOnline[node]) {
if (node == N_DOOR) {
doorOpen = !doorOpen;
if (doorOpen) playDoorOpen();
else playDoorClose();
Serial.printf("[net] DOOR_CTRL: blast door %s\n", doorOpen ? "OPEN" : "CLOSED");
flashMsg(doorOpen ? "DOOR OPEN" : "DOOR CLOSED");
return;
@@ -299,6 +410,8 @@ static void tryLink(int node)
l.prog = 0;
l.dur = ice ? ICE_TICKS : LINK_TICKS;
refreshOnline(); // offline until the build completes
playLinkBuild();
playLinkActive();
Serial.printf("[net] routing %s%s (%.1fs)\n", EDGE_LABELS[edge],
ice ? " [ICE]" : "", l.dur * nd::SIM_TICK_MS / 1000.0f);
return;
@@ -309,6 +422,7 @@ static void tryLink(int node)
// sever the link (and everything that loses its path to AIRLK)
static void severLink(int li)
{
playLinkSevered();
Serial.printf("[net] severed %s\n", EDGE_LABELS[edgeBetween(links[li].a, links[li].b)]);
links[li].active = false;
refreshOnline();
@@ -350,6 +464,7 @@ static void feedbackSpike()
dropLinks();
heatT = HEAT_TICKS;
reinforcePending = true;
playFeedback();
Serial.println("[net] FEEDBACK SPIKE: links dropped, OVERHEAT 3s, reinforcement inbound");
flashMsg("FEEDBACK!");
}
@@ -373,7 +488,17 @@ static void stepNetwork()
// red trace
if (traceActive) {
traceProg++;
if (traceProg >= TRACE_TICKS) feedbackSpike();
if (traceProg >= TRACE_TICKS) {
playTraceProgress(); // trace nearly reached airlock
feedbackSpike();
}
}
// ICE crack progress check during link building
for (auto &l : links) {
if (l.b == N_HIVE && l.active && l.prog < l.dur) {
int crackProg = l.prog;
if (crackProg % 20 == 0) playIceCrack(); // crack every ~1s
}
}
// thermal cooldown
if (heatT > 0) {
@@ -493,6 +618,8 @@ static bool inCover(int ui)
}
// nearest living enemy within range + LOS (unit index — see planPath() note)
// During FRENZY.EXE (frenzyT > 0), droids ignore team boundaries and target
// the nearest unit — friend or foe — causing droids to attack each other.
static int acquireTarget(int si)
{
const Unit &u = units[si];
@@ -500,7 +627,8 @@ static int acquireTarget(int si)
long bestD = 1L << 30;
for (int i = 0; i < 7; i++) {
if (i == si || !units[i].alive) continue;
if (units[i].team == u.team) continue;
// FRENZY: droids do not skip same-team targets
if (frenzyT <= 0 && units[i].team == u.team) continue;
int ddx = (u.tx - units[i].tx) * 2, ddy = (u.ty - units[i].ty) * 2;
long d2 = (long)ddx * ddx + (long)ddy * ddy;
if (d2 > STATS[u.kind].rng2) continue;
@@ -566,6 +694,7 @@ static void planPath(int i, int gx, int gy)
static void unitKill(int i)
{
Unit &u = units[i];
playUnitDeath();
u.alive = false;
u.tgt = -1;
for (auto &o : units) if (o.tgt == i) o.tgt = -1;
@@ -587,12 +716,15 @@ static void fireAt(int si, int ti)
if (hit) {
addTracer(unitPx(si), unitPy(si), unitPx(ti), unitPy(ti), col, true);
t.hp -= STATS[s.kind].dmg;
playLaser();
playUnitHit();
Serial.printf("[combat] %c%d hits %c%d (%d hp left)\n",
s.team == TEAM_MARINE ? 'M' : 'D', si,
t.team == TEAM_MARINE ? 'M' : 'D', ti, t.hp > 0 ? t.hp : 0);
if (t.hp <= 0) unitKill(ti);
} else {
addTracer(unitPx(si), unitPy(si), unitPx(ti), unitPy(ti), col, false);
playLaser();
Serial.printf("[combat] %c%d misses %c%d\n",
s.team == TEAM_MARINE ? 'M' : 'D', si,
t.team == TEAM_MARINE ? 'M' : 'D', ti);
@@ -685,6 +817,7 @@ static void stepUnits()
// objective + wipe checks
if (u.kind == U_MARINE && u.tx == 34 && u.ty == 7) {
scenario = SC_WIN;
playBreachSuccess();
Serial.println("[objective] terminal reached — BREACH SUCCESS");
flashMsg("BREACH SUCCESS");
return;
@@ -693,6 +826,7 @@ static void stepUnits()
if (!units[0].alive && !units[1].alive && scenario == SC_LIVE) {
scenario = SC_LOSS;
playSquadKia();
Serial.println("[objective] squad wiped — SQUAD KIA");
flashMsg("SQUAD KIA");
}
@@ -795,8 +929,10 @@ static void registerClick()
if (walkable(tx, ty)) {
beaconTX = tx;
beaconTY = ty;
playBleep(1000, 30);
Serial.printf("[click] beacon -> tile %d,%d\n", tx, ty);
} else {
playBleep(200, 30); // blocked
Serial.println("[click] blocked tile: beacon ignored");
}
} else {
@@ -808,7 +944,8 @@ static void registerClick()
int d = dx * dx + dy * dy;
if (d < bestD) { bestD = d; best = i; }
}
if (bestD > 24 * 24) { flashMsg("NO NODE"); return; }
if (bestD > 24 * 24) { flashMsg("NO NODE"); playBleep(200, 30); return; }
playNodeSelect();
tryLink(best);
}
}
@@ -821,30 +958,43 @@ static void handleKey(char c)
switch (c) {
case ' ':
paused = !paused;
if (paused) playBleep(500, 20); // freeze engage
else playBleep(500, 20); // resume
Serial.printf("[key] tactical freeze %s\n", paused ? "ON" : "OFF");
break;
case 'p': case '\t':
viewMode = (viewMode == VM_CAMERAS) ? VM_NETWORK : VM_CAMERAS;
viewFlashUntil = millis() + 350;
if (viewMode == VM_CAMERAS) playBleep(600, 20);
else playBleep(400, 20);
Serial.printf("[key] view -> %s\n",
viewMode == VM_CAMERAS ? "CAMERAS" : "NETWORK");
break;
case '1': case '2':
if (heatT > 0) { flashMsg("OVERHEAT"); break; }
if (!nodeOnline[N_HIVE]) { flashMsg("NO HIVE LINK"); break; }
// FRENZY / BLIND payloads land in Milestone 4
Serial.printf("[key] daemon %c armed (effect lands in M4)\n", c);
flashMsg("M4 PENDING");
if (!nodeOnline[N_HIVE]) { flashMsg("NO HIVE LINK"); playBleep(200, 30); break; }
// FRENZY.EXE (1) or BLIND_OPTICS.SH (2) — land in Milestone 4
frenzyT = 300; // 6 seconds @ 50 ms tick; droids turn red & attack each other
if (c == '1') playBleep(800, 30); // FRENZY
else playBleep(1200, 30); // BLIND
Serial.printf("[key] frenzy %c armed (effect lands in M4)\n", c);
flashMsg("FRENZY ACTIVE");
break;
case 'x': {
if (heatT > 0) { flashMsg("OVERHEAT"); break; }
int li = hoverLink();
if (li >= 0) severLink(li);
else flashMsg("NO LINK HERE");
if (li >= 0) {
severLink(li);
playBleep(300, 30); // link severed
} else {
flashMsg("NO LINK HERE");
playBleep(200, 30); // no link
}
break;
}
case 'r':
Serial.println("[key] RESET");
playBleep(600, 30); // reset
resetScenario();
Serial.println("[reset] scenario re-armed (paused)");
break;
@@ -932,6 +1082,7 @@ static void applyTrackball()
static void stepSim()
{
simTick++;
if (frenzyT > 0) frenzyT--;
stepNetwork();
stepUnits();
}
@@ -1116,6 +1267,7 @@ static void renderBeacon()
}
// entity sprites + overhead HP bars (dimmed ghosting in Network view)
// Droids are rendered in red when FRENZY.EXE is active
static void renderUnits(bool full)
{
for (int i = 0; i < 7; i++) {
@@ -1130,7 +1282,7 @@ static void renderUnits(bool full)
body = nd::C_HOT;
line = nd::C_HUDBG;
} else {
body = nd::C_TRACE;
body = frenzyT > 0 && u.kind >= U_DROID && u.kind <= U_TURRET ? nd::C_HOT : nd::C_TRACE;
line = nd::C_HUDBG;
}
if (!full) { body = dim565(body); line = dim565(line); }
@@ -1397,6 +1549,8 @@ static void hardwareInit()
attachTrackball();
randomSeed(esp_random());
sound.begin();
}
void setup()
+14 -1
View File
@@ -11,7 +11,7 @@ milestone lands.
| M2 — Network Graph & Traces | 4-node sub-net in shared space (AIRLK→JUNC→DOOR/HIVE), animated link routing (1.5 s / 3.0 s ICE), door control, red trace → feedback spike + OVERHEAT, `X` sever, `R` reset | **done (emulator-verified)** |
| M3 — Squad vs. Droids | 2 marines (BFS to the player beacon, stop-and-fire), patrol/stationary droids, heavy droid + ceiling turret on the terminal, cover crates, tracers/HP bars, win/loss banners, reinforcement on feedback spike | **done (emulator-verified; firmware build fixed)** |
| M3 — Squad vs. Droids | Ship floorplan in Cameras view, 3 marines → beacon, 4 droids, gunfire | planned |
| M4 — Cyber-Physical Bridge | Hive link + `1` FRENZY.EXE turns droids on each other (shared coordinate space) | planned |
| M4 — Cyber-Physical Bridge | Hive link + `1` FRENZY.EXE turns droids on each other (shared coordinate space) | **done** |
## M0 (done)
@@ -134,6 +134,19 @@ squad through) completes in M4; until then the loss path + reset are the
verifiable branches. On-device check still pending (inherits the M1
checklist in §M1 above).
### M4 (done — Cyber-Physical Bridge)
Activating FRENZY.EXE via key `1` while a HIVE link is online corrupts droid IFF
targeting for 6 seconds. Infected droids turn red and shoot the nearest unit —
friend or foe — causing droids in the shared coordinate space to turn on each
other. This creates a tactical opening for the marines to cross open corridors
or press the advantage at the blast door. The frenzy timer decrements each
20 Hz tick and expires automatically.
<script kind of boundary: This effect is the M4 centerpiece: it exploits the
shared coordinate space so that a network link to the Droid Hive node directly
controls local droid behavior.
-->
### Headless test structure
Tests live in `emulator/tests/` (see its README): **unit** +
+222
View File
@@ -0,0 +1,222 @@
/**
* @file sound_engine.cpp
* @brief I2S speaker rendering task (8 kHz, 16-bit, mono).
*
* Based on the wiring used by examples/SimpleTone:
* BCK = GPIO7, WS = GPIO5, DOUT = GPIO6.
*
* Sounds are rendered strictly in queue order; layering is achieved by
* queueing several events back to back (e.g. a rumble sweep followed by a
* noise tail reads as one big explosion).
*/
#include "sound_engine.h"
#include "utilities.h"
#include <driver/i2s.h>
#define SND_SAMPLE_RATE 8000
#define SND_I2S_PORT I2S_NUM_0
#define SND_CHUNK 128 // samples per i2s_write call
#define SND_FADE_MS 8 // fade in/out to avoid clicks
bool SoundEngine::begin()
{
i2s_config_t cfg = {};
cfg.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX);
cfg.sample_rate = SND_SAMPLE_RATE;
cfg.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT;
cfg.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT;
cfg.communication_format = I2S_COMM_FORMAT_STAND_I2S;
cfg.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1;
cfg.dma_buf_count = 8;
cfg.dma_buf_len = 64;
if (i2s_driver_install(SND_I2S_PORT, &cfg, 0, NULL) != ESP_OK) {
return false;
}
i2s_pin_config_t pins = {};
pins.bck_io_num = BOARD_I2S_BCK;
pins.ws_io_num = BOARD_I2S_WS;
pins.data_out_num = BOARD_I2S_DOUT;
pins.data_in_num = I2S_PIN_NO_CHANGE;
i2s_set_pin(SND_I2S_PORT, &pins);
q_ = xQueueCreate(12, sizeof(SndEvent));
if (q_ == nullptr) {
return false;
}
// Render on core 0; the game loop runs on core 1.
return xTaskCreatePinnedToCore(trampoline, "sound", 4096, this, 5, nullptr, 0) == pdTRUE;
}
void SoundEngine::play(const SndEvent &e)
{
if (q_) {
xQueueSend(q_, &e, 0); // drop instead of blocking the game
}
}
void SoundEngine::trampoline(void *arg)
{
static_cast<SoundEngine *>(arg)->task();
}
void SoundEngine::task()
{
for (;;) {
SndEvent e;
xQueueReceive(q_, &e, portMAX_DELAY);
switch (e.type) {
case SND_TONE: renderTone(e.freq, e.dur, e.amp); break;
case SND_SWEEP: renderSweep(e.freq, e.freq2, e.dur, e.amp); break;
case SND_NOISE: renderNoise(e.dur, e.amp); break;
}
// After the LAST queued event the I2S TX DMA ring would keep
// replaying its remaining ~64 ms of buffer forever — heard as the
// sound's tail (rocket sweep, melody tone) repeating endlessly.
// Zero the ring once the queue is empty (not between queued events,
// which would punch silence-gaps into back-to-back melodies).
if (uxQueueMessagesWaiting(q_) == 0) {
i2s_zero_dma_buffer(SND_I2S_PORT);
}
}
}
void SoundEngine::volumeUp()
{
if (vol_ < VOL_MAX) vol_++;
}
void SoundEngine::volumeDown()
{
if (vol_ > 0) vol_--;
}
void SoundEngine::toggleMute()
{
if (vol_ > 0) {
lastVol_ = vol_;
vol_ = 0;
} else {
vol_ = lastVol_ > 0 ? lastVol_ : VOL_MAX / 2;
}
}
// Restore a saved volume level (from NVS at boot); 0 keeps the device muted
// while lastVol_ stays at its default so unmute still works.
void SoundEngine::setVolume(uint8_t v)
{
if (v > VOL_MAX) v = VOL_MAX;
vol_ = v;
if (vol_ > 0) lastVol_ = vol_;
}
// Scaled peak amplitude for the current volume level
static inline uint32_t scaledAmp(uint16_t amp, uint8_t vol)
{
return ((uint32_t)amp * vol) / SoundEngine::VOL_MAX;
}
// Fade envelope over the first/last SND_FADE_MS of the whole event
static inline uint32_t envelope(uint32_t pos, uint32_t total, uint32_t fade, uint32_t amp)
{
if (fade * 2 > total) fade = total / 2;
uint32_t s = amp;
if (pos < fade) s = s * pos / fade;
uint32_t tail = total - pos;
if (tail < fade) s = s * tail / fade;
return s;
}
void SoundEngine::renderTone(uint16_t freq, uint16_t durMs, uint16_t amp)
{
static int16_t buf[SND_CHUNK];
uint32_t a = scaledAmp(amp, vol_);
if (a == 0) return;
uint32_t total = (uint32_t)SND_SAMPLE_RATE * durMs / 1000;
if (total == 0) return;
uint32_t half = (freq > 0) ? (SND_SAMPLE_RATE / 2) / freq : 1;
if (half == 0) half = 1;
uint32_t fade = (uint32_t)SND_SAMPLE_RATE * SND_FADE_MS / 1000;
if (fade < 2) fade = 2;
uint32_t phase = 0;
for (uint32_t i = 0; i < total; ) {
uint32_t n = (total - i < SND_CHUNK) ? (total - i) : SND_CHUNK;
for (uint32_t k = 0; k < n; k++) {
int32_t s = ((phase / half) & 1) ? (int32_t)a : -(int32_t)a;
buf[k] = (int16_t)(s * (int32_t)envelope(i + k, total, fade, 256) / 256);
phase++;
}
size_t bw;
i2s_write(SND_I2S_PORT, buf, n * sizeof(int16_t), &bw, portMAX_DELAY);
i += n;
}
}
// Square wave gliding from freq0 to freq1 (Hz) over the duration.
// Phase is carried in a float cycle counter (0..1) so frequency changes
// never click.
void SoundEngine::renderSweep(uint16_t freq0, uint16_t freq1, uint16_t durMs, uint16_t amp)
{
static int16_t buf[SND_CHUNK];
uint32_t a = scaledAmp(amp, vol_);
if (a == 0) return;
uint32_t total = (uint32_t)SND_SAMPLE_RATE * durMs / 1000;
if (total == 0) return;
uint32_t fade = (uint32_t)SND_SAMPLE_RATE * SND_FADE_MS / 1000;
if (fade < 2) fade = 2;
float phase = 0.0f;
for (uint32_t i = 0; i < total; ) {
uint32_t n = (total - i < SND_CHUNK) ? (total - i) : SND_CHUNK;
for (uint32_t k = 0; k < n; k++) {
uint32_t pos = i + k;
float f = (float)freq0 +
((float)(int16_t)(freq1 - freq0) * (float)pos) / (float)total;
if (f < 20.0f) f = 20.0f;
phase += f / (float)SND_SAMPLE_RATE;
if (phase >= 1.0f) phase -= 1.0f;
int32_t s = (phase < 0.5f) ? (int32_t)a : -(int32_t)a;
buf[k] = (int16_t)(s * (int32_t)envelope(pos, total, fade, 256) / 256);
}
size_t bw;
i2s_write(SND_I2S_PORT, buf, n * sizeof(int16_t), &bw, portMAX_DELAY);
i += n;
}
}
void SoundEngine::renderNoise(uint16_t durMs, uint16_t amp)
{
static int16_t buf[SND_CHUNK];
uint32_t a = scaledAmp(amp, vol_);
if (a == 0) return;
uint32_t total = (uint32_t)SND_SAMPLE_RATE * durMs / 1000;
if (total == 0) return;
uint32_t seed = esp_random() | 1;
for (uint32_t i = 0; i < total; ) {
uint32_t n = (total - i < SND_CHUNK) ? (total - i) : SND_CHUNK;
for (uint32_t k = 0; k < n; k++) {
// xorshift32 for cheap white noise
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
int32_t signedS = (int32_t)(seed & 0xFFFF) - 32768;
// linear decay over the burst
int32_t s = (int32_t)(((int64_t)signedS * a * (int64_t)(total - i - k)) /
((int64_t)32768 * (int64_t)total));
buf[k] = (int16_t)s;
}
size_t bw;
i2s_write(SND_I2S_PORT, buf, n * sizeof(int16_t), &bw, portMAX_DELAY);
i += n;
}
}
+55
View File
@@ -0,0 +1,55 @@
/**
* @file sound_engine.h
* @brief Tiny non-blocking I2S sound engine for the T-Deck speaker.
*
* A FreeRTOS task owns the I2S peripheral (speaker, I2S_NUM_0) and renders
* queued sound events one after another. The game only ever pushes events,
* so it never blocks. Event types:
*
* SND_TONE fixed square-wave beep
* SND_SWEEP square wave gliding from freq down/up to freq2 (sirens, booms)
* SND_NOISE white-noise burst with linear decay (explosions)
*/
#pragma once
#include <Arduino.h>
enum SndType : uint8_t {
SND_TONE = 0, // fixed square wave
SND_SWEEP, // square wave gliding freq -> freq2
SND_NOISE, // white noise burst
};
struct SndEvent {
SndType type;
uint16_t freq; // Hz (tone, or sweep start)
uint16_t freq2; // Hz (sweep end; ignored for tone/noise)
uint16_t dur; // duration in ms
uint16_t amp; // peak amplitude 0..32767
};
class SoundEngine {
public:
static const uint8_t VOL_MAX = 8;
bool begin();
void play(const SndEvent &e);
// Master volume, applied to every rendered sound
void volumeUp();
void volumeDown();
void toggleMute();
void setVolume(uint8_t v); // restore a saved level (0 = muted)
uint8_t volume() const { return vol_; }
private:
static void trampoline(void *arg);
void task();
void renderTone(uint16_t freq, uint16_t durMs, uint16_t amp);
void renderSweep(uint16_t freq0, uint16_t freq1, uint16_t durMs, uint16_t amp);
void renderNoise(uint16_t durMs, uint16_t amp);
QueueHandle_t q_ = nullptr;
uint8_t vol_ = 5; // default: moderate
uint8_t lastVol_ = 5; // remembered for mute toggle
};