PlayAgain's changes to Panda3DS 92e53d26, applied after patches/panda3ds-emscripten.patch (build.sh). GPL-3.0-or-later. - No SDL in the browser core: Emscripten's SDL2 port is neither fetched nor linked (its one use was SDL_GetPrefPath). - The app-data folder is a fixed /pa/3ds/ in the module's file system; a game's folder in it is named after its title (program) ID from the NCCH header, /pa/3ds/saves/<16 hex digits>/, not after the file (homebrew without one: saves/homebrew-/), set once the header is read. - AAC: FAAD2 (GPL-2.0-or-later; build.sh fetches it into third_party/faad2) decodes the DSP's AAC in place of fdk-aac, whose licence the FSF counts as GPL-incompatible; fdk-aac is neither fetched nor linked. The decoder restarts on the DSP's Init command, and answers the samples written over the whole buffer, as Azahar's FAAD2 decoder does. - Sound: the browser core has no audio device of its own (the libretro device class: a holder of the DSP's sample ring that plays nothing), so the DSP makes sound into the ring and the page drains it (pa_read_audio). - WebGL vertex fetch: each attribute starts at a multiple of its component size within the vertex (as on the PICA, Citra's and Azahar's vertex loader; both the accelerated and the CPU path), each loader's data starts 4-byte aligned in the vertex buffer, and a draw whose stride WebGL would refuse runs its vertex shader on the CPU (paUnalignedDraws counts them), so WebGL no longer rejects vertexAttribPointer and loses the draw. - Determinism: the guest's clock (Memory::timeSince3DSEpoch) is the session clock the page sets, advanced by emulated ticks, never the host's; the SSL service's RNG has a fixed seed instead of std::random_device. - Save states (pa_3ds.cpp, "save states"): deinitGraphicsContext also forgets what the renderer and the GPU remember about GL objects that are gone (the enabled attributes of the hardware-shader VAO, the vertex shader in use, the uniform block offsets; the vertex shader's uniforms and the lighting and fog tables are written again), so a memory image loaded into a fresh context draws. diff --git a/CMakeLists.txt b/CMakeLists.txt index 8e93a47..7b67103 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -178,8 +178,7 @@ if(ENABLE_DISCORD_RPC AND NOT ANDROID) endif() if (EMSCRIPTEN) - target_compile_options(AlberCore PUBLIC "-sUSE_SDL=2") - target_link_options(AlberCore PUBLIC "-sUSE_SDL=2") + # PlayAgain: no SDL in the browser core (the only use was the app-data path, see src/emulator.cpp), so no Emscripten port is fetched elseif (NOT ANDROID) if (USE_SYSTEM_SDL2) find_package(SDL2 CONFIG REQUIRED) @@ -345,7 +344,8 @@ else() endif() add_subdirectory(third_party/teakra) -add_subdirectory(third_party/fdk-aac) +# PlayAgain: FAAD2 (GPL-2.0-or-later) decodes the DSP's AAC in place of fdk-aac, whose licence is GPL-incompatible +add_subdirectory(third_party/faad2 EXCLUDE_FROM_ALL) set(CAPSTONE_ARCHITECTURE_DEFAULT OFF) set(CAPSTONE_ARM_SUPPORT ON) @@ -722,7 +722,7 @@ set(ALL_SOURCES ${SOURCE_FILES} ${FS_SOURCE_FILES} ${CRYPTO_SOURCE_FILES} ${KERN ${AUDIO_SOURCE_FILES} ${HEADER_FILES} ${FRONTEND_HEADER_FILES}) target_sources(AlberCore PRIVATE ${ALL_SOURCES}) -target_link_libraries(AlberCore PRIVATE dynarmic glad resources_console_fonts fdk-aac) +target_link_libraries(AlberCore PRIVATE dynarmic glad resources_console_fonts faad) target_link_libraries(AlberCore PUBLIC glad capstone fmt::fmt teakra) if(ENABLE_DISCORD_RPC AND NOT ANDROID) diff --git a/include/audio/aac_decoder.hpp b/include/audio/aac_decoder.hpp index 8964e1f..9d17c3a 100644 --- a/include/audio/aac_decoder.hpp +++ b/include/audio/aac_decoder.hpp @@ -4,14 +4,14 @@ #include "audio/aac.hpp" #include "helpers.hpp" -struct AAC_DECODER_INSTANCE; - namespace Audio::AAC { + // PlayAgain: decodes with FAAD2 (GPL-2.0-or-later) in place of fdk-aac, whose licence the FSF counts as GPL-incompatible. class Decoder { - using DecoderHandle = AAC_DECODER_INSTANCE*; + using DecoderHandle = void*; // NeAACDecHandle using PaddrCallback = std::function; DecoderHandle decoderHandle = nullptr; + bool streamInitialized = false; // NeAACDecInit has read the stream's first ADTS header bool isInitialized() { return decoderHandle != nullptr; } void initialize(); @@ -20,6 +20,8 @@ namespace Audio::AAC { // Decode function. Takes in a reference to the AAC response & request, and a callback for paddr -> pointer conversions // We also allow for optionally muting the AAC output (setting all of it to 0) instead of properly decoding it, for debug/research purposes void decode(AAC::Message& response, const AAC::Message& request, PaddrCallback paddrCallback, bool enableAudio = true); + // The DSP's Init command: the next decode starts a new stream (which may have another sample rate) + void reset(); ~Decoder(); }; -} // namespace Audio::AAC \ No newline at end of file +} // namespace Audio::AAC diff --git a/include/audio/audio_device.hpp b/include/audio/audio_device.hpp index 966fd66..e0646da 100644 --- a/include/audio/audio_device.hpp +++ b/include/audio/audio_device.hpp @@ -1,9 +1,12 @@ #pragma once -#if defined(__LIBRETRO__) && defined(USE_LIBRETRO_AUDIO_DEVICE) +// PlayAgain: the browser core never opens an audio device of its own (miniaudio's Web Audio backend needs the page's window and would play on +// its main thread); the page drains the DSP's sample ring itself (pa_read_audio in pa_3ds.cpp). The libretro device is that: a holder of the +// ring that is "initialised" so the emulator lets the DSP produce sound, and that plays nothing unless a libretro frontend asks it to. +#if (defined(__LIBRETRO__) && defined(USE_LIBRETRO_AUDIO_DEVICE)) || defined(__EMSCRIPTEN__) #include "audio/libretro_audio_device.hpp" using AudioDevice = LibretroAudioDevice; #else #include "audio/miniaudio_device.hpp" using AudioDevice = MiniAudioDevice; -#endif \ No newline at end of file +#endif diff --git a/include/memory.hpp b/include/memory.hpp index e5a7fca..b0c3b5e 100644 --- a/include/memory.hpp +++ b/include/memory.hpp @@ -323,6 +323,12 @@ class Memory { void setVRAM(u8* pointer) { vram = pointer; } void setDSPMem(u8* pointer) { dspRam = pointer; } void setCPUTicks(const u64& ticks) { cpuTicks = &ticks; } +#ifdef __EMSCRIPTEN__ + // PlayAgain: the guest's clock is the session's, never the host's. The page gives the local wall time at boot (ms since 1970, + // pa_set_clock); it advances with emulated CPU ticks only, so the same session runs the same and the page decides the date. + u64 sessionClockMs = 0; + void setSessionClock(u64 localMsSince1970) { sessionClockMs = localMsSince1970; } +#endif bool allocateMainThreadStack(u32 size); Regions getConsoleRegion(); diff --git a/src/core/PICA/draw_acceleration.cpp b/src/core/PICA/draw_acceleration.cpp index fe21fe1..97263de 100644 --- a/src/core/PICA/draw_acceleration.cpp +++ b/src/core/PICA/draw_acceleration.cpp @@ -7,6 +7,9 @@ #include "PICA/pica_simd.hpp" #include "PICA/regs.hpp" +// PlayAgain: draws the GPU could not fetch (an attribute stride WebGL refuses), run on the CPU instead; read by the browser shim's stats +u64 paUnalignedDraws = 0; + void GPU::getAcceleratedDrawInfo(PICA::DrawAcceleration& accel, bool indexed) { accel.indexed = indexed; accel.totalAttribCount = totalAttribCount; @@ -95,6 +98,11 @@ void GPU::getAcceleratedDrawInfo(PICA::DrawAcceleration& accel, bool indexed) { // So multiplication by 1 becomes a shift by 0, mul by 2 becomes a shift by 1, and mul by 4 becomes a shift by 2 static constexpr u32 sizeShiftPerComponent[4] = {0, 0, 1, 2}; + // PlayAgain: an attribute starts at a multiple of its component size within the vertex, as on the PICA (Citra's and Azahar's + // vertex loader). Without it WebGL rejects the attribute (offsets must be multiples of the type's size) and the draw is lost. + const u32 componentMask = (1u << sizeShiftPerComponent[attribType]) - 1; + attributeOffset = (attributeOffset + componentMask) & ~componentMask; + const u32 inputReg = (inputAttrCfg >> (attributeIndex * 4)) & 0xf; // Mark the attribute as enabled accel.enabledAttributeMask |= 1 << inputReg; @@ -107,7 +115,20 @@ void GPU::getAcceleratedDrawInfo(PICA::DrawAcceleration& accel, bool indexed) { attributeOffset += size << sizeShiftPerComponent[attribType]; } - loaderOffset += loader.size; + // PlayAgain: each loader's data starts on a 4-byte boundary of the vertex buffer (accelerateVertexUpload copies it there), as + // vertexDataSize already assumes; unaligned, the next loader's shorts and floats sat at offsets WebGL refuses. + loaderOffset += (bytes + 3) & ~3; + } + + // PlayAgain: WebGL also wants every stride to be a multiple of the attribute's type size. A loader whose stride is not (a rare layout) + // cannot be fetched by the GPU: such a draw runs its vertex shader on the CPU instead. + static constexpr u32 typeSize[4] = {1, 1, 2, 4}; + bool aligned = true; + for (u32 reg = 0; reg < PICA::DrawAcceleration::maxAttribCount; reg++) { + if ((accel.enabledAttributeMask & (1u << reg)) == 0) continue; + const auto& attr = accel.attributeInfo[reg]; + const u32 size = typeSize[attr.type & 3]; + if ((attr.offset % size) != 0 || (attr.stride % size) != 0) aligned = false; } u32 fixedAttributes = fixedAttribMask; @@ -137,5 +158,6 @@ void GPU::getAcceleratedDrawInfo(PICA::DrawAcceleration& accel, bool indexed) { } } - accel.canBeAccelerated = true; + accel.canBeAccelerated = aligned; + if (!aligned) paUnalignedDraws++; } diff --git a/src/core/PICA/gpu.cpp b/src/core/PICA/gpu.cpp index 0734717..3b56bb1 100644 --- a/src/core/PICA/gpu.cpp +++ b/src/core/PICA/gpu.cpp @@ -300,6 +300,15 @@ void GPU::drawArrays() { u32 attribType = attribInfo & 0x3; // Type of attribute(sbyte/ubyte/short/float) u32 size = (attribInfo >> 2) + 1; // Total number of components + // PlayAgain: an attribute starts at a multiple of its component size within the vertex, as on the PICA (Citra's and Azahar's + // vertex loader); the accelerated path does the same (getAcceleratedDrawInfo), so both paths read the same data + { + static constexpr u32 componentSize[4] = {1, 1, 2, 4}; + const u32 rowStart = vertexBase + attr.offset + (vertexIndex * attr.size); + const u32 mask = componentSize[attribType] - 1; + attrAddress = rowStart + (((attrAddress - rowStart) + mask) & ~mask); + } + // printf("vertex_attribute_strides[%d] = %d\n", attrCount, attr.size); vec4f& attribute = currentAttributes[attrCount]; uint component; // Current component diff --git a/src/core/audio/aac_decoder.cpp b/src/core/audio/aac_decoder.cpp index 58cebda..829507f 100644 --- a/src/core/audio/aac_decoder.cpp +++ b/src/core/audio/aac_decoder.cpp @@ -1,10 +1,31 @@ #include "audio/aac_decoder.hpp" -#include +#include +#include +#include #include using namespace Audio; +// PlayAgain: the DSP's AAC decoder on FAAD2 (GPL-2.0-or-later) instead of fdk-aac. Same requests and responses as before: an ADTS stream in +// guest memory, decoded to 16-bit PCM, one channel per output buffer. Code from FAAD2 is copyright (c) Nero AG, www.nero.com. +namespace { + u32 sampleRateCode(unsigned long rate) { + switch (rate) { + case 8000: return AAC::SampleRate::Rate8000; + case 11025: return AAC::SampleRate::Rate11025; + case 12000: return AAC::SampleRate::Rate12000; + case 16000: return AAC::SampleRate::Rate16000; + case 22050: return AAC::SampleRate::Rate22050; + case 24000: return AAC::SampleRate::Rate24000; + case 32000: return AAC::SampleRate::Rate32000; + case 44100: return AAC::SampleRate::Rate44100; + case 48000: + default: return AAC::SampleRate::Rate48000; + } + } +} // namespace + void AAC::Decoder::decode(AAC::Message& response, const AAC::Message& request, AAC::Decoder::PaddrCallback paddrCallback, bool enableAudio) { // Copy the command and mode fields of the request to the response response.command = request.command; @@ -37,80 +58,77 @@ void AAC::Decoder::decode(AAC::Message& response, const AAC::Message& request, A return; } - u32 bytesValid = request.decodeRequest.size; - u32 bufferSize = request.decodeRequest.size; - - // Each frame is 2048 samples with 2 channels - static constexpr usize frameSize = 2048 * 2; - std::array frame; - std::array, 2> audioStreams; + u32 bytesLeft = request.decodeRequest.size; + if (bytesLeft == 0) return; - while (bytesValid != 0) { - if (aacDecoder_Fill(decoderHandle, &input, &bufferSize, &bytesValid) != AAC_DEC_OK) { - Helpers::warn("Failed to fill AAC decoder with samples"); + // FAAD2 learns the stream's object type, rate and channels from its first header + if (!streamInitialized) { + unsigned long rate = 0; + unsigned char channels = 0; + const long skipped = NeAACDecInit(decoderHandle, input, bytesLeft, &rate, &channels); + if (skipped < 0) { + Helpers::warn("AAC decoder: not an ADTS stream"); return; } + streamInitialized = true; + input += std::min(u32(skipped), bytesLeft); + bytesLeft -= std::min(u32(skipped), bytesLeft); + } - auto decodeResult = aacDecoder_DecodeFrame(decoderHandle, frame.data(), frameSize, 0); - - if (decodeResult == AAC_DEC_TRANSPORT_SYNC_ERROR) { - // https://android.googlesource.com/platform/external/aac/+/2ddc922/libAACdec/include/aacdecoder_lib.h#362 - // According to the above, if we get a sync error, we're not meant to stop decoding, but rather just continue feeding data - } else if (decodeResult == AAC_DEC_OK) { - auto getSampleRate = [](u32 rate) { - switch (rate) { - case 8000: return AAC::SampleRate::Rate8000; - case 11025: return AAC::SampleRate::Rate11025; - case 12000: return AAC::SampleRate::Rate12000; - case 16000: return AAC::SampleRate::Rate16000; - case 22050: return AAC::SampleRate::Rate22050; - case 24000: return AAC::SampleRate::Rate24000; - case 32000: return AAC::SampleRate::Rate32000; - case 44100: return AAC::SampleRate::Rate44100; - case 48000: - default: return AAC::SampleRate::Rate48000; - } - }; + std::array, 2> audioStreams; - auto info = aacDecoder_GetStreamInfo(decoderHandle); - response.decodeResponse.sampleCount = info->frameSize; - response.decodeResponse.channelCount = info->numChannels; - response.decodeResponse.sampleRate = getSampleRate(info->sampleRate); + while (bytesLeft != 0) { + NeAACDecFrameInfo info; + std::memset(&info, 0, sizeof(info)); + const s16* frame = static_cast(NeAACDecDecode(decoderHandle, &info, input, bytesLeft)); - int channels = info->numChannels; - // Reserve space in our output stream vectors so push_back doesn't do allocations - for (int i = 0; i < channels; i++) { - audioStreams[i].reserve(audioStreams[i].size() + info->frameSize); - } + if (info.error != 0) { + // A damaged frame: FAAD2 has skipped what it consumed; stop if it consumed nothing (it cannot resynchronise in this buffer) + Helpers::warn("AAC decoder: %s", NeAACDecGetErrorMessage(info.error)); + if (info.bytesconsumed == 0) break; + } - // Fetch output pointer for right output channel if we've got > 1 channel - if (channels > 1 && outputRight == nullptr) { - outputRight = paddrCallback(request.decodeRequest.destAddrRight); - // If the right output channel doesn't point to a proper padddr, return - if (outputRight == nullptr) { - Helpers::warn("Right AAC output channel doesn't point to valid physical address"); - return; - } + const u32 consumed = std::min(u32(info.bytesconsumed), bytesLeft); + if (consumed == 0) break; + input += consumed; + bytesLeft -= consumed; + + if (info.error != 0 || frame == nullptr || info.samples == 0 || info.channels == 0) continue; + + const int channels = std::min(info.channels, 2); + const usize frameSize = info.samples / info.channels; // samples per channel + response.decodeResponse.channelCount = u32(channels); + response.decodeResponse.sampleRate = sampleRateCode(info.samplerate); + + // Fetch output pointer for right output channel if we've got > 1 channel + if (channels > 1 && outputRight == nullptr) { + outputRight = paddrCallback(request.decodeRequest.destAddrRight); + // If the right output channel doesn't point to a proper padddr, return + if (outputRight == nullptr) { + Helpers::warn("Right AAC output channel doesn't point to valid physical address"); + return; } + } + for (int stream = 0; stream < channels; stream++) { + auto& out = audioStreams[stream]; if (enableAudio) { - for (int sample = 0; sample < info->frameSize; sample++) { - for (int stream = 0; stream < channels; stream++) { - audioStreams[stream].push_back(frame[(sample * channels) + stream]); - } + out.reserve(out.size() + frameSize); + for (usize sample = 0; sample < frameSize; sample++) { + out.push_back(frame[sample * info.channels + stream]); } } else { // If audio is not enabled, push 0s - for (int stream = 0; stream < channels; stream++) { - audioStreams[stream].resize(audioStreams[stream].size() + info->frameSize, 0); - } + out.resize(out.size() + frameSize, 0); } - } else { - Helpers::warn("Failed to decode AAC frame"); - return; } } + // The samples written per channel, over every frame of the buffer (as Azahar answers) + if (!audioStreams[0].empty()) { + response.decodeResponse.sampleCount = u32(audioStreams[0].size()); + } + for (int i = 0; i < 2; i++) { auto& stream = audioStreams[i]; u8* pointer = (i == 0) ? outputLeft : outputRight; @@ -122,23 +140,31 @@ void AAC::Decoder::decode(AAC::Message& response, const AAC::Message& request, A } void AAC::Decoder::initialize() { - decoderHandle = aacDecoder_Open(TRANSPORT_TYPE::TT_MP4_ADTS, 1); + decoderHandle = NeAACDecOpen(); + streamInitialized = false; if (decoderHandle == nullptr) [[unlikely]] { return; } - // Cap output channel count to 2 - if (aacDecoder_SetParam(decoderHandle, AAC_PCM_MAX_OUTPUT_CHANNELS, 2) != AAC_DEC_OK) [[unlikely]] { - aacDecoder_Close(decoderHandle); + // 16-bit PCM out, at most two channels (a 5.1 stream is mixed down), plain AAC-LC unless the stream says otherwise + NeAACDecConfigurationPtr config = NeAACDecGetCurrentConfiguration(decoderHandle); + config->defObjectType = LC; + config->outputFormat = FAAD_FMT_16BIT; + config->downMatrix = 1; + if (NeAACDecSetConfiguration(decoderHandle, config) == 0) [[unlikely]] { + NeAACDecClose(decoderHandle); decoderHandle = nullptr; return; } } -AAC::Decoder::~Decoder() { +void AAC::Decoder::reset() { if (isInitialized()) { - aacDecoder_Close(decoderHandle); + NeAACDecClose(decoderHandle); decoderHandle = nullptr; } + streamInitialized = false; } + +AAC::Decoder::~Decoder() { reset(); } diff --git a/src/core/audio/hle_core.cpp b/src/core/audio/hle_core.cpp index 86100b0..a5da299 100644 --- a/src/core/audio/hle_core.cpp +++ b/src/core/audio/hle_core.cpp @@ -785,6 +785,12 @@ namespace Audio { break; case AAC::Command::Init: + // PlayAgain: a new stream follows (FAAD2 reads its rate and channels from its first header), as Azahar does + aacDecoder->reset(); + response = request; + response.resultCode = AAC::ResultCode::Success; + break; + case AAC::Command::Shutdown: case AAC::Command::LoadState: case AAC::Command::SaveState: diff --git a/src/core/memory.cpp b/src/core/memory.cpp index f962b8d..2692474 100644 --- a/src/core/memory.cpp +++ b/src/core/memory.cpp @@ -588,6 +588,12 @@ u8* Memory::mapSharedMemory(Handle handle, u32 vaddr, u32 myPerms, u32 otherPerm // Get the number of ms since Jan 1 1900 u64 Memory::timeSince3DSEpoch() { +#ifdef __EMSCRIPTEN__ + // PlayAgain: the session clock (see setSessionClock), advanced by the ticks emulated since boot (268,111,856 a second) + constexpr u64 msFrom1900To1970 = 2208988800000ull; + const u64 ticks = cpuTicks ? *cpuTicks : 0; + return msFrom1900To1970 + sessionClockMs + ticks * 1000ull / 268111856ull; +#endif using namespace std::chrono; std::time_t rawTime = std::time(nullptr); // Get current UTC time diff --git a/src/core/renderer_gl/renderer_gl.cpp b/src/core/renderer_gl/renderer_gl.cpp index 775be01..53f95ee 100644 --- a/src/core/renderer_gl/renderer_gl.cpp +++ b/src/core/renderer_gl/renderer_gl.cpp @@ -1468,7 +1468,7 @@ void RendererGL::accelerateVertexUpload(ShaderUnit& shaderUnit, PICA::DrawAccele auto& loader = accel->loaders[i]; std::memcpy(vertexData, loader.data, loader.size); - vertexData += loader.size; + vertexData += (loader.size + 3) & ~usize(3); // PlayAgain: every loader starts 4-byte aligned (see getAcceleratedDrawInfo) } hwVertexBuffer->Unmap(accel->vertexDataSize); diff --git a/src/core/services/ssl.cpp b/src/core/services/ssl.cpp index 8d373bb..ef6d43d 100644 --- a/src/core/services/ssl.cpp +++ b/src/core/services/ssl.cpp @@ -35,7 +35,11 @@ void SSLService::initialize(u32 messagePointer) { } initialized = true; +#ifdef __EMSCRIPTEN__ + rng.seed(std::mt19937::default_seed); // PlayAgain: a fixed seed, so a session replays the same (no host entropy reaches the guest) +#else rng.seed(std::random_device()()); // Seed rng via std::random_device +#endif mem.write32(messagePointer + 4, Result::Success); } diff --git a/src/emulator.cpp b/src/emulator.cpp index e5ba4e2..7ca9103 100644 --- a/src/emulator.cpp +++ b/src/emulator.cpp @@ -1,9 +1,10 @@ #include "emulator.hpp" -#if !defined(__ANDROID__) && !defined(__LIBRETRO__) +#if !defined(__ANDROID__) && !defined(__LIBRETRO__) && !defined(__EMSCRIPTEN__) #include #endif +#include #include #include "renderdoc.hpp" @@ -203,6 +204,9 @@ std::filesystem::path Emulator::getAppDataRoot() { #ifdef __ANDROID__ appDataPath = getAndroidAppPath(); +#elif defined(__EMSCRIPTEN__) + // PlayAgain: one fixed folder in the module's file system; the page owns what is in it (game saves, the DSP firmware stand-in) + appDataPath = std::filesystem::path("/pa/3ds/"); #else char* appData; if (!config.usePortableBuild) { @@ -234,7 +238,9 @@ bool Emulator::loadROM(const std::filesystem::path& path) { const std::filesystem::path aesKeysPath = appDataPath / "sysdata" / "aes_keys.txt"; const std::filesystem::path seedDBPath = appDataPath / "sysdata" / "seeddb.bin"; +#ifndef __EMSCRIPTEN__ IOFile::setAppDataDir(dataPath); +#endif // Open the text file containing our AES keys if it exists. We use the std::filesystem::exists overload that takes an error code param to // avoid the call throwing exceptions @@ -247,7 +253,9 @@ bool Emulator::loadROM(const std::filesystem::path& path) { aesEngine.setSeedPath(seedDBPath); } +#ifndef __EMSCRIPTEN__ kernel.initializeFS(); +#endif auto extension = path.extension(); bool success; // Tracks if we loaded the ROM successfully @@ -264,6 +272,23 @@ bool Emulator::loadROM(const std::filesystem::path& path) { success = false; } +#ifdef __EMSCRIPTEN__ + // PlayAgain: a game's folder (its saves, SD card and ext data) is named after its title (program) ID from the NCCH header, not after the + // file, so a renamed or re-picked file keeps its saves: /saves/<16 hex digits>/. Homebrew without one (.3dsx/.elf) is keyed + // by its file name. Set once the header is read and before the file system is set up; loading a game touches neither. + if (success) { + const std::optional programID = memory.getProgramID(); + char folder[64]; + if (programID.has_value() && *programID != 0) { + std::snprintf(folder, sizeof(folder), "%016llx", static_cast(*programID)); + } else { + std::snprintf(folder, sizeof(folder), "homebrew-%.40s", path.filename().stem().string().c_str()); + } + IOFile::setAppDataDir(appDataPath / "saves" / folder); + kernel.initializeFS(); + } +#endif + if (success) { romPath = path; #ifdef PANDA3DS_ENABLE_DISCORD_RPC --- a/include/PICA/gpu.hpp +++ b/include/PICA/gpu.hpp @@ -108,7 +108,15 @@ GPU(Memory& mem, EmulatorConfig& config); void display() { renderer->display(); } void screenshot(const std::string& name) { renderer->screenshot(name); } - void deinitGraphicsContext() { renderer->deinitGraphicsContext(); } + // PlayAgain: what the GPU remembers of GL objects that are gone goes with them. The next draw writes the vertex + // shader's uniforms and the lighting and fog tables again (a save state's memory image is loaded into a fresh context). + void deinitGraphicsContext() { + renderer->deinitGraphicsContext(); + shaderUnit.vs.uniformsDirty = true; + lightingLUTDirty = true; + lightingLUTDirtyMask = (1u << PICA::Lights::LUT_Count) - 1; + fogLUTDirty = true; + } void initGraphicsContext(void* context) { renderer->initGraphicsContext(context); } --- a/src/core/renderer_gl/renderer_gl.cpp +++ b/src/core/renderer_gl/renderer_gl.cpp @@ -1327,6 +1327,16 @@ depthBufferCache.reset(); colourBufferCache.reset(); shaderCache.clear(); + + // PlayAgain: so is what the renderer remembers about them: which attributes the hardware-shader VAO has enabled, the + // vertex shader in use and where the uniform blocks were last written. Left as they were, the first draws after + // initGraphicsContext go out with no vertex attributes enabled (a black picture). + previousAttributeMask = 0; + generatedVertexShader = nullptr; + usingAcceleratedShader = false; + hwShaderUniformUBOOffset = 0; + prevFragmentUBOOffset = 0; + hasPrevFragmentUniforms = false; // All other GL objects should be invalidated automatically and be recreated by the next call to initGraphicsContext // TODO: Make it so that depth and colour buffers get written back to 3DS memory