Rename Lotus3 to MiataDrive; original-graphics title screen
- examples/Lotus3 -> examples/MiataDrive, sketch MiataDrive.ino, emulator target APP=MiataDrive, platformio src_dir updated - drop the borrowed photo title background (title_bg.h): the title screen now renders the game's own start line under the arch with the selected car parked on the road; color picker labels sit over the horizon, showcase car doubles as the live preview - add dedicated README (controls, features, sprite pipeline, gallery) - commit in-progress work the game now depends on: sound engine events (engine hum, crash noise) plus the 4-line SDL audio shim in the emulator host
This commit is contained in:
@@ -23,6 +23,9 @@ endif
|
||||
ifeq ($(APP),Lotus3)
|
||||
APP_TITLE := Lotus 3
|
||||
DEFS += -DEMU_APP_LOTUS3
|
||||
ifdef AUTOPLAY
|
||||
DEFS += -DAUTOPLAY
|
||||
endif
|
||||
endif
|
||||
APP_TITLE ?= $(APP)
|
||||
|
||||
|
||||
@@ -22,6 +22,9 @@
|
||||
#ifndef APP_INO
|
||||
#define APP_INO "MissileCommand.ino"
|
||||
#endif
|
||||
|
||||
// emulator-side autoplay request (consumed by sketches that support it)
|
||||
bool emuAutoplay = false;
|
||||
#ifndef APP_NAME
|
||||
#define APP_NAME "T-Deck app"
|
||||
#endif
|
||||
@@ -82,6 +85,7 @@ int main(int argc, char **argv)
|
||||
else if (!strcmp(argv[i], "--dump-interval") && i + 1 < argc) dumpEvery = atoi(argv[++i]);
|
||||
else if (!strcmp(argv[i], "--type") && i + 1 < argc) typeStr = argv[++i];
|
||||
else if (!strcmp(argv[i], "--type-at") && i + 1 < argc) typeFromFrame = atoi(argv[++i]);
|
||||
else if (!strcmp(argv[i], "--autoplay")) { emuAutoplay = true; }
|
||||
#ifdef EMU_APP_MISSILECOMMAND
|
||||
else if (!strcmp(argv[i], "--wave") && i + 1 < argc) emuStartWaveRequest = atoi(argv[++i]);
|
||||
else if (!strcmp(argv[i], "--autoplay")) autoplay = true;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* @file Lotus3.ino
|
||||
* @brief Lotus Turbo Challenge style pseudo-3D racer for LilyGo T-Deck.
|
||||
* @file MiataDrive.ino
|
||||
* @brief MiataDrive - Lotus Turbo Challenge style pseudo-3D racer for LilyGo T-Deck.
|
||||
*
|
||||
* Classic segment-based pseudo-3D road: track = list of (curve, hill)
|
||||
* segments projected with perspective. Road is drawn near->far with rumble
|
||||
@@ -20,10 +20,11 @@
|
||||
#include <Wire.h>
|
||||
#include <math.h>
|
||||
#include "utilities.h"
|
||||
#include "title_bg.h"
|
||||
#include "sprites.h"
|
||||
#include "sound_engine.h"
|
||||
|
||||
TFT_eSPI tft;
|
||||
SoundEngine sound;
|
||||
|
||||
static int scrW, scrH;
|
||||
|
||||
@@ -64,9 +65,16 @@ static Segment segments[MAX_SEGS];
|
||||
static int segCount = 0;
|
||||
static float trackLen = 0;
|
||||
|
||||
enum { SID_PLAYER = 0, SID_CAR_BLUE, SID_CAR_DARK, SID_CAR_YELLOW,
|
||||
SID_PALM, SID_PINE, SID_BUSH, SID_BILLBOARD, SID_ARCH, SID_TIRES,
|
||||
SID_CRASH_A, SID_CRASH_B, SID_CRASH_C };
|
||||
// player views per color: 0 rear, 1 slight-turn, 2 turn, 3 side
|
||||
enum { PV_REAR = 0, PV_SLIGHT, PV_TURN, PV_SIDE };
|
||||
enum { SID_PLAYER_RED = 0, SID_PLAYER_BLUE = 4, SID_PLAYER_WHITE = 8, SID_PLAYER_YELLOW = 12,
|
||||
SID_PALM = 16, SID_PINE, SID_BUSH, SID_BILLBOARD, SID_ARCH, SID_TIRES,
|
||||
SID_CAR_BLUE, SID_CAR_BLUE_T, SID_CAR_WHITE, SID_CAR_WHITE_T,
|
||||
SID_CAR_YELLOW, SID_CAR_YELLOW_T };
|
||||
|
||||
enum PlayerColor { PC_RED = 0, PC_BLUE = 1, PC_WHITE = 2, PC_YELLOW = 3 };
|
||||
static int playerColor = PC_RED;
|
||||
static inline int playerSprite(int view) { return playerColor * 4 + view; }
|
||||
|
||||
static float lastY() { return segCount ? segments[segCount - 1].y2 : 0.0f; }
|
||||
|
||||
@@ -122,7 +130,7 @@ static void buildTrack() {
|
||||
addRoad(25, 35, 25, 3, 0); // S bends
|
||||
addRoad(25, 35, 25, -3, 0);
|
||||
addRoad(40, 70, 40, 5, 20); // long right sweeper, uphill
|
||||
addRoad(30, 30, 30, 0, -40); // downhill straight
|
||||
addRoad(30, 30, 30, 0, -6); // downhill straight (tuned to close the elevation loop)
|
||||
addRoad(30, 60, 30, -4, 0); // long left
|
||||
addRoad(20, 20, 20, 6, 0); // tight right
|
||||
addRoad(40, 40, 40, 0, 0); // finish straight
|
||||
@@ -143,7 +151,7 @@ static void buildTrack() {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Game state
|
||||
// ---------------------------------------------------------------------------
|
||||
enum GameState { ST_TITLE, ST_PLAYING, ST_CRASH, ST_GAMEOVER, ST_WIN };
|
||||
enum GameState { ST_TITLE, ST_PLAYING, ST_CRASH, ST_GAMEOVER, ST_WIN, ST_SPRITES };
|
||||
static GameState gameState = ST_TITLE;
|
||||
static uint32_t stateT0 = 0;
|
||||
static uint32_t nextFrame = 0;
|
||||
@@ -154,7 +162,29 @@ static float speed_ = 0;
|
||||
static float timeLeft = LAP_TIME;
|
||||
static int lap = 0;
|
||||
static int score = 0;
|
||||
static bool autoPlay = false; // player drives by default (P toggles demo)
|
||||
static bool autoPlay =
|
||||
#ifdef AUTOPLAY
|
||||
true;
|
||||
#else
|
||||
false;
|
||||
#endif
|
||||
;
|
||||
|
||||
// sound cooldowns
|
||||
static uint32_t sndAccelT = 0;
|
||||
#ifdef EMULATOR
|
||||
extern bool emuAutoplay;
|
||||
#endif
|
||||
static uint32_t sndSkidT = 0;
|
||||
// steering click tracking for skid trigger
|
||||
static uint32_t turnClickT = 0;
|
||||
static int turnClicks = 0;
|
||||
static void registerTurn() {
|
||||
uint32_t now = millis();
|
||||
if (now - turnClickT > 350) turnClicks = 0;
|
||||
turnClicks++;
|
||||
turnClickT = now;
|
||||
}
|
||||
|
||||
// crash / rollover
|
||||
static uint32_t crashT0 = 0;
|
||||
@@ -162,7 +192,7 @@ static int crashDir = 1; // slide direction off the road
|
||||
static float crashVel = 0; // sliding speed during the tumble
|
||||
static uint32_t shakeUntil = 0; // camera jolt
|
||||
|
||||
struct TrafficCar { float z, offset, speed; int sprite; };
|
||||
struct TrafficCar { float z, offset, speed; int sprite, spriteTurn; };
|
||||
static const int N_CARS = 8;
|
||||
static TrafficCar cars[N_CARS];
|
||||
|
||||
@@ -276,7 +306,7 @@ static void fillTrap(float y1, float xa1, float xb1, float y2, float xa2, float
|
||||
}
|
||||
|
||||
// scaled sprite, bottom-center anchor, rows below clipY are cut (hill occlusion)
|
||||
static void drawSprite(int id, int destW, float sx, float bottomY, float clipY) {
|
||||
static void drawSprite(int id, int destW, float sx, float bottomY, float clipY, bool flip = false) {
|
||||
const GameSprite &sp = SPRITES[id];
|
||||
if (destW < 1) return;
|
||||
int dw = destW;
|
||||
@@ -292,7 +322,7 @@ static void drawSprite(int id, int destW, float sx, float bottomY, float clipY)
|
||||
const uint16_t *row = sp.data + (y * sp.h / dh) * sp.w;
|
||||
int lastC = -2, runStart = 0;
|
||||
for (int x = 0; x <= dw; x++) {
|
||||
uint16_t c = (x < dw) ? row[x * sp.w / dw] : (uint16_t)0;
|
||||
uint16_t c = (x < dw) ? row[(flip ? (dw - 1 - x) : x) * sp.w / dw] : (uint16_t)0;
|
||||
bool trans = (x == dw) || (c == SPR_TRANSP);
|
||||
if (!trans) {
|
||||
if (c != lastC) {
|
||||
@@ -353,11 +383,23 @@ static void renderRoad() {
|
||||
float z1 = idx * (float)SEG_LEN - camZ;
|
||||
float z2 = z1 + SEG_LEN;
|
||||
|
||||
// clamp near plane so the road reaches the bottom of the screen
|
||||
// (avoids a gap where the camera's own segment is skipped)
|
||||
float z1p = z1;
|
||||
float xn = x;
|
||||
const float NEAR_Z = CAM_D * 30.0f;
|
||||
if (z1p < NEAR_Z) {
|
||||
float frac = (NEAR_Z - z1) / SEG_LEN;
|
||||
if (frac > 1.0f) frac = 1.0f;
|
||||
z1p = NEAR_Z;
|
||||
xn = x + dx * frac;
|
||||
}
|
||||
|
||||
// project p1/p2 (curve accumulated into camera x)
|
||||
float s1 = CAM_D / z1;
|
||||
float s1 = CAM_D / z1p;
|
||||
float s2 = CAM_D / z2;
|
||||
P1[n].x = scrW / 2.0f + s1 * (0 - (camX - x)) * scrW / 2.0f;
|
||||
P1[n].y = HORIZON_Y - s1 * (seg.y1 - camY) * scrH / 2.0f;
|
||||
P1[n].x = scrW / 2.0f + s1 * (0 - (camX - xn)) * scrW / 2.0f;
|
||||
P1[n].y = HORIZON_Y - s1 * (seg.y1 + (seg.y2 - seg.y1) * ((z1p - z1) / SEG_LEN) - camY) * scrH / 2.0f;
|
||||
P1[n].w = s1 * ROAD_W * scrW / 2.0f;
|
||||
float x2 = x + dx; // p2 camera x offset (curve)
|
||||
float camX2 = camX - x2;
|
||||
@@ -367,12 +409,12 @@ static void renderRoad() {
|
||||
|
||||
seg.clip = maxY;
|
||||
segIdxN[n] = idx;
|
||||
slotValid[n] = (z1 > CAM_D * 30.0f) && (z1 < DRAW_DIST * SEG_LEN * 2.0f);
|
||||
slotValid[n] = (z1 > NEAR_Z) && (z1 < DRAW_DIST * SEG_LEN * 2.0f);
|
||||
|
||||
x += dx;
|
||||
dx += seg.curve;
|
||||
|
||||
if (z1 <= CAM_D * 30.0f) continue; // at/behind camera
|
||||
if (z2 <= NEAR_Z) continue; // fully behind camera
|
||||
if (P2[n].y >= maxY || P2[n].y >= P1[n].y) continue; // hidden or backfacing
|
||||
|
||||
int fog = 0;
|
||||
@@ -445,7 +487,10 @@ static void renderSprites() {
|
||||
float sx = pr.x + (pn.x - pr.x) * percent + cars[c].offset * pr.w;
|
||||
float sy = pr.y + (pn.y - pr.y) * percent;
|
||||
float w = pr.w + (pn.w - pr.w) * percent;
|
||||
drawSprite(cars[c].sprite, iround(w * 0.48f), sx, sy, seg.clip);
|
||||
// lean into corners: turning 3/4 view, mirrored on right-hand curves
|
||||
float cv = segments[idx].curve;
|
||||
int sid = (fabsf(cv) > 1.5f) ? cars[c].spriteTurn : cars[c].sprite;
|
||||
drawSprite(sid, iround(w * 0.48f), sx, sy, seg.clip, cv > 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -456,12 +501,38 @@ static void drawPlayerCar() {
|
||||
float bounce = (float)(random(3) - 1) * speedPct * 1.0f;
|
||||
float cx = scrW / 2.0f + steerInput * 5.0f;
|
||||
int baseY = scrH - 3 + (int)bounce;
|
||||
|
||||
// dirt rushing from the rear wheels while accelerating
|
||||
if (gasFrame > 0 && speed_ > MAX_SPEED * 0.15f) {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
int side = (i < 5) ? -1 : 1;
|
||||
int dx0 = iround(cx) + side * (14 + (int)random(6));
|
||||
int dy0 = baseY - 2 - (int)random(14);
|
||||
int r = 1 + (int)random(3);
|
||||
uint8_t g = 110 + (uint8_t)random(60);
|
||||
tft.fillCircle(dx0, dy0, r, C(g, g - 20, g - 40));
|
||||
}
|
||||
// skid-like streaks when launching hard
|
||||
if (speedPct < 0.4f) {
|
||||
for (int i = 0; i < 4; i++) {
|
||||
int side = (i < 2) ? -1 : 1;
|
||||
int x0 = iround(cx) + side * 16;
|
||||
tft.drawFastVLine(x0, baseY - 18, 12, C(150, 140, 120));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// contact shadow -> plants the car on the road
|
||||
for (int dy = 0; dy < 5; dy++) {
|
||||
int wdt = CAR_W - 6 - dy * 7;
|
||||
if (wdt > 0) tft.drawFastHLine(scrW / 2 - wdt / 2, baseY + dy, wdt, C(30, 30, 26));
|
||||
}
|
||||
drawSprite(SID_PLAYER, CAR_W, cx, baseY, scrH);
|
||||
float ta = fabsf(steerInput);
|
||||
int view = PV_REAR;
|
||||
if (ta > 0.75f) view = PV_TURN;
|
||||
else if (ta > 0.30f) view = PV_SLIGHT;
|
||||
bool flip = steerInput > 0; // sheet views face nose-left; mirror for right turns
|
||||
drawSprite(playerSprite(view), CAR_W, cx, baseY, scrH, flip);
|
||||
}
|
||||
|
||||
// rollover animation: spare car sprites tumbling off the road
|
||||
@@ -469,13 +540,13 @@ static void drawCrashCar() {
|
||||
uint32_t t = millis() - crashT0;
|
||||
const float DUR = 2300.0f;
|
||||
float p = t / DUR; if (p > 1) p = 1;
|
||||
// sprite sequence: rear -> 3/4 -> side -> other side (rolling over)
|
||||
// sprite sequence: rear -> slight -> turn -> side (rolling over)
|
||||
int id;
|
||||
if (t < 260) {
|
||||
id = SID_PLAYER;
|
||||
id = playerSprite(PV_REAR);
|
||||
} else {
|
||||
int f = ((t - 260) / 140) % 3;
|
||||
id = (f == 0) ? SID_CRASH_A : (f == 1) ? SID_CRASH_B : SID_CRASH_C;
|
||||
id = playerSprite(PV_SLIGHT + f);
|
||||
}
|
||||
float cx = scrW / 2.0f + crashDir * p * 46.0f;
|
||||
if (t < 650) cx += (float)(random(7) - 3); // whiplash shake
|
||||
@@ -488,7 +559,7 @@ static void drawCrashCar() {
|
||||
int dy0 = baseY - (int)random(10);
|
||||
tft.fillCircle(dx0, dy0, 1 + (int)random(2), C(150, 140, 120));
|
||||
}
|
||||
drawSprite(id, w, cx, baseY, scrH);
|
||||
drawSprite(id, w, cx, baseY, scrH, crashDir > 0);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -518,14 +589,20 @@ static void placeTraffic() {
|
||||
cars[i].z = (float)random((long)trackLen);
|
||||
cars[i].offset = lane[i % 3];
|
||||
cars[i].speed = MAX_SPEED * (0.25f + (float)random(30) / 100.0f);
|
||||
cars[i].sprite = (i % 3 == 0) ? SID_CAR_BLUE : (i % 3 == 1) ? SID_CAR_DARK : SID_CAR_YELLOW;
|
||||
static const int carSets[3][2] = {
|
||||
{ SID_CAR_BLUE, SID_CAR_BLUE_T },
|
||||
{ SID_CAR_WHITE, SID_CAR_WHITE_T },
|
||||
{ SID_CAR_YELLOW, SID_CAR_YELLOW_T },
|
||||
};
|
||||
cars[i].sprite = carSets[i % 3][0];
|
||||
cars[i].spriteTurn = carSets[i % 3][1];
|
||||
}
|
||||
}
|
||||
|
||||
static void startGame() {
|
||||
position_ = 0; playerX = 0; speed_ = 0;
|
||||
timeLeft = LAP_TIME; lap = 0; score = 0;
|
||||
steerInput = 0; gasLatch = 1; brakeUntil = 0; // auto-gas: throttle by default
|
||||
steerInput = 0; gasLatch = 0; brakeUntil = 0; // manual gas by default (no auto-throttle)
|
||||
placeTraffic();
|
||||
gameState = ST_PLAYING;
|
||||
stateT0 = millis();
|
||||
@@ -537,7 +614,26 @@ static void updateGame(float dt) {
|
||||
int baseIdx = ((int)(position_ / SEG_LEN)) % segCount;
|
||||
const Segment &baseSeg = segments[baseIdx];
|
||||
float speedPct = speed_ / MAX_SPEED;
|
||||
float dx = dt * 2.4f * speedPct; // steer authority grows with speed
|
||||
|
||||
// --- sound triggers ---
|
||||
uint32_t now = millis();
|
||||
// continuous engine hum: frequency tracks speed (keep queue short for snappy SFX)
|
||||
if (speed_ > 10.0f && sound.pending() < 2 && (int32_t)(now - sndAccelT) >= 100) {
|
||||
sndAccelT = now;
|
||||
int f = 70 + (int)(speedPct * 170.0f);
|
||||
uint16_t amp = gasFrame > 0 ? 7000 : 4500;
|
||||
SndEvent e = { SND_TONE, (uint16_t)f, 0, 120, amp };
|
||||
sound.play(e);
|
||||
}
|
||||
bool skid = (turnClicks >= 3) && (fabsf(steerInput) > 0.55f) && (speedPct > 0.45f);
|
||||
if (skid && (int32_t)(now - sndSkidT) >= 600) {
|
||||
sndSkidT = now;
|
||||
turnClicks = 0;
|
||||
sound.clear();
|
||||
SndEvent e = { SND_SWEEP, 900, 300, 120, 9000 };
|
||||
sound.play(e);
|
||||
}
|
||||
float dx = dt * 2.4f * (speedPct > 0.18f ? speedPct : 0.18f); // steer authority grows with speed (min so steering works at low speed)
|
||||
|
||||
if (autoPlay) {
|
||||
// AI: aim inside of upcoming curve, dodge traffic
|
||||
@@ -556,7 +652,7 @@ static void updateGame(float dt) {
|
||||
float maxA = (fabsf(aheadCurve) > 9.0f) ? 0.6f : 1.0f;
|
||||
speed_ += (speed_ < MAX_SPEED * maxA) ? ACCEL * dt : DECEL * dt;
|
||||
} else {
|
||||
playerX += dx * steerInput;
|
||||
playerX += dx * steerInput * 1.8f;
|
||||
if (gasFrame > 0) speed_ += ACCEL * dt;
|
||||
else if (gasFrame < 0) speed_ += BRAKE * dt;
|
||||
else speed_ += DECEL * dt;
|
||||
@@ -578,6 +674,10 @@ static void updateGame(float dt) {
|
||||
score -= 300; if (score < 0) score = 0;
|
||||
speed_ = 0;
|
||||
gameState = ST_CRASH;
|
||||
// crash sound (clear queued hum so it plays immediately)
|
||||
sound.clear();
|
||||
{ SndEvent e = { SND_NOISE, 0, 0, 260, 22000 }; sound.play(e);
|
||||
SndEvent f = { SND_SWEEP, 400, 80, 220, 14000 }; sound.play(f); }
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -605,6 +705,7 @@ static void updateGame(float dt) {
|
||||
position_ = cars[c].z - SEG_LEN * 1.2f;
|
||||
if (position_ < 0) position_ += trackLen;
|
||||
shakeUntil = millis() + 250; // jolt on rear-ending traffic
|
||||
{ SndEvent e = { SND_NOISE, 0, 0, 120, 12000 }; sound.play(e); }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -631,20 +732,89 @@ static void updateCrash(float dt) {
|
||||
// Screens
|
||||
// ---------------------------------------------------------------------------
|
||||
static void drawTitle() {
|
||||
for (int y = 0; y < scrH; y++)
|
||||
for (int x = 0; x < scrW; x++)
|
||||
tft.drawPixel(x, y, titleBg[y * scrW + x]);
|
||||
// backdrop is our own scene: the start line under the arch
|
||||
position_ = 0; playerX = 0; speed_ = 0;
|
||||
renderRoad();
|
||||
renderSprites();
|
||||
|
||||
tft.setTextDatum(MC_DATUM);
|
||||
tft.setFreeFont(&FreeSansBold24pt7b);
|
||||
tft.setTextColor(TFT_YELLOW, C(0,0,0));
|
||||
tft.drawString("MIATA RACING", scrW / 2, 42);
|
||||
tft.setTextColor(TFT_YELLOW, C(15,15,18));
|
||||
tft.drawString("MIATADRIVE", scrW / 2, 14);
|
||||
tft.setFreeFont(nullptr);
|
||||
tft.setTextFont(2);
|
||||
tft.setTextColor(TFT_WHITE, C(0,0,0));
|
||||
tft.drawString("Arrows / ball: gas, brake, steer", scrW / 2, 104);
|
||||
tft.drawString("W gas S brake A/D steer P auto", scrW / 2, 124);
|
||||
tft.setTextColor(TFT_GOLD, C(0,0,0));
|
||||
tft.drawString("Press / tap to race", scrW / 2, 168);
|
||||
tft.setTextColor(TFT_WHITE, C(15,15,18));
|
||||
tft.drawString("W gas S brake A/D steer", scrW / 2, 60);
|
||||
tft.drawString("P auto T sprites Press/tap: race", scrW / 2, 78);
|
||||
// car color picker: 1 Red 2 Blue 3 White 4 Yellow
|
||||
static const char* names[4] = { "1 Red", "2 Blue", "3 White", "4 Yellow" };
|
||||
uint16_t pal[4] = { C(220,40,40), C(60,90,220), C(235,235,235), C(240,200,40) };
|
||||
for (int i = 0; i < 4; i++) {
|
||||
tft.setTextColor(i == playerColor ? pal[i] : C(200,200,200), C(15,15,18));
|
||||
tft.setTextDatum(TC_DATUM);
|
||||
tft.drawString(names[i], 46 + i * 76, 102);
|
||||
if (i == playerColor) {
|
||||
tft.setTextColor(TFT_WHITE, C(15,15,18));
|
||||
tft.drawString("^", 46 + i * 76, 118);
|
||||
}
|
||||
}
|
||||
tft.setTextDatum(TL_DATUM);
|
||||
// showcase the selected car, parked on the road below the arch
|
||||
drawSprite(playerSprite(PV_REAR), 110, scrW / 2, scrH - 4, scrH);
|
||||
}
|
||||
|
||||
// sprite test gallery: every SPRITES[] entry at native size on a checkerboard,
|
||||
// bottom-center anchored like in-game, labeled with index + crop size
|
||||
static int spritePage = 0;
|
||||
|
||||
static void drawSpriteTest() {
|
||||
// checker background
|
||||
for (int by = 0; by < scrH; by += 8)
|
||||
for (int bx = 0; bx < scrW; bx += 8) {
|
||||
uint16_t c = (((bx / 8) + (by / 8)) & 1) ? C(70,70,74) : C(135,135,138);
|
||||
tft.fillRect(bx, by, 8, 8, c);
|
||||
}
|
||||
|
||||
// build list of sprite ids for this page
|
||||
int ids[12]; int nids = 0;
|
||||
if (spritePage < 4) {
|
||||
int color = spritePage; // 0..3
|
||||
ids[nids++] = color * 4 + PV_REAR;
|
||||
ids[nids++] = color * 4 + PV_SLIGHT;
|
||||
ids[nids++] = color * 4 + PV_TURN;
|
||||
} else if (spritePage == 4) {
|
||||
int arr[] = { SPR_CAR_BLUE, SPR_CAR_BLUE_T, SPR_CAR_WHITE, SPR_CAR_WHITE_T, SPR_CAR_YELLOW, SPR_CAR_YELLOW_T };
|
||||
for (int i = 0; i < 6; i++) ids[nids++] = arr[i];
|
||||
} else {
|
||||
int arr[] = { SPR_PALM, SPR_PINE, SPR_BUSH, SPR_BILLBOARD, SPR_ARCH, SPR_TIRES };
|
||||
for (int i = 0; i < 6; i++) ids[nids++] = arr[i];
|
||||
}
|
||||
|
||||
const int CELL_W = 96, CELL_H = 96;
|
||||
int cols = 3;
|
||||
for (int i = 0; i < nids; i++) {
|
||||
int col = i % cols, row = i / cols;
|
||||
int cx0 = col * CELL_W + 8, cy0 = row * CELL_H + 24;
|
||||
tft.drawRect(cx0, cy0, CELL_W, CELL_H, C(20,20,24));
|
||||
const GameSprite &sp = SPRITES[ids[i]];
|
||||
int destW = sp.w <= CELL_W - 8 ? sp.w : CELL_W - 8;
|
||||
if (destW * sp.h / sp.w > CELL_H - 16) destW = (CELL_H - 16) * sp.w / sp.h;
|
||||
drawSprite(ids[i], destW, cx0 + CELL_W / 2, cy0 + CELL_H - 8, scrH);
|
||||
tft.fillCircle(cx0 + CELL_W / 2, cy0 + CELL_H - 8, 1, TFT_MAGENTA);
|
||||
char buf[24];
|
||||
snprintf(buf, sizeof(buf), "%d %dx%d", ids[i], sp.w, sp.h);
|
||||
tft.setTextDatum(TL_DATUM);
|
||||
tft.setTextFont(1);
|
||||
tft.setTextColor(TFT_YELLOW, C(20,20,24));
|
||||
tft.drawString(buf, cx0 + 2, cy0 + 2);
|
||||
}
|
||||
tft.setTextFont(2);
|
||||
tft.setTextColor(TFT_WHITE, C(20,20,24));
|
||||
tft.setTextDatum(TC_DATUM);
|
||||
char title[48];
|
||||
const char* names[] = { "Car 1", "Car 2", "Car 3", "Car 4", "Traffic cars", "Props" };
|
||||
snprintf(title, sizeof(title), "Page %d/6: %s (A/D flip, T back)", spritePage + 1, names[spritePage]);
|
||||
tft.drawString(title, scrW / 2, 0);
|
||||
tft.setTextDatum(TL_DATUM);
|
||||
}
|
||||
|
||||
@@ -668,6 +838,7 @@ static void drawEndScreen(bool win) {
|
||||
static void render() {
|
||||
switch (gameState) {
|
||||
case ST_TITLE: drawTitle(); break;
|
||||
case ST_SPRITES: drawSpriteTest(); break;
|
||||
case ST_GAMEOVER: drawEndScreen(false); break;
|
||||
case ST_WIN: drawEndScreen(true); break;
|
||||
default:
|
||||
@@ -694,9 +865,23 @@ static void pollKeyboard() {
|
||||
switch (c) {
|
||||
case 'w': gasLatch = 1; break;
|
||||
case 's': brakeUntil = millis() + 500; gasLatch = 0; break;
|
||||
case 'a': steerInput -= 0.5f; break;
|
||||
case 'd': steerInput += 0.5f; break;
|
||||
case 'a':
|
||||
if (gameState == ST_SPRITES) { spritePage = (spritePage + 5) % 6; }
|
||||
else { steerInput -= 0.8f; registerTurn(); }
|
||||
break;
|
||||
case 'd':
|
||||
if (gameState == ST_SPRITES) { spritePage = (spritePage + 1) % 6; }
|
||||
else { steerInput += 0.8f; registerTurn(); }
|
||||
break;
|
||||
case 'p': autoPlay = !autoPlay; break;
|
||||
case '1': playerColor = PC_RED; if (gameState == ST_TITLE) drawTitle(); break;
|
||||
case '2': playerColor = PC_BLUE; if (gameState == ST_TITLE) drawTitle(); break;
|
||||
case '3': playerColor = PC_WHITE; if (gameState == ST_TITLE) drawTitle(); break;
|
||||
case '4': playerColor = PC_YELLOW; if (gameState == ST_TITLE) drawTitle(); break;
|
||||
case 't':
|
||||
if (gameState == ST_SPRITES) { gameState = ST_TITLE; stateT0 = millis(); }
|
||||
else gameState = ST_SPRITES;
|
||||
break;
|
||||
case ' ': case 'r':
|
||||
if (gameState == ST_TITLE) startGame();
|
||||
else if (gameState == ST_GAMEOVER || gameState == ST_WIN) { gameState = ST_TITLE; stateT0 = millis(); }
|
||||
@@ -736,6 +921,11 @@ void setup() {
|
||||
scrH = tft.height();
|
||||
buildPalette();
|
||||
buildTrack();
|
||||
if (!sound.begin()) Serial.println("Sound engine init failed");
|
||||
sound.setVolume(5);
|
||||
#ifdef EMULATOR
|
||||
if (emuAutoplay) autoPlay = true;
|
||||
#endif
|
||||
drawTitle();
|
||||
}
|
||||
|
||||
@@ -765,8 +955,8 @@ void loop() {
|
||||
if ((int32_t)(now - brakeUntil) < 0) gasFrame = -1;
|
||||
|
||||
if (gameState == ST_PLAYING && !autoPlay) {
|
||||
if (pxX) steerInput += (pxX > 0 ? 1 : -1) * 0.09f * (1 + (pxX > 3 ? 1 : 0));
|
||||
steerInput *= 0.92f; // auto-center
|
||||
if (pxX) { steerInput += (pxX > 0 ? 1 : -1) * 0.15f * (1 + (pxX > 3 ? 1 : 0)); registerTurn(); }
|
||||
else steerInput *= 0.90f; // auto-center only when not steering
|
||||
steerInput = clampf(steerInput, -1, 1);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
# MiataDrive
|
||||
|
||||
A Lotus Turbo Challenge–style pseudo-3D racing game for the LilyGo T-Deck
|
||||
(ESP32-S3, 320×240). Drive a Mazda MX-5 through a 3-lap circuit against
|
||||
traffic before the clock runs out.
|
||||
|
||||

|
||||
|
||||
## Running
|
||||
|
||||
### On your PC (SDL2 emulator)
|
||||
|
||||
```sh
|
||||
cd emulator
|
||||
make run APP=MiataDrive
|
||||
```
|
||||
|
||||
Headless smoke test (N frames, dump the last frame as a BMP):
|
||||
|
||||
```sh
|
||||
make smoke APP=MiataDrive
|
||||
```
|
||||
|
||||
### On the T-Deck
|
||||
|
||||
`platformio.ini` has `src_dir = examples/MiataDrive`; build and flash with
|
||||
PlatformIO as usual.
|
||||
|
||||
## Controls
|
||||
|
||||
| Input | Action |
|
||||
|--------------------------|-----------------------------------------|
|
||||
| Trackball / arrow keys | steer left/right, gas (up), brake (down)|
|
||||
| `W` / `S` | gas on / brake pulse |
|
||||
| `A` / `D` | steer left / right |
|
||||
| `1` `2` `3` `4` (title) | pick car color: red / blue / white / yellow |
|
||||
| Enter / click / tap | start / restart |
|
||||
| `P` | toggle the auto-play demo driver |
|
||||
| `T` | sprite test gallery |
|
||||
|
||||
Manual driving is the default; the demo AI (`P`) steers toward the racing
|
||||
line, dodges traffic and eases off in sharp corners — handy when tuning
|
||||
graphics.
|
||||
|
||||
## Game features
|
||||
|
||||
- **Segment-based pseudo-3D road** (the classic "2.5D" technique): the track
|
||||
is a list of `(curve, hill)` segments projected with perspective. Road,
|
||||
rumble strips and lane dashes are drawn near→far with hill crest clipping;
|
||||
distance fog fades the far road into the sky.
|
||||
- **Centrifugal force** pulls you wide in corners; deep off-road excursions
|
||||
trigger a **rollover crash**: the car slides off, kicks up dust, the camera
|
||||
jolts, and the body tumbles through its sprite views (rear → slight → turn
|
||||
→ side) before you rejoin the tarmac.
|
||||
- **Traffic** (blue / white / yellow cars from the sprite sheet) drive slower
|
||||
lanes; rear-ending one costs speed and jolts the camera. Cars lean into
|
||||
corners with their turning sprite, mirrored on right-hand bends.
|
||||
- **Scoring / laps**: 3 laps, 75 s + 45 s per lap, −300 for a crash.
|
||||
- **Sound**: engine + event blips via `sound_engine.*` (I2S on device).
|
||||
|
||||
All graphics — including the title screen, which renders the start line
|
||||
under the arch with your selected car parked on the road — come from the
|
||||
game's own sprites. There are no external image assets.
|
||||
|
||||
## Sprite pipeline (hand-editable assets)
|
||||
|
||||
All sprites live in **one editable image** — `sprites_sheet.png` — tracked in
|
||||
git. The converter is `sprite_tool.py` (needs Pillow):
|
||||
|
||||
```sh
|
||||
python3 sprite_tool.py export # sprites.h -> sprites_sheet.png
|
||||
# ... edit the PNG by hand (paint magenta = transparent) ...
|
||||
python3 sprite_tool.py import # sprites_sheet.png -> sprites.h
|
||||
```
|
||||
|
||||
Sheet layout (fixed, the cutter never guesses):
|
||||
|
||||
- 1120×560: 7×4 grid of 160×140 cells; the top 14px of each cell is a label
|
||||
strip the cutter ignores; content area is 160×126 (largest sprite: arch,
|
||||
140×109).
|
||||
- Background is pure magenta (255,0,255) = transparent. Pink anti-aliasing
|
||||
fringes are cut (magenta excess > 35) or despilled automatically, so soft
|
||||
edges don't leave a purple halo.
|
||||
- Cell order is fixed and matches the `SpriteId` enum in `sprites.h`:
|
||||
0–15 player cars (red/blue/white/yellow × rear/slight/turn/side),
|
||||
16–21 scenery (palm, pine, bush, billboard, arch, tires),
|
||||
22–27 traffic (blue/white/yellow, rear + turning view).
|
||||
- The sharp-turn views are mirrored at extraction time so rear → slight →
|
||||
turn all face the same way; the game flips sprites for right-hand
|
||||
steering/curves.
|
||||
|
||||
Round-tripping is lossless (565→888 uses bit replication) and each import
|
||||
re-trims crops to content, so stray background pixels at sprite edges get
|
||||
cleaned up automatically.
|
||||
|
||||
## Sprite test gallery
|
||||
|
||||
Press `T` from the title screen: paginated view of every sprite at native
|
||||
size on a checkerboard, labeled with index and crop size. `A`/`D` flips the
|
||||
displayed sprite horizontally (to check turn-view alignment), page keys
|
||||
cycle through car colors / scenery / traffic, `T` returns.
|
||||
|
||||
## Tuning
|
||||
|
||||
Key constants live at the top of `MiataDrive.ino`: segment length/road
|
||||
width/camera (`SEG_LEN`, `ROAD_W`, `CAM_H`, `CAM_D`, `DRAW_DIST`), speeds
|
||||
(`MAX_SPEED`, `ACCEL`, `BRAKE`, `OFF_DECEL`), physics (`CENTRIFUGAL`), and
|
||||
race format (`LAPS`, `LAP_TIME`).
|
||||
|
||||
## Files
|
||||
|
||||
| File | Purpose |
|
||||
|----------------------|------------------------------------------------|
|
||||
| `MiataDrive.ino` | the game |
|
||||
| `sprites.h` | generated sprite data (do not edit by hand) |
|
||||
| `sprites_sheet.png` | editable sprite sheet (source of truth) |
|
||||
| `sprite_tool.py` | sheet ⇄ sprites.h converter |
|
||||
| `sound_engine.*` | I2S sound effects |
|
||||
| `utilities.h` | T-Deck board pins |
|
||||
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* @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
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t SoundEngine::pending() const
|
||||
{
|
||||
if (!q_) return 0;
|
||||
return (uint8_t)uxQueueMessagesWaiting(q_);
|
||||
}
|
||||
|
||||
void SoundEngine::clear()
|
||||
{
|
||||
if (!q_) return;
|
||||
SndEvent dummy;
|
||||
while (xQueueReceive(q_, &dummy, 0)) { }
|
||||
}
|
||||
|
||||
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; ) {
|
||||
if (q_ && uxQueueMessagesWaiting(q_) > 0) return; // interrupted by higher-priority sound
|
||||
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; ) {
|
||||
if (q_ && uxQueueMessagesWaiting(q_) > 0) return; // interrupted by higher-priority sound
|
||||
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; ) {
|
||||
if (q_ && uxQueueMessagesWaiting(q_) > 0) return; // interrupted by higher-priority sound
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* @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);
|
||||
uint8_t pending() const;
|
||||
void clear();
|
||||
|
||||
// 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
|
||||
};
|
||||
|
Before Width: | Height: | Size: 144 KiB After Width: | Height: | Size: 144 KiB |
+1
-1
@@ -35,7 +35,7 @@ default_envs = T-Deck
|
||||
;src_dir = examples/CrtTerminal
|
||||
;src_dir = examples/NoiseSensor
|
||||
; src_dir = examples/MissileCommand
|
||||
src_dir = examples/Lotus3
|
||||
src_dir = examples/MiataDrive
|
||||
|
||||
|
||||
;! Don't make changes
|
||||
|
||||
Reference in New Issue
Block a user