diff --git a/src/core/thread.c b/src/core/thread.c index e3d48d8..c8aa522 100644 --- a/src/core/thread.c +++ b/src/core/thread.c @@ -31,6 +31,14 @@ typedef struct { #ifndef DISABLE_THREADING static const float _defaultFPSTarget = 60.f; + +#ifdef __EMSCRIPTEN__ +// GBA Link Online: turno de ejecución para el link local determinista. +// Si está definido, se llama antes (begin=true) y después (begin=false) de cada +// runLoop de los hilos con "lockstepRunLoop", para que solo emule un hilo a la vez. +// Tras el runLoop devuelve si este hilo debe ajustarse al reloj (60 fps). +bool (*mCoreThreadLockstepTurn)(struct mCoreThread* thread, bool begin) = NULL; +#endif static ThreadLocal _contextKey; #ifdef USE_PTHREADS @@ -383,8 +391,16 @@ static THREAD_ENTRY _mCoreThreadRun(void* context) { bool lockstepRunLoop = false; mCoreConfigGetBoolValue(&core->config, "lockstepRunLoop", &lockstepRunLoop); if (lockstepRunLoop) { + bool (*turn)(struct mCoreThread*, bool) = mCoreThreadLockstepTurn; + bool pace = true; + if (turn) { + turn(threadContext, true); + } core->runLoop(core); - if (core->frameCounter && impl->sync.fpsTarget > 0) { + if (turn) { + pace = turn(threadContext, false); + } + if (pace && core->frameCounter && impl->sync.fpsTarget > 0) { uint32_t frame = core->frameCounter(core); if (frame != loop.lockstepFrame) { double now = emscripten_get_now(); diff --git a/src/gba/sio/lockstep.c b/src/gba/sio/lockstep.c index 74492ec..a2e3487 100644 --- a/src/gba/sio/lockstep.c +++ b/src/gba/sio/lockstep.c @@ -848,11 +848,13 @@ static void _setData(struct GBASIOLockstepCoordinator* coordinator, uint32_t id, void _setReady(struct GBASIOLockstepCoordinator* coordinator, struct GBASIOLockstepPlayer* activePlayer, int playerId, enum GBASIOMode mode) { activePlayer->otherModes[playerId] = mode; - bool ready = true; - int i; - for (i = 0; ready && i < coordinator->nAttached; ++i) { - ready = activePlayer->otherModes[i] == activePlayer->mode; - } + // GBA Link Online: SD es una línea compartida con pull-up que solo baja una GBA en + // modo multijugador que aún no está lista. Una GBA que todavía no ha entrado en ese + // modo (p. ej. sigue en un menú, con RCNT en GPIO) no la baja. mGBA exigía que todas + // estuvieran ya en modo multijugador, y la consola hija de juegos como Yu-Gi-Oh! WC + // 2006 se rinde si no ve SD a tiempo: el link solo conectaba si los dos jugadores + // entraban casi en el mismo frame. Aquí SD está alto en cuanto hay otra GBA conectada. + bool ready = coordinator->nAttached >= 2; if (activePlayer->mode == GBA_SIO_MULTI) { struct GBASIO* sio = activePlayer->driver->d.p; sio->siocnt = GBASIOMultiplayerSetReady(sio->siocnt, ready); @@ -937,7 +939,7 @@ void _lockstepEvent(struct mTiming* timing, void* context, uint32_t cyclesLate) if (!event) { break; } - if (event->timestamp > GBASIOLockstepTime(player)) { + if (event->timestamp - GBASIOLockstepTime(player) > 0) { break; } player->queue = event->next; @@ -962,11 +964,20 @@ void _lockstepEvent(struct mTiming* timing, void* context, uint32_t cyclesLate) GBASIOLockstepCoordinatorAckPlayer(coordinator, player); break; case SIO_EV_TRANSFER_START: - _setData(coordinator, player->playerId, sio); - nextEvent = event->finishCycle - GBASIOLockstepTime(player) - cyclesLate; - player->driver->d.p->siocnt |= 0x80; - mTimingDeschedule(&sio->p->timing, &sio->completeEvent); - mTimingSchedule(&sio->p->timing, &sio->completeEvent, nextEvent); + if (player->mode == coordinator->transferMode) { + _setData(coordinator, player->playerId, sio); + nextEvent = event->finishCycle - GBASIOLockstepTime(player) - cyclesLate; + player->driver->d.p->siocnt |= 0x80; + mTimingDeschedule(&sio->p->timing, &sio->completeEvent); + mTimingSchedule(&sio->p->timing, &sio->completeEvent, nextEvent); + } else { + // GBA Link Online: una GBA que no está en el modo de la transferencia (p. ej. + // sigue en un menú) no participa: sus líneas quedan altas y la primaria lee + // 0xFFFF, como en hardware. mGBA metía su registro de envío (0x0000), y + // Yu-Gi-Oh! WC 2006 lo tomaba por una consola que responde mal y daba + // "Connection Error" si la primaria entraba antes en "Link Duel". + coordinator->normalData[player->playerId] = 0xFFFFFFFF; + } GBASIOLockstepCoordinatorAckPlayer(coordinator, player); break; case SIO_EV_MODE_SET: diff --git a/src/platform/wasm/CMakeLists.txt b/src/platform/wasm/CMakeLists.txt index 751e8b1..a043db2 100644 --- a/src/platform/wasm/CMakeLists.txt +++ b/src/platform/wasm/CMakeLists.txt @@ -2,7 +2,7 @@ set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} \ -O3 \ -s USE_SDL=2 \ -s INITIAL_MEMORY=256mb \ - -s EXPORTED_RUNTIME_METHODS=[\"FS\",\"cwrap\",\"addFunction\",\"removeFunction\"] \ + -s EXPORTED_RUNTIME_METHODS=[\"FS\",\"cwrap\",\"addFunction\",\"removeFunction\",\"HEAPU8\"] \ -s ALLOW_TABLE_GROWTH=1 \ -s ENVIRONMENT='web,worker' \ -s PTHREAD_POOL_SIZE=5 \ diff --git a/src/platform/wasm/main.c b/src/platform/wasm/main.c index 0a4ac5b..98ccba0 100644 --- a/src/platform/wasm/main.c +++ b/src/platform/wasm/main.c @@ -10,11 +10,17 @@ #include #include #include +#include #include #include #include #include #include +#include + +#include +#include +#include #include "platform/sdl/sdl-audio.h" #include "platform/sdl/sdl-events.h" @@ -48,6 +54,63 @@ typedef struct { static mEmscriptenLinkSession* linkSession = NULL; +/* --------------------------------------------------------------------------- + * GBA Link Online: control de frames para lockstep determinista. + * + * Cada consola llama a linkFrameCallback() en SU hilo al terminar cada frame. + * "frame N" = frames completados. Antes de ejecutar el frame N (N >= 1): + * - si el gate está activo, espera a tener la entrada de ese jugador para N + * (linkLocalPushInput) y la aplica con setKeys; + * - ejecuta operaciones pedidas para ese frame exacto (save/load state); + * - cada `hashInterval` frames guarda un hash de EWRAM+IWRAM. + * El frame 0 siempre corre sin teclas. Todo es por jugador y sin bloquear el + * hilo principal: JS escribe/lee con atómicos o punteros a memoria compartida. + * ------------------------------------------------------------------------- */ +#define LINK_INPUT_RING 512 +#define LINK_HASH_RING 64 +#define LINK_VIDEO_PIXELS (GBA_VIDEO_HORIZONTAL_PIXELS * GBA_VIDEO_VERTICAL_PIXELS) + +// SAVE_ALL / LOAD_ALL: los pide JS en la consola 1 y su hilo guarda/carga TODAS las +// consolas en el mismo instante (las demás están paradas fuera de runLoop esperando +// turno). El estado de link (coordinador incluido) va dentro del save state de mGBA. +enum { LINK_OP_NONE = 0, LINK_OP_SAVE = 1, LINK_OP_LOAD = 2, LINK_OP_SAVE_ALL = 3, LINK_OP_LOAD_ALL = 4 }; + +_Static_assert(sizeof(mColor) == sizeof(uint32_t), "linkControl.display asume pixeles de 32 bits"); + +typedef struct { + atomic_uint tag; // frame + 1 (0 = vacío) + atomic_uint keys; +} mLinkInputSlot; + +typedef struct { + atomic_uint frame; + atomic_uint hash; +} mLinkHashSlot; + +typedef struct { + atomic_uint framesDone; // frames completados + mLinkInputSlot inputs[LINK_INPUT_RING]; + mLinkHashSlot hashes[LINK_HASH_RING]; + // Operación de estado pendiente (save/load) en un frame concreto. + atomic_int opKind; + atomic_uint opFrame; + const void* opLoadData; + size_t opLoadSize; + atomic_int opResult; // 0 pendiente, 1 ok, -1 error + void* stateData; // último save state generado (malloc) + size_t stateSize; + uint32_t stateFrames; // SAVE_ALL/LOAD_ALL: frames completados de esta consola en ese instante + uint32_t display[LINK_VIDEO_PIXELS]; // copia del último frame completo + atomic_uint displaySeq; +} mLinkControl; + +static mLinkControl linkControl[MAX_GBAS]; +static atomic_int linkGate = 0; // 1 = esperar entradas por frame +static atomic_int linkStopping = 0; // 1 = la sesión se está cerrando +static atomic_uint linkHashInterval = 0; +static int linkAudioPin = 0; // 0 = el audio sigue al jugador activo +static bool linkAudioReady = false; + // log utilities static void _log(struct mLogger*, int category, enum mLogLevel level, const char* format, va_list args); static struct mLogFilter logFilter; @@ -74,7 +137,7 @@ static struct mCore* activeInputCore(void) { } static void setLinkAudioPlayer(int player) { - if (!linkPlayerIndexValid(player) || !linkSession->threads[player - 1]) { + if (!linkAudioReady || !linkPlayerIndexValid(player) || !linkSession->threads[player - 1]) { return; } @@ -82,16 +145,168 @@ static void setLinkAudioPlayer(int player) { renderer->audio.sync = &linkSession->threads[player - 1]->impl->sync; } +/* + * GBA Link Online: turnos deterministas entre los hilos de las consolas. + * + * El coordinador de link de mGBA deja que las dos consolas emulen a la vez; el + * orden real de sus operaciones depende del planificador del sistema y no es + * reproducible. Aquí solo emula una consola a la vez (un runLoop por turno) y el + * siguiente turno se decide SOLO con el estado emulado (ciclos de cada consola y + * si el coordinador la ha dormido). Así la ejecución es la misma en cada cliente. + */ +extern bool (*mCoreThreadLockstepTurn)(struct mCoreThread* thread, bool begin); + +static atomic_int linkTurnsEnabled = 1; // 0 = comportamiento original (hilos libres) +static atomic_uint linkTurnQuantum = 4096; // ciclos que una consola puede adelantarse +static atomic_uint linkTurnHandoffs = 0; // estadística: cambios de turno + +static pthread_mutex_t linkTurnMutex = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t linkTurnCond = PTHREAD_COND_INITIALIZER; +static int linkTurnOwner = -1; // consola emulando ahora (-1 = ninguna) +static int linkTurnLast = 0; // última consola que tuvo el turno +static bool linkTurnReady[MAX_GBAS]; // el hilo ya llegó a su primer runLoop +static bool linkAsleep[MAX_GBAS]; // dormida por el coordinador de link +static void (*linkOrigSleep[MAX_GBAS])(struct mLockstepUser*); +static void (*linkOrigWake[MAX_GBAS])(struct mLockstepUser*); + +// Ciclos emulados de la consola i (32 bits, da la vuelta): compararlos siempre con +// diferencias con signo. Las dos consolas arrancan desde reset a la vez. +static uint32_t linkCoreTime(int i) { + struct mCore* c = linkSession->cores[i]; + return c && c->timing ? (uint32_t) mTimingCurrentTime(c->timing) : 0; +} + +static int32_t linkTimeDiff(uint32_t a, uint32_t b) { + return (int32_t) (a - b); +} + +// Con linkTurnMutex tomado. Devuelve la consola a la que le toca, o -1. +static int linkTurnPick(void) { + int n = linkSession->playerCount; + for (int i = 0; i < n; ++i) { + if (!linkTurnReady[i]) { + return -1; // nadie emula hasta que todas hayan arrancado + } + } + int last = linkTurnLast; + if (last >= 0 && last < n && !linkAsleep[last]) { + uint32_t t = linkCoreTime(last); + int32_t quantum = (int32_t) atomic_load(&linkTurnQuantum); + bool keep = true; + for (int j = 0; j < n; ++j) { + if (j != last && !linkAsleep[j] && linkTimeDiff(t, linkCoreTime(j)) > quantum) { + keep = false; + } + } + if (keep) { + return last; + } + } + int best = -1; + uint32_t bestTime = 0; + for (int i = 0; i < n; ++i) { + if (linkAsleep[i]) { + continue; + } + uint32_t t = linkCoreTime(i); + if (best < 0 || linkTimeDiff(t, bestTime) < 0) { + best = i; + bestTime = t; + } + } + return best; +} + +static bool linkTurn(struct mCoreThread* thread, bool begin) { + if (!linkSession || !atomic_load(&linkTurnsEnabled)) { + return true; + } + int i = (int) (intptr_t) thread->userData; + if (i < 0 || i >= linkSession->playerCount) { + return true; + } + pthread_mutex_lock(&linkTurnMutex); + if (begin) { + if (!linkTurnReady[i]) { + linkTurnReady[i] = true; + pthread_cond_broadcast(&linkTurnCond); + } + while (!atomic_load(&linkStopping)) { + if (linkTurnOwner < 0 && linkTurnPick() == i) { + if (linkTurnLast != i) { + atomic_fetch_add(&linkTurnHandoffs, 1); + } + linkTurnOwner = i; + linkTurnLast = i; + break; + } + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_nsec += 2000000; + if (ts.tv_nsec >= 1000000000) { + ts.tv_sec += 1; + ts.tv_nsec -= 1000000000; + } + pthread_cond_timedwait(&linkTurnCond, &linkTurnMutex, &ts); + } + } else { + if (linkTurnOwner == i) { + linkTurnOwner = -1; + } + pthread_cond_broadcast(&linkTurnCond); + } + pthread_mutex_unlock(&linkTurnMutex); + // Solo la consola 1 se ajusta al reloj; la otra la sigue por turnos. Si las dos + // esperasen al reloj por separado, sus esperas se sumarían. + return i == 0; +} + +static void linkUserSleep(struct mLockstepUser* user) { + int i = ((mEmscriptenLinkUser*) user)->requestedId; + pthread_mutex_lock(&linkTurnMutex); + linkAsleep[i] = true; + pthread_cond_broadcast(&linkTurnCond); + pthread_mutex_unlock(&linkTurnMutex); + linkOrigSleep[i](user); +} + +static void linkUserWake(struct mLockstepUser* user) { + int i = ((mEmscriptenLinkUser*) user)->requestedId; + pthread_mutex_lock(&linkTurnMutex); + linkAsleep[i] = false; + pthread_cond_broadcast(&linkTurnCond); + pthread_mutex_unlock(&linkTurnMutex); + linkOrigWake[i](user); +} + +static void resetLinkControl(void) { + for (int i = 0; i < MAX_GBAS; ++i) { + mLinkControl* c = &linkControl[i]; + free(c->stateData); + memset(c, 0, sizeof(*c)); + } + pthread_mutex_lock(&linkTurnMutex); + linkTurnOwner = -1; + linkTurnLast = 0; + memset(linkTurnReady, 0, sizeof(linkTurnReady)); + memset(linkAsleep, 0, sizeof(linkAsleep)); + pthread_mutex_unlock(&linkTurnMutex); +} + static void destroyLinkSession(void) { if (!linkSession) { return; } - if (renderer->audio.core) { + // Libera a los hilos que estén esperando entradas en el gate. + atomic_store(&linkStopping, 1); + + if (linkAudioReady) { mSDLPauseAudio(&renderer->audio); mSDLDeinitAudio(&renderer->audio); renderer->audio.core = NULL; renderer->audio.sync = NULL; + linkAudioReady = false; } for (int i = 0; i < linkSession->playerCount; ++i) { @@ -115,6 +330,145 @@ static void destroyLinkSession(void) { GBASIOLockstepCoordinatorDeinit(&linkSession->coordinator); free(linkSession); linkSession = NULL; + resetLinkControl(); + atomic_store(&linkStopping, 0); +} + +// FNV-1a de 32 bits sobre un bloque de memoria. +static uint32_t linkHashBlock(uint32_t h, const uint8_t* data, size_t size) { + for (size_t i = 0; i < size; ++i) { + h ^= data[i]; + h *= 16777619u; + } + return h; +} + +static uint32_t linkHashCore(struct mCore* core) { + uint32_t h = 2166136261u; + static const size_t regions[] = { GBA_REGION_EWRAM, GBA_REGION_IWRAM }; + for (size_t r = 0; r < sizeof(regions) / sizeof(regions[0]); ++r) { + size_t size = 0; + const uint8_t* block = core->getMemoryBlock(core, regions[r], &size); + if (block && size) { + h = linkHashBlock(h, block, size); + } + } + return h ? h : 1; // 0 se reserva para "sin hash" +} + +static bool linkSaveCore(struct mCore* core, mLinkControl* c) { + bool ok = false; + struct VFile* vf = VFileMemChunk(NULL, 0); + if (!vf) { + return false; + } + if (mCoreSaveStateNamed(core, vf, SAVESTATE_SAVEDATA | SAVESTATE_RTC)) { + ssize_t size = vf->size(vf); + void* data = size > 0 ? malloc(size) : NULL; + if (data) { + vf->seek(vf, 0, SEEK_SET); + ok = vf->read(vf, data, size) == size; + if (ok) { + free(c->stateData); + c->stateData = data; + c->stateSize = size; + } else { + free(data); + } + } + } + vf->close(vf); + return ok; +} + +static bool linkLoadCore(struct mCore* core, mLinkControl* c) { + if (!c->opLoadData || !c->opLoadSize) { + return false; + } + struct VFile* vf = VFileFromConstMemory(c->opLoadData, c->opLoadSize); + if (!vf) { + return false; + } + bool ok = mCoreLoadStateNamed(core, vf, SAVESTATE_SAVEDATA | SAVESTATE_RTC); + vf->close(vf); + return ok; +} + +static void linkRunPendingOp(struct mCore* core, mLinkControl* c, uint32_t frame) { + int kind = atomic_load(&c->opKind); + if (kind == LINK_OP_NONE || atomic_load(&c->opFrame) != frame) { + return; + } + bool ok = false; + if (kind == LINK_OP_SAVE) { + ok = linkSaveCore(core, c); + } else if (kind == LINK_OP_LOAD) { + ok = linkLoadCore(core, c); + } else if ((kind == LINK_OP_SAVE_ALL || kind == LINK_OP_LOAD_ALL) && c == &linkControl[0] && linkSession) { + // Hilo de la consola 1 con el turno: las demás no están dentro de runLoop. + ok = true; + for (int i = 0; i < linkSession->playerCount && ok; ++i) { + struct mCore* ci = linkSession->cores[i]; + mLinkControl* li = &linkControl[i]; + if (kind == LINK_OP_SAVE_ALL) { + ok = ci && linkSaveCore(ci, li); + li->stateFrames = i == 0 ? frame : atomic_load(&li->framesDone); + } else { + ok = ci && linkLoadCore(ci, li); + if (ok && i != 0) { + atomic_store(&li->framesDone, li->stateFrames); + } + } + } + } + atomic_store(&c->opKind, LINK_OP_NONE); + atomic_store(&c->opResult, ok ? 1 : -1); +} + +// Se ejecuta en el hilo de cada consola al terminar un frame. +static void linkFrameCallback(struct mCoreThread* thread) { + int index = (int) (intptr_t) thread->userData; + if (index < 0 || index >= MAX_GBAS || !linkSession) { + return; + } + struct mCore* core = thread->core; + mLinkControl* c = &linkControl[index]; + uint32_t done = atomic_load(&c->framesDone) + 1; // frames completados tras este + + // Copia del frame para que JS pueda mostrar ambas pantallas. + if (linkSession->outputBuffers[index]) { + memcpy(c->display, linkSession->outputBuffers[index], sizeof(c->display)); + atomic_fetch_add(&c->displaySeq, 1); + } + + uint32_t interval = atomic_load(&linkHashInterval); + if (interval && done % interval == 0) { + mLinkHashSlot* slot = &c->hashes[(done / interval) % LINK_HASH_RING]; + atomic_store(&slot->hash, linkHashCore(core)); + atomic_store(&slot->frame, done); + } + + // Operaciones de estado en el límite exacto de frame (antes del frame `done`). + linkRunPendingOp(core, c, done); + + // Visible para JS: este hilo completó `done` frames (y espera la entrada de `done`). + atomic_store(&c->framesDone, done); + + // Gate: no seguir hasta tener la entrada de este jugador para el frame `done`. + if (atomic_load(&linkGate)) { + mLinkInputSlot* slot = &c->inputs[done % LINK_INPUT_RING]; + while (atomic_load(&slot->tag) != done + 1) { + if (atomic_load(&linkStopping) || !atomic_load(&linkGate)) { + break; + } + // Una operación pedida mientras esperamos también se atiende aquí. + linkRunPendingOp(core, c, done); + emscripten_thread_sleep(0.5); + } + if (atomic_load(&slot->tag) == done + 1) { + core->setKeys(core, atomic_load(&slot->keys)); + } + } } static void wrapped_log(int level, const char* categoryName, const char* message) { @@ -649,6 +1003,10 @@ static bool setupLinkCore(int index, const char* romPath, const char* savePathOv mLockstepThreadUserInit(&linkSession->users[index].d, NULL); linkSession->users[index].requestedId = index; linkSession->users[index].d.d.requestedId = linkRequestedId; + linkOrigSleep[index] = linkSession->users[index].d.d.sleep; + linkOrigWake[index] = linkSession->users[index].d.d.wake; + linkSession->users[index].d.d.sleep = linkUserSleep; + linkSession->users[index].d.d.wake = linkUserWake; GBASIOLockstepDriverCreate(&linkSession->sioDrivers[index], &linkSession->users[index].d.d); GBASIOLockstepCoordinatorAttach(&linkSession->coordinator, &linkSession->sioDrivers[index]); core->setPeripheral(core, mPERIPH_GBA_LINK_PORT, &linkSession->sioDrivers[index].d); @@ -668,6 +1026,7 @@ EMSCRIPTEN_KEEPALIVE bool linkLocalStartSession(const char* player1RomPath, cons quitGame(); } destroyLinkSession(); + resetLinkControl(); linkSession = calloc(1, sizeof(mEmscriptenLinkSession)); if (!linkSession) { return false; @@ -711,6 +1070,9 @@ EMSCRIPTEN_KEEPALIVE bool linkLocalStartSession(const char* player1RomPath, cons memset(linkSession->threads[i], 0, sizeof(struct mCoreThread)); linkSession->threads[i]->core = linkSession->cores[i]; linkSession->threads[i]->logger.logger = &logCtx; + linkSession->threads[i]->frameCallback = linkFrameCallback; + mCoreThreadLockstepTurn = linkTurn; + linkSession->threads[i]->userData = (void*) (intptr_t) i; linkSession->users[i].d.thread = linkSession->threads[i]; if (!mCoreThreadStart(linkSession->threads[i])) { destroyLinkSession(); @@ -718,12 +1080,14 @@ EMSCRIPTEN_KEEPALIVE bool linkLocalStartSession(const char* player1RomPath, cons } } - if (!mSDLInitAudio(&renderer->audio, linkSession->threads[0])) { - destroyLinkSession(); - return false; + // Sin audio (navegador sin Web Audio) el link sigue funcionando, en silencio. + linkAudioReady = mSDLInitAudio(&renderer->audio, linkSession->threads[0]); + if (linkAudioReady) { + setLinkAudioPlayer(linkAudioPin ? linkAudioPin : 1); + mSDLResumeAudio(&renderer->audio); + } else { + printf("[link] audio no disponible: se continua sin sonido\n"); } - setLinkAudioPlayer(1); - mSDLResumeAudio(&renderer->audio); emscripten_resume_main_loop(); return true; @@ -737,10 +1101,211 @@ EMSCRIPTEN_KEEPALIVE void linkLocalStopSession(void) { EMSCRIPTEN_KEEPALIVE void linkLocalSetActivePlayer(int player) { if (linkPlayerIndexValid(player)) { linkSession->activePlayer = player; - setLinkAudioPlayer(player); + if (!linkAudioPin) { + setLinkAudioPlayer(player); + } + } +} + +/* ---------------- GBA Link Online: API de lockstep ---------------- */ + +// Turnos deterministas (1, por defecto) u hilos libres como mGBA original (0). +EMSCRIPTEN_KEEPALIVE void linkLocalSetTurns(int enabled) { + atomic_store(&linkTurnsEnabled, enabled ? 1 : 0); + pthread_mutex_lock(&linkTurnMutex); + pthread_cond_broadcast(&linkTurnCond); + pthread_mutex_unlock(&linkTurnMutex); +} + +// Ciclos que una consola puede adelantarse a la otra antes de ceder el turno. +EMSCRIPTEN_KEEPALIVE void linkLocalSetTurnQuantum(uint32_t cycles) { + atomic_store(&linkTurnQuantum, cycles ? cycles : 1); +} + +// Diagnóstico: 0 dueño del turno, 1 último, 2 máscara de dormidas, 3 cambios de turno, +// 4/5 ciclos (bajos) de cada consola, 6 máscara de hilos listos. +EMSCRIPTEN_KEEPALIVE uint32_t linkLocalGetTurnStat(int what) { + uint32_t v = 0; + pthread_mutex_lock(&linkTurnMutex); + switch (what) { + case 0: v = (uint32_t) linkTurnOwner; break; + case 1: v = (uint32_t) linkTurnLast; break; + case 2: for (int i = 0; i < MAX_GBAS; ++i) v |= linkAsleep[i] ? 1u << i : 0; break; + case 3: v = atomic_load(&linkTurnHandoffs); break; + case 4: v = linkSession ? linkCoreTime(0) : 0; break; + case 5: v = linkSession ? linkCoreTime(1) : 0; break; + case 6: for (int i = 0; i < MAX_GBAS; ++i) v |= linkTurnReady[i] ? 1u << i : 0; break; + } + pthread_mutex_unlock(&linkTurnMutex); + return v; +} + +static mLinkControl* linkControlFor(int player) { + return (player >= 1 && player <= MAX_GBAS) ? &linkControl[player - 1] : NULL; +} + +// Teclas de un jugador sin gate (bitmask GBA: A=1, B=2, Select=4, Start=8, ...). +EMSCRIPTEN_KEEPALIVE void linkLocalSetKeys(int player, int keys) { + if (linkPlayerIndexValid(player) && linkSession->cores[player - 1]) { + linkSession->cores[player - 1]->setKeys(linkSession->cores[player - 1], (uint32_t) keys); + } +} + +// Activa/desactiva el gate. Activarlo ANTES de linkLocalStartSession. +EMSCRIPTEN_KEEPALIVE void linkLocalSetGate(int enabled) { + atomic_store(&linkGate, enabled ? 1 : 0); +} + +// Entrada de `player` para el frame `frame` (>= 1). Se puede adelantar hasta LINK_INPUT_RING frames. +EMSCRIPTEN_KEEPALIVE void linkLocalPushInput(int player, uint32_t frame, int keys) { + mLinkControl* c = linkControlFor(player); + if (!c || frame == 0) { + return; + } + mLinkInputSlot* slot = &c->inputs[frame % LINK_INPUT_RING]; + atomic_store(&slot->keys, (uint32_t) keys); + atomic_store(&slot->tag, frame + 1); +} + +// Frames completados por la consola de `player`. +EMSCRIPTEN_KEEPALIVE uint32_t linkLocalGetFrame(int player) { + mLinkControl* c = linkControlFor(player); + return c ? atomic_load(&c->framesDone) : 0; +} + +// Puntero (en HEAPU8) al último frame completo de `player`: 240x160 píxeles RGBX de 32 bits. +EMSCRIPTEN_KEEPALIVE uint32_t* linkLocalGetVideoBuffer(int player) { + mLinkControl* c = linkControlFor(player); + return c ? c->display : NULL; +} + +// Contador que sube con cada frame copiado (para no redibujar lo mismo). +EMSCRIPTEN_KEEPALIVE uint32_t linkLocalGetVideoSeq(int player) { + mLinkControl* c = linkControlFor(player); + return c ? atomic_load(&c->displaySeq) : 0; +} + +// Fija qué consola suena (0 = la activa). +EMSCRIPTEN_KEEPALIVE void linkLocalSetAudioPlayer(int player) { + linkAudioPin = (player >= 1 && player <= MAX_GBAS) ? player : 0; + if (linkSession) { + setLinkAudioPlayer(linkAudioPin ? linkAudioPin : linkSession->activePlayer); } } +// Calcula un hash de EWRAM+IWRAM cada `interval` frames (0 = desactivado). +EMSCRIPTEN_KEEPALIVE void linkLocalSetHashInterval(uint32_t interval) { + atomic_store(&linkHashInterval, interval); +} + +// Hash de `player` tras `frame` frames, o 0 si no está disponible (aún o ya sobrescrito). +EMSCRIPTEN_KEEPALIVE uint32_t linkLocalGetHash(int player, uint32_t frame) { + mLinkControl* c = linkControlFor(player); + uint32_t interval = atomic_load(&linkHashInterval); + if (!c || !interval || frame % interval) { + return 0; + } + mLinkHashSlot* slot = &c->hashes[(frame / interval) % LINK_HASH_RING]; + return atomic_load(&slot->frame) == frame ? atomic_load(&slot->hash) : 0; +} + +// Pide un save state de `player` justo después de `frame` frames. +// Resultado con linkLocalGetOpResult; datos con linkLocalGetStateData/Size. +EMSCRIPTEN_KEEPALIVE bool linkLocalRequestSaveState(int player, uint32_t frame) { + mLinkControl* c = linkControlFor(player); + if (!c || atomic_load(&c->opKind) != LINK_OP_NONE) { + return false; + } + atomic_store(&c->opResult, 0); + atomic_store(&c->opFrame, frame); + atomic_store(&c->opKind, LINK_OP_SAVE); + return true; +} + +// Pide cargar un save state (data/size en memoria de JS vía _malloc) justo después de `frame` frames. +// `data` debe seguir vivo hasta que linkLocalGetOpResult devuelva != 0. +EMSCRIPTEN_KEEPALIVE bool linkLocalRequestLoadState(int player, uint32_t frame, const void* data, uint32_t size) { + mLinkControl* c = linkControlFor(player); + if (!c || !data || !size || atomic_load(&c->opKind) != LINK_OP_NONE) { + return false; + } + c->opLoadData = data; + c->opLoadSize = size; + atomic_store(&c->opResult, 0); + atomic_store(&c->opFrame, frame); + atomic_store(&c->opKind, LINK_OP_LOAD); + return true; +} + +// Resincronización: save state de TODAS las consolas en el instante en que la consola 1 +// termina `frame` frames. Resultado en linkLocalGetOpResult(1); datos de cada consola con +// linkLocalGetStateData/Size(player) y sus frames completados con linkLocalGetStateFrames. +EMSCRIPTEN_KEEPALIVE bool linkLocalRequestSaveAll(uint32_t frame) { + mLinkControl* c = &linkControl[0]; + if (!linkSession || atomic_load(&c->opKind) != LINK_OP_NONE) { + return false; + } + atomic_store(&c->opResult, 0); + atomic_store(&c->opFrame, frame); + atomic_store(&c->opKind, LINK_OP_SAVE_ALL); + return true; +} + +// Prepara los datos de una consola para linkLocalRequestLoadAll (data debe seguir vivo +// hasta que la operación termine). `frames` = sus frames completados en ese instante. +EMSCRIPTEN_KEEPALIVE bool linkLocalSetLoadData(int player, const void* data, uint32_t size, uint32_t frames) { + mLinkControl* c = linkControlFor(player); + if (!c || atomic_load(&linkControl[0].opKind) != LINK_OP_NONE) { + return false; + } + c->opLoadData = data; + c->opLoadSize = size; + c->stateFrames = frames; + return true; +} + +// Carga en TODAS las consolas los datos de linkLocalSetLoadData cuando la consola 1 +// termina `frame` frames. +EMSCRIPTEN_KEEPALIVE bool linkLocalRequestLoadAll(uint32_t frame) { + mLinkControl* c = &linkControl[0]; + if (!linkSession || atomic_load(&c->opKind) != LINK_OP_NONE) { + return false; + } + atomic_store(&c->opResult, 0); + atomic_store(&c->opFrame, frame); + atomic_store(&c->opKind, LINK_OP_LOAD_ALL); + return true; +} + +EMSCRIPTEN_KEEPALIVE uint32_t linkLocalGetStateFrames(int player) { + mLinkControl* c = linkControlFor(player); + return c ? c->stateFrames : 0; +} + +// 0 = pendiente, 1 = hecho, -1 = error. +EMSCRIPTEN_KEEPALIVE int linkLocalGetOpResult(int player) { + mLinkControl* c = linkControlFor(player); + return c ? atomic_load(&c->opResult) : -1; +} + +EMSCRIPTEN_KEEPALIVE void* linkLocalGetStateData(int player) { + mLinkControl* c = linkControlFor(player); + return c ? c->stateData : NULL; +} + +EMSCRIPTEN_KEEPALIVE uint32_t linkLocalGetStateSize(int player) { + mLinkControl* c = linkControlFor(player); + return c ? (uint32_t) c->stateSize : 0; +} + +EMSCRIPTEN_KEEPALIVE void* linkLocalAlloc(uint32_t size) { + return malloc(size); +} + +EMSCRIPTEN_KEEPALIVE void linkLocalFree(void* ptr) { + free(ptr); +} + EMSCRIPTEN_KEEPALIVE int linkLocalGetActivePlayer(void) { return linkSession ? linkSession->activePlayer : 0; }