### Netplay Session Example (C++) Source: https://context7.com/sourmesen/mesen2/llms.txt Example demonstrating how to host a server, load a game, and connect to the session as a player or spectator. ```cpp // Example: Host a netplay session StartServer(8888, "secretpass"); printf("Server running: %s\n", IsServerRunning() ? "yes" : "no"); // Load a game and wait for players LoadRom("game.nes", nullptr); // Example: Connect to a session as player Connect("192.168.1.100", 8888, "secretpass", false); while (!IsConnected()) { Sleep(100); } printf("Connected!\n"); // Example: Connect as spectator Connect("192.168.1.100", 8888, "secretpass", true); ``` -------------------------------- ### Initialize and Control Debugger Source: https://context7.com/sourmesen/mesen2/llms.txt Provides functions to start, stop, and inspect the emulator state via the debugger. ```cpp DllExport void __stdcall InitializeDebugger(); DllExport void __stdcall ReleaseDebugger(); DllExport bool __stdcall IsDebuggerRunning(); DllExport bool __stdcall IsExecutionStopped(); DllExport void __stdcall ResumeExecution(); // Example: Initialize debugger and wait for breakpoint InitializeDebugger(); while (IsRunning()) { if (IsExecutionStopped()) { // Execution hit breakpoint - inspect state printf("Stopped at PC: 0x%04X\n", GetProgramCounter(CpuType::Nes, false)); ResumeExecution(); } Sleep(16); } ``` -------------------------------- ### Start and Stop Netplay Server (C++) Source: https://context7.com/sourmesen/mesen2/llms.txt Use these functions to host a netplay session. Ensure the port is not in use and a password is set for security. ```cpp DllExport void __stdcall StartServer(uint16_t port, char* password); DllExport void __stdcall StopServer(); DllExport bool __stdcall IsServerRunning(); ``` -------------------------------- ### Get Emulator State (Lua) Source: https://context7.com/sourmesen/mesen2/llms.txt Retrieve the complete emulator state as a Lua table, including frame count, master clock, console type, region, and CPU registers. ```lua -- Get complete emulator state as table local state = emu.getState() -- Access common values ému.log("Frame: " .. state["frameCount"]) ému.log("Master Clock: " .. state["masterClock"]) ému.log("Console: " .. state["consoleType"]) ému.log("Region: " .. state["region"]) -- Access CPU registers (varies by console/CPU) -- NES: cpu.a, cpu.x, cpu.y, cpu.sp, cpu.pc, cpu.ps -- SNES: cpu.a, cpu.x, cpu.y, cpu.sp, cpu.pc, cpu.db, cpu.d -- GB: cpu.a, cpu.b, cpu.c, cpu.d, cpu.e, cpu.h, cpu.l, cpu.sp, cpu.pc ému.log("PC: " .. string.format("%04X", state["cpu.pc"])) ému.log("A: " .. string.format("%02X", state["cpu.a"]))) ``` -------------------------------- ### Get Screen Dimensions (Lua) Source: https://context7.com/sourmesen/mesen2/llms.txt Retrieve the current screen dimensions (width and height) of the selected drawing surface. ```lua -- Get screen dimensions local size = emu.getScreenSize() ému.log("Screen: " .. size.width .. "x" .. size.height) ``` -------------------------------- ### Get Memory Size (Lua) Source: https://context7.com/sourmesen/mesen2/llms.txt Retrieve the size of a specific memory type for the current console. ```lua -- Get memory size local ramSize = emu.getMemorySize(emu.memType.nesMemory) ``` -------------------------------- ### InitializeEmu Source: https://context7.com/sourmesen/mesen2/llms.txt Initializes the emulator with window handles and rendering configuration, setting up the rendering device, audio system, and input manager. ```APIDOC ## InitializeEmu ### Description Initializes the emulator with window handles and rendering configuration. This function sets up the rendering device, audio system, and input manager for the specified platform. ### Method `DllExport void __stdcall InitializeEmu` ### Parameters #### Path Parameters - **homeFolder** (const char*) - Required - Path to store emulator data (saves, settings) - **windowHandle** (void*) - Required - Platform window handle for audio/input - **viewerHandle** (void*) - Required - Handle for video rendering surface - **softwareRenderer** (bool) - Required - true for software rendering, false for hardware - **noAudio** (bool) - Required - Disable audio subsystem if needed - **noVideo** (bool) - Required - Disable video subsystem if needed - **noInput** (bool) - Required - Disable input subsystem if needed ### Request Example ```cpp // Initialize with hardware rendering on Windows InitializeEmu("C:/MesenData", hwnd, viewerHwnd, false, false, false, false); // Initialize headless for automated testing InitializeEmu("/tmp/mesen", nullptr, nullptr, true, true, true, true); ``` ``` -------------------------------- ### Initialize Mesen Emulator Source: https://context7.com/sourmesen/mesen2/llms.txt Initializes the emulator with window handles and rendering configuration. Specify subsystem enablement and renderer type. Use nullptr for headless operation. ```cpp DllExport void __stdcall InitializeEmu( const char* homeFolder, void* windowHandle, void* viewerHandle, bool softwareRenderer, bool noAudio, bool noVideo, bool noInput ); // Example: Initialize with hardware rendering on Windows InitializeEmu("C:/MesenData", hwnd, viewerHwnd, false, false, false, false); // Example: Initialize headless for automated testing InitializeEmu("/tmp/mesen", nullptr, nullptr, true, true, true, true); ``` -------------------------------- ### Implement a Memory Monitor with Lua Source: https://context7.com/sourmesen/mesen2/llms.txt A comprehensive script demonstrating memory reading, HUD drawing, and event callbacks for tracking game state. ```lua ----------------------- -- NES Memory Monitor -- Displays player stats and provides save state hotkeys ----------------------- -- Configuration local PLAYER_LIVES_ADDR = 0x0075 local PLAYER_SCORE_ADDR = 0x0079 local PLAYER_COINS_ADDR = 0x007E -- State local lastLives = 0 local saveSlot = {} function onFrame() -- Read game memory local lives = emu.read(PLAYER_LIVES_ADDR, emu.memType.nesMemory) local score = emu.read(PLAYER_SCORE_ADDR, emu.memType.nesMemory) * 100 local coins = emu.read(PLAYER_COINS_ADDR, emu.memType.nesMemory) -- Detect life loss if lives < lastLives then emu.log("Lost a life! " .. lastLives .. " -> " .. lives) end lastLives = lives -- Draw HUD overlay emu.drawRectangle(2, 2, 80, 35, 0x80000000, true) emu.drawString(5, 5, "Lives: " .. lives, 0xFFFFFF, 0x000000) emu.drawString(5, 15, "Score: " .. score, 0xFFFFFF, 0x000000) emu.drawString(5, 25, "Coins: " .. coins, 0xFFFFFF, 0x000000) -- Quick save/load hotkeys for i = 1, 4 do if emu.isKeyPressed("F" .. (i + 4)) then -- F5-F8 to save saveSlot[i] = emu.createSavestate() emu.displayMessage("Script", "Saved to slot " .. i) end if emu.isKeyPressed("F" .. i) then -- F1-F4 to load if saveSlot[i] then emu.loadSavestate(saveSlot[i]) emu.displayMessage("Script", "Loaded slot " .. i) end end end end -- Watch for writes to lives address function onLivesWrite() local newValue = emu.read(PLAYER_LIVES_ADDR, emu.memType.nesMemory) emu.log("Lives changed to: " .. newValue) end -- Register callbacks emu.addEventCallback(onFrame, emu.eventType.endFrame) emu.addMemoryCallback(onLivesWrite, emu.callbackType.write, PLAYER_LIVES_ADDR) -- Startup message emu.displayMessage("Script", "Memory Monitor loaded!") emu.log("Press F1-F4 to load, F5-F8 to save") ``` -------------------------------- ### Configure Console Emulation Settings Source: https://context7.com/sourmesen/mesen2/llms.txt Sets specific emulation parameters and controller mappings for various consoles. ```cpp DllExport void __stdcall SetNesConfig(NesConfig config); DllExport void __stdcall SetSnesConfig(SnesConfig config); DllExport void __stdcall SetGameboyConfig(GameboyConfig config); DllExport void __stdcall SetGbaConfig(GbaConfig config); DllExport void __stdcall SetPcEngineConfig(PcEngineConfig config); DllExport void __stdcall SetSmsConfig(SmsConfig config); DllExport void __stdcall SetWsConfig(WsConfig config); // Example: Configure NES controller NesConfig nesConfig = GetNesConfig(); nesConfig.Port1.Type = ControllerType::NesController; nesConfig.Port1.Keys.Mapping1.A = KEY_Z; nesConfig.Port1.Keys.Mapping1.B = KEY_X; nesConfig.Port1.Keys.Mapping1.Start = KEY_ENTER; nesConfig.Port1.Keys.Mapping1.Select = KEY_RSHIFT; SetNesConfig(nesConfig); // Example: Configure Game Boy as Game Boy Color GameboyConfig gbConfig = {}; gbConfig.Model = GameboyModel::GameboyColor; gbConfig.Controller.Keys.Mapping1.A = KEY_Z; gbConfig.Controller.Keys.Mapping1.B = KEY_X; SetGameboyConfig(gbConfig); ``` -------------------------------- ### Connect to Netplay Session (C++) Source: https://context7.com/sourmesen/mesen2/llms.txt Connect to an existing netplay session as a player or spectator. The `spectator` flag determines the connection type. ```cpp DllExport void __stdcall Connect(char* host, uint16_t port, char* password, bool spectator); DllExport void __stdcall Disconnect(); DllExport bool __stdcall IsConnected(); ``` -------------------------------- ### Console Configuration API Source: https://context7.com/sourmesen/mesen2/llms.txt Configure emulation settings for supported console types including controller mappings. ```APIDOC ## Console Configuration ### Description Configure emulation settings for each supported console type (NES, SNES, Gameboy, GBA, PC Engine, SMS, Ws). ### Methods - SetNesConfig(NesConfig config) - SetSnesConfig(SnesConfig config) - SetGameboyConfig(GameboyConfig config) - SetGbaConfig(GbaConfig config) - SetPcEngineConfig(PcEngineConfig config) - SetSmsConfig(SmsConfig config) - SetWsConfig(WsConfig config) ``` -------------------------------- ### Record video and audio Source: https://context7.com/sourmesen/mesen2/llms.txt Capture gameplay to AVI or WAV files using the recording API. ```cpp struct RecordAviOptions { uint32_t Codec; uint32_t CompressionLevel; }; DllExport void __stdcall AviRecord(char* filename, RecordAviOptions options); DllExport void __stdcall AviStop(); DllExport bool __stdcall AviIsRecording(); DllExport void __stdcall WaveRecord(char* filename); DllExport void __stdcall WaveStop(); DllExport bool __stdcall WaveIsRecording(); // Example: Record video with compression RecordAviOptions opts = {}; opts.Codec = 0; // ZMBV codec opts.CompressionLevel = 6; AviRecord("gameplay.avi", opts); // Record for 60 seconds then stop Sleep(60000); AviStop(); // Example: Record audio only WaveRecord("soundtrack.wav"); ``` -------------------------------- ### Step through emulator execution Source: https://context7.com/sourmesen/mesen2/llms.txt Use the Step function to advance the emulator by instructions, cycles, scanlines, or frames. ```cpp enum class StepType { Step, // Single instruction StepOut, // Run until return StepOver, // Step over subroutines CpuCycleStep, // Single CPU cycle PpuStep, // Single PPU cycle PpuScanline, // One scanline PpuFrame, // One frame SpecificScanline }; DllExport void __stdcall Step(CpuType cpuType, uint32_t count, StepType type); // Example: Step one instruction on NES CPU Step(CpuType::Nes, 1, StepType::Step); // Example: Step to next frame Step(CpuType::Snes, 1, StepType::PpuFrame); // Example: Step over a subroutine call Step(CpuType::Gameboy, 1, StepType::StepOver); ``` -------------------------------- ### Recording API Source: https://context7.com/sourmesen/mesen2/llms.txt Record gameplay to AVI video or WAV audio files. ```APIDOC ## AviRecord / WaveRecord ### Description Record gameplay to AVI video or WAV audio files. ### Methods - AviRecord(char* filename, RecordAviOptions options) - AviStop() - WaveRecord(char* filename) - WaveStop() ### Request Example RecordAviOptions opts = {}; opts.Codec = 0; opts.CompressionLevel = 6; AviRecord("gameplay.avi", opts); ``` -------------------------------- ### GetRomInfo Source: https://context7.com/sourmesen/mesen2/llms.txt Retrieves detailed information about the currently loaded ROM, including path, format, console type, and CPU types. ```APIDOC ## GetRomInfo ### Description Retrieves detailed information about the currently loaded ROM including path, format, console type, and available CPU types. ### Method `DllExport void __stdcall GetRomInfo` ### Parameters #### Path Parameters - **info** (InteropRomInfo&) - Output - Structure to be filled with ROM information. ### Request Example ```cpp InteropRomInfo info; GetRomInfo(info); printf("ROM: %s\n", info.RomPath); printf("Console: %d\n", info.Console); printf("CPU Count: %d\n", info.CpuTypeCount); ``` ### Response #### Success Response (200) - **InteropRomInfo** (struct) - Contains details about the loaded ROM: - **RomPath** (char[2000]) - Path to the ROM file. - **PatchPath** (char[2000]) - Path to the applied patch file, if any. - **Format** (RomFormat) - The format of the ROM. - **Console** (ConsoleType) - The console type (Snes=0, Gameboy=1, Nes=2, PcEngine=3, Sms=4, Gba=5, Ws=6). - **DipSwitches** (DipSwitchInfo) - Information about DIP switches. - **CpuTypes** (CpuType[5]) - Array of supported CPU types. - **CpuTypeCount** (uint32_t) - Number of supported CPU types. ``` -------------------------------- ### Create and Load Savestates (Lua) Source: https://context7.com/sourmesen/mesen2/llms.txt Create a savestate from the current emulator state or load a previously saved state. This functionality is restricted to execution callbacks. ```lua -- Create and load savestates (in exec callbacks only) local savedata = emu.createSavestate() -- ... later ... ému.loadSavestate(savedata) ``` -------------------------------- ### SetAudioConfig Source: https://context7.com/sourmesen/mesen2/llms.txt Configures audio output including device selection, volume, latency, and equalizer settings. ```APIDOC ## SetAudioConfig ### Description Configures audio output including device selection, volume, latency, and equalizer settings. ### Request Body - **AudioDevice** (const char*) - Audio device identifier - **EnableAudio** (bool) - Enable/disable audio - **MasterVolume** (uint32_t) - Volume level (0-100) - **SampleRate** (uint32_t) - Audio sample rate - **AudioLatency** (uint32_t) - Latency in milliseconds - **MuteSoundInBackground** (bool) - Mute when window is in background - **ReduceSoundInBackground** (bool) - Reduce volume when window is in background - **EnableEqualizer** (bool) - Enable/disable equalizer - **Band1Gain** (double) - Gain for EQ bands ``` -------------------------------- ### Manage Save States Source: https://context7.com/sourmesen/mesen2/llms.txt Handles saving and loading emulation states using quick-save slots or custom file paths. Includes a function to retrieve a preview image of a save state. ```cpp DllExport void __stdcall SaveState(uint32_t stateIndex); DllExport void __stdcall LoadState(uint32_t stateIndex); DllExport void __stdcall SaveStateFile(char* filepath); DllExport void __stdcall LoadStateFile(char* filepath); DllExport int32_t __stdcall GetSaveStatePreview(char* saveStatePath, uint8_t* pngData); // Example: Quick save to slot 1 SaveState(1); // Example: Load from slot 1 LoadState(1); // Example: Save to custom file SaveStateFile("speedrun_checkpoint.mss"); // Example: Get save state preview image uint8_t pngBuffer[1024 * 1024]; int32_t pngSize = GetSaveStatePreview("save.mss", pngBuffer); if (pngSize > 0) { // Write PNG to file for display } ``` -------------------------------- ### Configure emulator breakpoints Source: https://context7.com/sourmesen/mesen2/llms.txt Define memory and execution breakpoints using the Breakpoint structure and SetBreakpoints function. ```cpp struct Breakpoint { uint32_t Id; CpuType CpuType; MemoryType MemoryType; BreakpointTypeFlags Type; // Read=1, Write=2, Execute=4 int32_t StartAddr; int32_t EndAddr; bool Enabled; char Condition[1000]; // Expression like "A == $50" }; DllExport void __stdcall SetBreakpoints(Breakpoint breakpoints[], uint32_t length); // Example: Break on NES CPU execution at $8000 Breakpoint bp = {}; bp.Id = 1; bp.CpuType = CpuType::Nes; bp.MemoryType = MemoryType::NesMemory; bp.Type = BreakpointTypeFlags::Execute; bp.StartAddr = 0x8000; bp.EndAddr = 0x8000; bp.Enabled = true; SetBreakpoints(&bp, 1); // Example: Break on RAM write to $0200-$02FF with condition Breakpoint bp2 = {}; bp2.Id = 2; bp2.CpuType = CpuType::Nes; bp2.MemoryType = MemoryType::NesMemory; bp2.Type = BreakpointTypeFlags::Write; bp2.StartAddr = 0x0200; bp2.EndAddr = 0x02FF; bp2.Enabled = true; strcpy(bp2.Condition, "value > $80"); SetBreakpoints(&bp2, 1); ``` -------------------------------- ### Lua Scripting API - Callback Registration Source: https://context7.com/sourmesen/mesen2/llms.txt Register callbacks for memory access and emulation events. ```APIDOC ## Lua Scripting API - Callback Registration Register callbacks for memory access and emulation events to create custom behaviors. ### Memory Callbacks - `emu.addMemoryCallback(handler, callbackType, startAddress, [endAddress])`: Registers a `handler` function for a specific `callbackType` (e.g., `emu.callbackType.read`, `emu.callbackType.write`, `emu.callbackType.exec`) at a given `startAddress` (and optional `endAddress` for ranges). - `emu.removeMemoryCallback(callbackId, callbackType, address)`: Removes a previously registered memory callback. ### Event Callbacks - `emu.addEventCallback(handler, eventType)`: Registers a `handler` function for a specific `eventType` (e.g., `emu.eventType.startFrame`, `emu.eventType.endFrame`, `emu.eventType.reset`, `emu.eventType.inputPolled`). ### Callback Types - **Memory**: `emu.callbackType.read`, `emu.callbackType.write`, `emu.callbackType.exec` - **Event**: `emu.eventType.startFrame`, `emu.eventType.endFrame`, `emu.eventType.reset`, `emu.eventType.inputPolled`, `emu.eventType.saveStateLoad`, `emu.eventType.saveStateSave`, `emu.eventType.pause`, `emu.eventType.resume`, `emu.eventType.fastForwardStart`, `emu.eventType.fastForwardStop`, `emu.eventType.movieBegin`, `emu.eventType.movieEnd`, `emu.eventType.movieFrame` ### Example Usage ```lua -- Memory read callback function onReadHandler() local value = emu.read(0x0000, emu.memType.nesMemory) emu.log("RAM $0000 read: " .. value) end local callbackId = emu.addMemoryCallback(onReadHandler, emu.callbackType.read, 0x0000) -- Write callback for address range function onWriteHandler() emu.log("Write to sprite DMA area!") end ému.addMemoryCallback(onWriteHandler, emu.callbackType.write, 0x0200, 0x02FF) -- Frame end event callback function onFrameEnd() local state = emu.getState() emu.drawString(10, 10, "Frame: " .. state["frameCount"], 0xFFFFFF) end ému.addEventCallback(onFrameEnd, emu.eventType.endFrame) -- Remove callbacks ému.removeMemoryCallback(callbackId, emu.callbackType.read, 0x0000) ``` ``` -------------------------------- ### Configure Audio Output Settings Source: https://context7.com/sourmesen/mesen2/llms.txt Manages audio device, volume, latency, and equalizer settings. The AudioConfig struct is required for SetAudioConfig. ```cpp struct AudioConfig { const char* AudioDevice; bool EnableAudio; uint32_t MasterVolume; // 0-100 uint32_t SampleRate; // Default: 48000 uint32_t AudioLatency; // Milliseconds bool MuteSoundInBackground; bool ReduceSoundInBackground; bool EnableEqualizer; double Band1Gain; // 20 band EQ: Band1Gain to Band20Gain }; DllExport void __stdcall SetAudioConfig(AudioConfig config); // Example: Configure low-latency audio AudioConfig audio = {}; audio.EnableAudio = true; audio.MasterVolume = 80; audio.SampleRate = 48000; audio.AudioLatency = 30; audio.MuteSoundInBackground = true; SetAudioConfig(audio); ``` -------------------------------- ### Retrieve ROM Information Source: https://context7.com/sourmesen/mesen2/llms.txt Fetches detailed information about the loaded ROM, including file paths, format, console type, and CPU details. The `InteropRomInfo` struct holds the returned data. ```cpp struct InteropRomInfo { char RomPath[2000]; char PatchPath[2000]; RomFormat Format; ConsoleType Console; // Snes=0, Gameboy=1, Nes=2, PcEngine=3, Sms=4, Gba=5, Ws=6 DipSwitchInfo DipSwitches; CpuType CpuTypes[5]; uint32_t CpuTypeCount; }; DllExport void __stdcall GetRomInfo(InteropRomInfo& info); // Example: Get and display ROM information InteropRomInfo info; GetRomInfo(info); printf("ROM: %s\n", info.RomPath); printf("Console: %d\n", info.Console); printf("CPU Count: %d\n", info.CpuTypeCount); ``` -------------------------------- ### LoadRom Source: https://context7.com/sourmesen/mesen2/llms.txt Loads a ROM file into the emulator, with optional IPS/BPS patch support. Automatically detects console type based on file extension and headers. ```APIDOC ## LoadRom ### Description Loads a ROM file into the emulator with optional IPS/BPS patch support. Automatically detects console type based on file extension and headers. ### Method `DllExport bool __stdcall LoadRom` ### Parameters #### Path Parameters - **filename** (char*) - Required - Path to the ROM file - **patchFile** (char*) - Optional - Path to an IPS or BPS patch file ### Request Example ```cpp // Load an NES ROM bool success = LoadRom("SuperMarioBros.nes", nullptr); // Load a SNES ROM with a patch bool success = LoadRom("game.sfc", "translation.ips"); // Load from archive (ZIP, 7z supported) bool success = LoadRom("roms.zip/game.nes", nullptr); ``` ``` -------------------------------- ### Configure Video Output Settings Source: https://context7.com/sourmesen/mesen2/llms.txt Defines video parameters such as filters, aspect ratio, and color adjustments. Use the VideoConfig struct to pass settings to SetVideoConfig. ```cpp struct VideoConfig { double CustomAspectRatio; VideoFilterType VideoFilter; // None, NtscBlargg, xBRZ2x-6x, HQ2x-4x, Scale2x-4x, etc. VideoAspectRatio AspectRatio; // NoStretching, Auto, NTSC, PAL, Standard, Widescreen bool UseBilinearInterpolation; bool VerticalSync; double Brightness, Contrast, Hue, Saturation; double ScanlineIntensity; uint32_t ScreenRotation; // 0, 90, 180, 270 }; DllExport void __stdcall SetVideoConfig(VideoConfig config); // Example: Configure NTSC filter with scanlines VideoConfig video = {}; video.VideoFilter = VideoFilterType::NtscBlargg; video.AspectRatio = VideoAspectRatio::NTSC; video.ScanlineIntensity = 0.3; video.VerticalSync = true; SetVideoConfig(video); ``` -------------------------------- ### Lua Memory and Event API Source: https://context7.com/sourmesen/mesen2/llms.txt Functions for reading emulator memory, drawing to the screen, and registering callbacks for game events. ```APIDOC ## Lua Memory and Event API ### Description Allows scripts to monitor game memory, draw HUD elements, and trigger logic on specific events like frame updates or memory writes. ### Methods - **emu.read(address, memType)**: Reads a value from the specified memory address. - **emu.drawRectangle(x, y, w, h, color, fill)**: Draws a rectangle on the emulator screen. - **emu.drawString(x, y, text, color, bgColor)**: Draws text on the emulator screen. - **emu.addEventCallback(function, eventType)**: Registers a function to be called on specific emulator events. - **emu.addMemoryCallback(function, callbackType, address)**: Registers a function to be called when a specific memory address is accessed. ``` -------------------------------- ### SetVideoConfig Source: https://context7.com/sourmesen/mesen2/llms.txt Configures video output settings including filters, aspect ratio, and color adjustments. ```APIDOC ## SetVideoConfig ### Description Configures video output settings including filters, aspect ratio, and color adjustments. ### Request Body - **CustomAspectRatio** (double) - Custom aspect ratio value - **VideoFilter** (VideoFilterType) - Filter type (None, NtscBlargg, xBRZ2x-6x, etc.) - **AspectRatio** (VideoAspectRatio) - Aspect ratio mode (NoStretching, Auto, NTSC, etc.) - **UseBilinearInterpolation** (bool) - Enable/disable bilinear interpolation - **VerticalSync** (bool) - Enable/disable VSync - **Brightness** (double) - Brightness level - **Contrast** (double) - Contrast level - **Hue** (double) - Hue level - **Saturation** (double) - Saturation level - **ScanlineIntensity** (double) - Intensity of scanlines - **ScreenRotation** (uint32_t) - Rotation in degrees (0, 90, 180, 270) ``` -------------------------------- ### Lua Scripting API - State Management Source: https://context7.com/sourmesen/mesen2/llms.txt Functions to access and modify emulator state. ```APIDOC ## Lua Scripting API - State Management Access and modify emulator state including CPU registers and system status. ### Functions - `emu.getState()`: Returns the complete emulator state as a Lua table. - `emu.setState(stateTable)`: Sets the emulator state from a provided Lua table. This function should typically only be called within `exec` callbacks. - `emu.createSavestate()`: Creates a savestate. This function should typically only be called within `exec` callbacks. - `emu.loadSavestate(savedata)`: Loads a savestate from the provided `savedata`. This function should typically only be called within `exec` callbacks. ### State Table Contents The state table contains various information, including: - `frameCount`: Current frame count. - `masterClock`: Emulator's master clock value. - `consoleType`: Type of the emulated console. - `region`: Emulated console region. - CPU Registers: Specific registers vary by console. Examples: - NES: `cpu.a`, `cpu.x`, `cpu.y`, `cpu.sp`, `cpu.pc`, `cpu.ps` - SNES: `cpu.a`, `cpu.x`, `cpu.y`, `cpu.sp`, `cpu.pc`, `cpu.db`, `cpu.d` - GB: `cpu.a`, `cpu.b`, `cpu.c`, `cpu.d`, `cpu.e`, `cpu.h`, `cpu.l`, `cpu.sp`, `cpu.pc` ### Example Usage ```lua -- Get complete emulator state local state = emu.getState() -- Access common values ému.log("Frame: " .. state["frameCount"]) ému.log("Master Clock: " .. state["masterClock"]) ému.log("Console: " .. state["consoleType"]) ému.log("Region: " .. state["region"]) -- Access CPU registers (NES example) ému.log("PC: " .. string.format("%04X", state["cpu.pc"])) ému.log("A: " .. string.format("%02X", state["cpu.a"])) -- Modify state (NES example) state["cpu.a"] = 0x50 ému.setState(state) -- Create and load savestates (in exec callbacks only) local savedata = emu.createSavestate() -- ... later ... ému.loadSavestate(savedata) ``` ``` -------------------------------- ### Breakpoint API Source: https://context7.com/sourmesen/mesen2/llms.txt Configure memory and execution breakpoints with optional conditions. ```APIDOC ## SetBreakpoints ### Description Configure memory and execution breakpoints with optional conditions. ### Method DllExport void __stdcall SetBreakpoints(Breakpoint breakpoints[], uint32_t length); ### Parameters - **breakpoints** (Breakpoint[]) - Required - Array of breakpoint structures. - **length** (uint32_t) - Required - Number of breakpoints in the array. ### Request Example Breakpoint bp = {}; bp.Id = 1; bp.CpuType = CpuType::Nes; bp.MemoryType = MemoryType::NesMemory; bp.Type = BreakpointTypeFlags::Execute; bp.StartAddr = 0x8000; bp.EndAddr = 0x8000; bp.Enabled = true; SetBreakpoints(&bp, 1); ``` -------------------------------- ### Lua Scripting API - Drawing Functions Source: https://context7.com/sourmesen/mesen2/llms.txt Functions to draw overlays on the game screen. ```APIDOC ## Lua Scripting API - Drawing Functions Draw overlays on the game screen including text, shapes, and custom graphics. ### Functions - `emu.drawString(x, y, text, textColor, [bgColor], [maxWidth], [frameCount], [delay])`: Draws text at the specified coordinates with optional background color, max width, frame count, and delay. - `emu.drawPixel(x, y, color)`: Draws a single pixel at the given coordinates with the specified color. - `emu.drawLine(x1, y1, x2, y2, color)`: Draws a line between two points with the specified color. - `emu.drawRectangle(x, y, width, height, color, [filled])`: Draws a rectangle at the specified coordinates with the given dimensions and color. `filled` (boolean, optional) determines if the rectangle should be filled. - `emu.clearScreen()`: Clears all drawings from the screen. - `emu.selectDrawSurface(surface, [scale])`: Selects the drawing surface (`emu.drawSurface.consoleScreen` or `emu.drawSurface.scriptHud`) and an optional scale factor. - `emu.getScreenSize()`: Returns the dimensions (width and height) of the current screen. ### Colors Colors are specified in `0xAARRGGBB` format (Alpha, Red, Green, Blue). ### Draw Surfaces - `emu.drawSurface.consoleScreen`: Draws directly on the game output. - `emu.drawSurface.scriptHud`: Draws on a separate overlay, supporting scaling. ### Example Usage ```lua -- Draw text with background ému.drawString(10, 10, "Score: 1000", 0xFFFFFF, 0x000000) -- Draw shapes -- Colors are 0xAARRGGBB format ému.drawPixel(50, 50, 0xFFFF0000) -- Red pixel ému.drawLine(0, 0, 100, 100, 0xFF00FF00) -- Green line ému.drawRectangle(20, 20, 40, 30, 0x80FF0000, true) -- Semi-transparent red filled rect ému.drawRectangle(20, 20, 40, 30, 0xFFFFFFFF, false) -- White border -- Clear screen ému.clearScreen() -- Select drawing surface and scale ému.selectDrawSurface(emu.drawSurface.scriptHud, 2) -- 2x scale -- Get screen dimensions local size = emu.getScreenSize() ému.log("Screen: " .. size.width .. "x" .. size.height) ``` ``` -------------------------------- ### Load ROM File with Optional Patch Source: https://context7.com/sourmesen/mesen2/llms.txt Loads a ROM file, optionally applying an IPS or BPS patch. The function auto-detects the console type. Supports loading from archives like ZIP and 7z. ```cpp DllExport bool __stdcall LoadRom(char* filename, char* patchFile); // Example: Load an NES ROM bool success = LoadRom("SuperMarioBros.nes", nullptr); // Example: Load a SNES ROM with a patch bool success = LoadRom("game.sfc", "translation.ips"); // Example: Load from archive (ZIP, 7z supported) bool success = LoadRom("roms.zip/game.nes", nullptr); ``` -------------------------------- ### Debugger API Source: https://context7.com/sourmesen/mesen2/llms.txt Initialize and control the integrated debugger. ```APIDOC ## Debugger API ### Methods - **InitializeDebugger()**: Starts the debugger. - **ReleaseDebugger()**: Shuts down the debugger. - **IsDebuggerRunning()**: Returns true if debugger is active. - **IsExecutionStopped()**: Returns true if execution is paused at a breakpoint. - **ResumeExecution()**: Resumes emulation execution. ``` -------------------------------- ### Draw Text with Background (Lua) Source: https://context7.com/sourmesen/mesen2/llms.txt Draw text on the screen with optional background color, maximum width, frame count, and delay. Coordinates are 0-based. ```lua -- Draw text with background -- emu.drawString(x, y, text, textColor, [bgColor], [maxWidth], [frameCount], [delay]) ému.drawString(10, 10, "Score: 1000", 0xFFFFFF, 0x000000) ``` -------------------------------- ### Clear Screen and Select Draw Surface (Lua) Source: https://context7.com/sourmesen/mesen2/llms.txt Clear all previous drawings from the screen or select a specific drawing surface like the console screen or a HUD overlay with scaling options. ```lua -- Clear all drawings ému.clearScreen() -- Select drawing surface -- emu.drawSurface.consoleScreen - Draw directly on game output -- emu.drawSurface.scriptHud - Draw on separate overlay (supports scaling) ému.selectDrawSurface(emu.drawSurface.scriptHud, 2) -- 2x scale ``` -------------------------------- ### Emulation Control API Source: https://context7.com/sourmesen/mesen2/llms.txt Core functions to control emulation state including pause, resume, stop, and checking running/paused status. ```APIDOC ## Emulation Control ### Description Core functions to control emulation state including pause, resume, stop, and frame information retrieval. ### Methods - `DllExport void __stdcall Pause()`: Pauses the emulation. - `DllExport void __stdcall Resume()`: Resumes the emulation. - `DllExport void __stdcall Stop()`: Stops the emulation and releases resources. - `DllExport bool __stdcall IsRunning()`: Returns true if the emulator is running. - `DllExport bool __stdcall IsPaused()`: Returns true if the emulator is paused. ### Request Example ```cpp // Pause emulation, take screenshot, resume if (IsRunning() && !IsPaused()) { Pause(); TakeScreenshot(); Resume(); } // Stop emulation and release resources Stop(); Release(); ``` ``` -------------------------------- ### Multiplayer Networking API Source: https://context7.com/sourmesen/mesen2/llms.txt Functions for hosting and connecting to netplay sessions. ```APIDOC ## Multiplayer Networking Host or connect to netplay sessions for online multiplayer gaming. ### Functions - `StartServer(uint16_t port, char* password)`: Starts a netplay server on the specified port with a password. - `StopServer()`: Stops the currently running netplay server. - `IsServerRunning()`: Returns true if a netplay server is running, false otherwise. - `Connect(char* host, uint16_t port, char* password, bool spectator)`: Connects to a netplay server at the given host and port, with optional spectator mode. - `Disconnect()`: Disconnects from the current netplay session. - `IsConnected()`: Returns true if currently connected to a netplay session, false otherwise. ### Example Usage ```cpp // Host a netplay session StartServer(8888, "secretpass"); printf("Server running: %s\n", IsServerRunning() ? "yes" : "no"); // Load a game and wait for players LoadRom("game.nes", nullptr); // Connect to a session as player Connect("192.168.1.100", 8888, "secretpass", false); while (!IsConnected()) { Sleep(100); } printf("Connected!\n"); // Connect as spectator Connect("192.168.1.100", 8888, "secretpass", true); ``` ``` -------------------------------- ### Lua Input Control API Source: https://context7.com/sourmesen/mesen2/llms.txt Functions for reading and overriding controller inputs, checking keyboard states, and retrieving mouse coordinates. ```APIDOC ## Lua Input Control ### Description Provides methods to interface with controller ports, keyboard input, and mouse state for automation. ### Methods - **emu.getInput(port)**: Returns a table of button states for the specified controller port. - **emu.setInput(port, table)**: Overrides the controller input for the specified port. - **emu.isKeyPressed(keyName)**: Returns true if the specified keyboard key is currently pressed. - **emu.getMouseState()**: Returns a table containing mouse x, y coordinates and button states. ``` -------------------------------- ### Record and playback movies Source: https://context7.com/sourmesen/mesen2/llms.txt Manage input movie recording and playback for TAS workflows. ```cpp struct RecordMovieOptions { char Filename[2000]; char Author[1000]; char Description[10000]; RecordMovieFrom RecordFrom; // StartWithSaveData, StartWithoutSaveData, CurrentState }; DllExport void __stdcall MovieRecord(RecordMovieOptions options); DllExport void __stdcall MoviePlay(char* filename); DllExport void __stdcall MovieStop(); DllExport bool __stdcall MoviePlaying(); DllExport bool __stdcall MovieRecording(); // Example: Start recording a movie RecordMovieOptions opts = {}; strcpy(opts.Filename, "speedrun.msm"); strcpy(opts.Author, "Player1"); strcpy(opts.Description, "Any% speedrun attempt"); opts.RecordFrom = RecordMovieFrom::StartWithoutSaveData; MovieRecord(opts); // Example: Play back a movie MoviePlay("speedrun.msm"); while (MoviePlaying()) { Sleep(100); } ``` -------------------------------- ### Draw Shapes (Lua) Source: https://context7.com/sourmesen/mesen2/llms.txt Draw pixels, lines, and rectangles on the screen. Colors are in 0xAARRGGBB format. Rectangles can be filled or just borders. ```lua -- Draw shapes -- Colors are 0xAARRGGBB format (alpha, red, green, blue) ému.drawPixel(50, 50, 0xFFFF0000) -- Red pixel ému.drawLine(0, 0, 100, 100, 0xFF00FF00) -- Green line ému.drawRectangle(20, 20, 40, 30, 0x80FF0000, true) -- Semi-transparent red filled rect ému.drawRectangle(20, 20, 40, 30, 0xFFFFFFFF, false) -- White border ``` -------------------------------- ### Execution Control API Source: https://context7.com/sourmesen/mesen2/llms.txt Functions for stepping through emulator execution using various modes like instruction, cycle, or frame-based stepping. ```APIDOC ## Step ### Description Step through code execution with various stepping modes. ### Method DllExport void __stdcall Step(CpuType cpuType, uint32_t count, StepType type); ### Parameters - **cpuType** (CpuType) - Required - The target CPU architecture (e.g., Nes, Snes, Gameboy). - **count** (uint32_t) - Required - The number of units to step. - **type** (StepType) - Required - The stepping mode (Step, StepOut, StepOver, CpuCycleStep, PpuStep, PpuScanline, PpuFrame, SpecificScanline). ### Request Example Step(CpuType::Nes, 1, StepType::Step); ``` -------------------------------- ### Control Emulator Input and Mouse State in Lua Source: https://context7.com/sourmesen/mesen2/llms.txt Use these functions to read or override controller inputs, detect keyboard presses, and retrieve mouse coordinates. ```lua -- Get current controller input -- Returns table with button states: A, B, X, Y, Up, Down, Left, Right, Start, Select, etc. local input = emu.getInput(0) -- Port 0 if input.A then emu.log("A button pressed") end -- Override controller input emu.setInput(0, { A = true, B = false, Up = false, Down = false, Left = true, Right = false, Start = false, Select = false }) -- Check keyboard keys if emu.isKeyPressed("Space") then emu.log("Space pressed!") end -- Get mouse state local mouse = emu.getMouseState() emu.log("Mouse: " .. mouse.x .. ", " .. mouse.y) if mouse.left then emu.log("Left click at " .. mouse.x .. ", " .. mouse.y) end ``` -------------------------------- ### Save State API Source: https://context7.com/sourmesen/mesen2/llms.txt Manage save states by slot index or file path. Supports 10 quick-save slots plus unlimited file-based saves. ```APIDOC ## Save and Load State ### Description Manage save states by slot index or file path. Supports 10 quick-save slots plus unlimited file-based saves. ### Methods - `DllExport void __stdcall SaveState(uint32_t stateIndex)`: Saves the current state to the specified quick-save slot. - `DllExport void __stdcall LoadState(uint32_t stateIndex)`: Loads the state from the specified quick-save slot. - `DllExport void __stdcall SaveStateFile(char* filepath)`: Saves the current state to a file. - `DllExport void __stdcall LoadStateFile(char* filepath)`: Loads the state from a file. - `DllExport int32_t __stdcall GetSaveStatePreview(char* saveStatePath, uint8_t* pngData)`: Retrieves a PNG preview of a save state file. ### Request Example ```cpp // Quick save to slot 1 SaveState(1); // Load from slot 1 LoadState(1); // Save to custom file SaveStateFile("speedrun_checkpoint.mss"); // Get save state preview image uint8_t pngBuffer[1024 * 1024]; int32_t pngSize = GetSaveStatePreview("save.mss", pngBuffer); if (pngSize > 0) { // Write PNG to file for display } ``` ``` -------------------------------- ### Register Emulation Event Callback (Lua) Source: https://context7.com/sourmesen/mesen2/llms.txt Register a function to be called on specific emulation events, such as the end of a frame. The handler receives no arguments. ```lua -- Event callback types -- emu.eventType.startFrame, endFrame, reset, inputPolled, etc. -- Register frame callback function onFrameEnd() local state = emu.getState() emu.drawString(10, 10, "Frame: " .. state["frameCount"], 0xFFFFFF) end ému.addEventCallback(onFrameEnd, emu.eventType.endFrame) ``` -------------------------------- ### History Viewer C++ API Source: https://context7.com/sourmesen/mesen2/llms.txt C++ interface for managing the rewind buffer, seeking through history, and exporting gameplay data. ```APIDOC ## History Viewer API ### Description Provides access to the rewind buffer for gameplay review, state extraction, and movie exporting. ### Methods - **HistoryViewerEnabled()**: Returns true if history is available. - **HistoryViewerInitialize(windowHandle, viewerHandle)**: Initializes the viewer. - **HistoryViewerGetState()**: Returns the current history state including buffer length. - **HistoryViewerSetPosition(seekPosition)**: Seeks the history buffer to a specific frame. - **HistoryViewerResumeGameplay(resumePosition)**: Resumes gameplay from a specific history frame. - **HistoryViewerSaveMovie(movieFile, startPosition, endPosition)**: Exports a segment of history to a movie file. ``` -------------------------------- ### Register Memory Write Callback (Lua) Source: https://context7.com/sourmesen/mesen2/llms.txt Register a function to be called when memory is written to within a specified address range. The handler receives no arguments. ```lua -- Register write callback for address range function onWriteHandler() emu.log("Write to sprite DMA area!") end ému.addMemoryCallback(onWriteHandler, emu.callbackType.write, 0x0200, 0x02FF) ```