### Initialize SubsystemContent Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/content Example of creating a SubsystemContent instance. ```python >>> from libretro.api.content import SubsystemContent >>> sc = SubsystemContent(game_type=0, info=[b'/game.bin']) >>> sc.game_type 0 ``` -------------------------------- ### Initialize retro_core_option_v2_definition Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/options Example usage of the v2 option definition structure. ```python >>> from libretro.api import retro_core_option_v2_definition >>> d = retro_core_option_v2_definition() >>> d.key is None True ``` -------------------------------- ### Manage Hardware Rendering Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/environment/composite Handles hardware rendering context setup and callback registration. ```python @override def _set_hw_render(self, callback: TypedPointer[retro_hw_render_callback]) -> bool: if not callback: raise ValueError("RETRO_ENVIRONMENT_SET_HW_RENDER doesn't accept NULL") core_callback = callback[0] try: self._video.set_context(core_callback) except UnsupportedContextError: return False if not self._hw_render_callback: self._hw_render_callback = retro_hw_render_callback( get_current_framebuffer=retro_hw_get_current_framebuffer_t( self._get_current_framebuffer ), get_proc_address=retro_hw_get_proc_address_t(self._get_hw_proc_address), ) core_callback.get_current_framebuffer = self._hw_render_callback.get_current_framebuffer core_callback.get_proc_address = self._hw_render_callback.get_proc_address # Give the core the callbacks that the video driver defines return True @_return_on_raise(0) def _get_current_framebuffer(self) -> int: return self._video.current_framebuffer or 0 @_return_on_raise(0) def _get_hw_proc_address(self, sym: bytes) -> int: proc = self._video.get_proc_address(sym) if not proc: return 0 return cast(proc, c_void_p).value or 0 ``` -------------------------------- ### Initialize retro_core_option_v2_category Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/options Example usage of the v2 category structure. ```python >>> from libretro.api import retro_core_option_v2_category >>> cat = retro_core_option_v2_category() >>> cat.key is None True ``` -------------------------------- ### Initialize retro_core_options_intl Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/options Example usage of the internationalized options structure. ```python >>> from libretro.api import retro_core_options_intl >>> intl = retro_core_options_intl() >>> intl.us is None True ``` -------------------------------- ### Iterate and Count Subsystems Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/content Examples for iterating over subsystem entries and retrieving the total count. ```python >>> from libretro.api.content import Subsystems >>> list(Subsystems([])) [] ``` ```python >>> from libretro.api.content import Subsystems >>> len(Subsystems([])) 0 ``` -------------------------------- ### Get Rumble Interface Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/environment/composite Provides the rumble interface to the core, initializing it if necessary. ```python @override def _get_rumble_interface(self, rumble: TypedPointer[retro_rumble_interface]) -> bool: if not rumble: raise ValueError("RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE doesn't accept NULL") if not self._rumble: return False if not self._rumble_interface: self._rumble_interface = retro_rumble_interface( retro_set_rumble_state_t(self._set_rumble_state) ) # So that even if the rumble/input drivers are swapped out, # the core still has valid function pointers tied to non-GC'd callable objects rumble[0] = self._rumble_interface return True @_return_on_raise(False) def _set_rumble_state(self, port: Port, effect: int, strength: int) -> bool: if self._rumble is None: return False return self._rumble.set_rumble_state(port, RumbleEffect(effect), strength) ``` -------------------------------- ### Get System Information Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/core Retrieves core system information as a retro_system_info instance. ```python @override def get_system_info(self) -> retro_system_info: """ Call the core's ``retro_get_system_info`` function. :return: A ``retro_system_info`` instance containing information about the core. All strings are copied and may be accessed even after unloading the core. """ system_info = retro_system_info() self._core.retro_get_system_info(byref(system_info)) return deepcopy(system_info) ``` -------------------------------- ### Logging Interface Setup Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/environment/composite Provides the logging interface callback and handles log message routing to the log driver. ```python @property def log(self) -> LogDriver | None: """Return the :class:`.LogDriver` supplied at construction time, or ``None`` if absent.""" return self._log_driver @override def _get_log_interface(self, interface: TypedPointer[retro_log_callback]) -> bool: if self._log_driver is None: return False if not interface: raise ValueError("RETRO_ENVIRONMENT_GET_LOG_INTERFACE doesn't accept NULL") if not self._log_callback: self._log_callback = retro_log_callback(log=retro_log_printf_t(self._log)) interface[0] = self._log_callback return True @_return_on_raise(None) def _log(self, level: int, message: bytes): if self._log_driver is not None and level in LogLevel: self._log_driver.log(LogLevel(level), message) ``` -------------------------------- ### Camera Control Methods Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/environment/composite Wrappers for starting and stopping the camera driver, decorated to handle exceptions. ```python @_return_on_raise(False) def _camera_start(self) -> bool: if self._camera is None: return False return self._camera.start() @_return_on_raise(None) def _camera_stop(self) -> None: if self._camera is not None: self._camera.stop() ``` -------------------------------- ### Initialize retro_game_info_ext Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/content Shows how to instantiate the retro_game_info_ext structure with path and extension metadata. ```python >>> from libretro.api import retro_game_info_ext >>> info = retro_game_info_ext(full_path=b'/games/test.bin', ext=b'bin') >>> info.ext b'bin' ``` -------------------------------- ### Implement retro_hw_render_context_negotiation_interface Structure Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/video/negotiate Defines the structure for hardware rendering context negotiation, including usage examples for initialization. ```python [docs] @dataclass(init=False, slots=True) class retro_hw_render_context_negotiation_interface(Structure): """ Corresponds to :c:type:`retro_hw_render_context_negotiation_interface` in ``libretro.h``. >>> from libretro.api.video import retro_hw_render_context_negotiation_interface >>> iface = retro_hw_render_context_negotiation_interface() >>> iface.interface_version 0 """ interface_type: ContextNegotiationInterfaceType """Rendering API this negotiation interface is for.""" interface_version: int """Version of this negotiation interface.""" _fields_ = ( ("interface_type", retro_hw_render_context_negotiation_interface_type), ("interface_version", c_uint), ) ``` -------------------------------- ### Access SensorType Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/sensor Example of accessing the SensorType enumeration. ```python >>> from libretro.api import SensorType >>> SensorType.ACCELEROMETER ``` -------------------------------- ### init() Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/core Initializes the Libretro core. ```APIDOC ## init() ### Description Calls the core's retro_init function. Note that this method does not check if the core has already been initialized. ``` -------------------------------- ### RumbleEffect Enumeration Usage Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/rumble Example usage of the RumbleEffect enumeration. ```python >>> from libretro.api import RumbleEffect >>> RumbleEffect.STRONG ``` -------------------------------- ### Initialize retro_core_option_display Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/options Demonstrates creating a new retro_core_option_display instance and checking the default visibility. ```python >>> from libretro.api import retro_core_option_display >>> d = retro_core_option_display() >>> d.visible False ``` -------------------------------- ### Initialize retro_core_option_definition Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/options Demonstrates creating a new retro_core_option_definition instance and verifying its default key state. ```python >>> from libretro.api import retro_core_option_definition >>> d = retro_core_option_definition() >>> d.key is None True ``` -------------------------------- ### retro_perf_start_t Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/perf Starts timing a previously registered performance counter. ```APIDOC ## retro_perf_start_t ### Description Starts timing a registered performance counter. This should be called by the core right before the code being measured. ### Parameters - **counter** (retro_perf_counter*) - Required - Pointer to a performance counter that has been registered. ``` -------------------------------- ### Initialize retro_vfs_interface_info Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/vfs Demonstrates instantiation of the VFS interface info structure and verification of the default version number. ```python >>> from libretro.api import retro_vfs_interface_info >>> info = retro_vfs_interface_info() >>> info.required_interface_version 0 ``` -------------------------------- ### Get Version Property Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/vfs/history Retrieves the version from the underlying interface. ```python @property @override def version(self) -> int: return self._interface.version ``` -------------------------------- ### get_memory_size(id) Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/core Gets the size of a specific memory region. ```APIDOC ## get_memory_size(id) ### Description Returns the size of the specified memory region in bytes. ### Parameters - **id** (int) - Required - The ID of the memory region. ### Returns - **int** - The size of the memory region in bytes. ``` -------------------------------- ### libretro.session.__init__ Source: https://libretropy.readthedocs.io/en/latest/api/libretro.session Initializes a new session with the specified core and driver configurations. ```APIDOC ## libretro.session.__init__ ### Description Initializes the session with a core and various driver configurations. The core can be a Core object, a ctypes.CDLL, or a filesystem path. ### Parameters - **preferred_hw** (HardwareContext | None) - Optional - The preferred hardware context to report to the core. - **driver_switch_enable** (bool | None) - Optional - Whether the core may switch hardware rendering drivers at runtime. - **savestate_context** (SavestateContext | None) - Optional - The savestate context to report to the core. - **jit_capable** (bool | None) - Optional - Whether the host environment is JIT-capable. - **mic** (MicrophoneDriver | Callable | None) - Optional - The microphone driver or a factory function. - **device_power** (PowerDriver | Callable | None) - Optional - The power driver or a factory function. ``` -------------------------------- ### Initialize retro_core_options_v2_intl Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/options Demonstrates instantiation of the wrapper for US English and localized v2 option sets. ```python >>> from libretro.api import retro_core_options_v2_intl >>> intl = retro_core_options_v2_intl() >>> intl.us is None True ``` -------------------------------- ### Initialize retro_controller_info Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/input/device Demonstrates creating a retro_controller_info object with multiple controller descriptions. ```python >>> from libretro.api import retro_controller_description, retro_controller_info >>> descs = (retro_controller_description * 2)( ... retro_controller_description(b'Game Pad', 1), ... retro_controller_description(b'Analog Stick', 2), ... ) >>> info = retro_controller_info(descs, 2) >>> info[-1].desc b'Analog Stick' ``` -------------------------------- ### Get file metadata Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/vfs/driver Retrieves metadata for a file at the specified path. ```python @abstractmethod def stat(self, path: bytes) -> tuple[VfsStat, int] | None: """ Return file metadata for ``path``. :param path: Path of the entry to inspect, encoded as :class:`bytes`. :return: A pair of :class:`.VfsStat` flags and the entry size in bytes, or ``None`` if ``path`` does not exist. .. seealso:: :c:func:`retro_vfs_stat_t` """ ... ``` -------------------------------- ### Get version property Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/options/dict Retrieves the current version of the options dictionary. ```python @property @override def version(self) -> int: return self._version ``` -------------------------------- ### Initialize retro_core_options_v2 Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/options Demonstrates instantiation of the top-level container for v2 option categories and definitions. ```python >>> from libretro.api import retro_core_options_v2 >>> v2 = retro_core_options_v2() >>> v2.categories is None True ``` -------------------------------- ### Get Microphone State Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/microphone/generator Returns the current state of the specified microphone. ```python @override def get_mic_state(self, mic: retro_microphone) -> bool: mic_id = mic.id if (m := self._microphones.get(mic_id)) is not None: return m.state return False ``` -------------------------------- ### Initialize Disk Control Callback Structure Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/disk Demonstrates the initialization of the disk control callback structure and verification of default null states. ```python >>> from libretro.api import retro_disk_control_callback >>> cb = retro_disk_control_callback() >>> cb.set_eject_state is None True ``` -------------------------------- ### Access SensorAction Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/sensor Example of accessing the SensorAction enumeration and checking its enabled status. ```python >>> from libretro.api import SensorAction >>> SensorAction.GYROSCOPE_ENABLE.enabled True ``` -------------------------------- ### Initialize retro_hw_render_interface Source: https://libretropy.readthedocs.io/en/latest/api/libretro.api.video.render Demonstrates instantiation of the hardware render interface structure. ```python >>> from libretro.api.video import retro_hw_render_interface >>> iface = retro_hw_render_interface() >>> iface.interface_version 0 ``` -------------------------------- ### Initialize retro_subsystem_rom_info Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/content Demonstrates basic initialization and empty state of the ROM info structure. ```python >>> from libretro.api import retro_subsystem_rom_info >>> list(retro_subsystem_rom_info()) [] ``` -------------------------------- ### set_mic_state(mic, state) Source: https://libretropy.readthedocs.io/en/latest/api/libretro.drivers.microphone.generator Starts or pauses audio capture on the specified microphone. ```APIDOC ## set_mic_state(mic, state) ### Description Updates the capture state of the microphone. ### Parameters - **mic** (retro_microphone) - Required - The microphone handle to update. - **state** (bool) - Required - True to start capturing, False to pause. ``` -------------------------------- ### Initialize and Copy AV Information Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/av Demonstrates creating a retro_system_av_info instance with geometry and timing, and verifying that deepcopy creates a distinct object. ```python >>> from copy import deepcopy >>> from ctypes import addressof >>> from libretro.api import retro_system_av_info, retro_game_geometry, retro_system_timing >>> geom = retro_game_geometry(base_width=320, base_height=240, max_width=320, max_height=240) >>> timing = retro_system_timing(fps=60.0, sample_rate=32000.0) >>> av = retro_system_av_info(geom, timing) >>> av2 = deepcopy(av) >>> av == av2 True >>> av is av2 False >>> addressof(av) == addressof(av2) False ``` -------------------------------- ### Get Input Device Capabilities Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/environment/composite Retrieves the input device capabilities bitmask. ```python @override def _get_input_device_capabilities(self, capabilities: TypedPointer[c_uint64]) -> bool: if not capabilities: raise ValueError("RETRO_ENVIRONMENT_GET_INPUT_DEVICE_CAPABILITIES doesn't accept NULL") caps = self._input.device_capabilities if caps is None: return False capabilities[0] = caps return True ``` -------------------------------- ### Core.__init__ Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/core Initializes a new Core instance by loading a libretro shared library from a path or an existing CDLL object. ```APIDOC ## Core.__init__(core) ### Description Creates a new Core instance. This constructor loads the specified shared library and verifies that it exposes the required libretro functions. ### Parameters - **core** (CDLL | PathLike | str) - Required - The core to wrap, provided as a file path or a loaded CDLL instance. ### Exceptions - **ValueError**: Raised if the core does not define all required retro_* functions. - **TypeError**: Raised if the provided core argument is not a valid type. ``` -------------------------------- ### Manage Pixel Format Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/environment/composite Handles getting and setting the video pixel format. ```python @property def pixel_format(self) -> PixelFormat: """ Return the :class:`.PixelFormat` currently set on the underlying :class:`.VideoDriver`. .. seealso:: :attr:`.EnvironmentCall.SET_PIXEL_FORMAT` The environment call that updates this value. """ return self._video.pixel_format @override def _set_pixel_format(self, fmt: TypedPointer[retro_pixel_format]) -> bool: if not fmt: raise ValueError("RETRO_ENVIRONMENT_SET_PIXEL_FORMAT doesn't accept NULL") self._video.pixel_format = PixelFormat(fmt[0]) return True ``` -------------------------------- ### Initialize and copy microphone parameters Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/microphone Demonstrates creating a parameter structure and performing a deep copy operation. ```python >>> from libretro.api.microphone import retro_microphone_params >>> p = retro_microphone_params() >>> p.rate 0 ``` ```python >>> import copy >>> from libretro.api.microphone import retro_microphone_params >>> copy.deepcopy(retro_microphone_params()).rate 0 ``` -------------------------------- ### Get Software Framebuffer Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/video/opengl/moderngl Placeholder for mapping OpenGL textures to a software framebuffer. ```python [docs] @override def get_software_framebuffer( self, width: int, height: int, flags: MemoryAccess ) -> retro_framebuffer | None: # TODO: Map the OpenGL texture to a software framebuffer pass ``` -------------------------------- ### Initialize Extended Disk Control Callback Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/disk Demonstrates the initialization of the extended disk control callback structure. ```python >>> from libretro.api import retro_disk_control_ext_callback >>> cb = retro_disk_control_ext_callback() >>> cb.set_initial_image is None True ``` -------------------------------- ### Get Procedure Address Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/video/opengl/moderngl Loads an OpenGL function address from the initialized context. ```python @override def get_proc_address(self, sym: bytes) -> retro_proc_address_t | None: if not sym: return None if not self._context: raise RuntimeError("OpenGL context not initialized") # See here https://github.com/moderngl/glcontext?tab=readme-ov-file#structure proc: int | None = self._context.mglo._context.load_opengl_function(sym.decode()) if proc is None: return None return retro_proc_address_t(proc) ``` -------------------------------- ### Get directory entry name Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/vfs/driver Returns the name of the current directory entry. ```python @abstractmethod def dirent_get_name(self, dir: retro_vfs_dir_handle) -> bytes | None: """ Return the name of the current entry in ``dir``. :param dir: An open directory handle previously returned by :meth:`opendir`. :return: The entry name as :class:`bytes`, or ``None`` if no entry is available. .. seealso:: :c:func:`retro_vfs_dirent_get_name_t` """ ... ``` -------------------------------- ### Initialize KeyboardState Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/input/keyboard Demonstrates how to instantiate the KeyboardState class and check the default state of a key. ```python >>> from libretro.api.input import KeyboardState >>> state = KeyboardState() >>> state.space False ``` -------------------------------- ### Initialize retro_hw_render_callback Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/video/context Demonstrates creating a new hardware rendering callback instance and verifying its default context type. ```python >>> from libretro.api.video import retro_hw_render_callback, HardwareContext >>> cb = retro_hw_render_callback() >>> cb.context_type == HardwareContext.NONE True ``` -------------------------------- ### Initialize and Verify Location Callback Structure Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/location Demonstrates instantiation of the callback structure and verification of default null states. ```python >>> from libretro.api import retro_location_callback >>> loc = retro_location_callback() >>> loc.start is None True ``` -------------------------------- ### Initialize and Verify retro_midi_interface Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/midi Demonstrates the instantiation of the MIDI interface structure and verification of its default state. ```python >>> from libretro.api import retro_midi_interface >>> midi = retro_midi_interface() >>> midi.read is None True ``` -------------------------------- ### Define Screen Rotation Enum Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/video/render Enumeration for screen rotation angles with a usage example. ```python class Rotation(IntEnum): """ Screen rotation angle. >>> from libretro.api.video import Rotation >>> Rotation.NONE """ NONE = 0 NINETY = 1 ONE_EIGHTY = 2 TWO_SEVENTY = 3 ``` -------------------------------- ### Initialize retro_subsystem_info Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/content Demonstrates creating a subsystem info object and iterating over its associated ROM descriptors. ```python >>> from libretro.api import retro_subsystem_info, retro_subsystem_rom_info >>> roms = (retro_subsystem_rom_info * 2)( ... retro_subsystem_rom_info(desc=b'BIOS'), ... retro_subsystem_rom_info(desc=b'Cartridge'), ... ) >>> info = retro_subsystem_info(b'My Subsystem', b'mysub', roms, 2, 0) >>> len(info) 2 >>> [r.desc for r in info] [b'BIOS', b'Cartridge'] ``` -------------------------------- ### Get Libretro Path Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/environment/composite Retrieves the current Libretro path, ensuring the pointer is valid. ```python @override def _get_libretro_path(self, path: TypedPointer[c_char_p]) -> bool: if self._path is None or not self._path.libretro_path: return False if not path: raise ValueError("RETRO_ENVIRONMENT_GET_LIBRETRO_PATH doesn't accept NULL") path[0] = self._path.libretro_path return True ``` -------------------------------- ### Initialize retro_vfs_interface Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/vfs Demonstrates instantiation of the VFS interface structure and verification of default callback values. ```python >>> from libretro.api import retro_vfs_interface >>> vfs = retro_vfs_interface() >>> vfs.open is None True ``` -------------------------------- ### Get System AV Information Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/core Retrieves core audiovisual capabilities as a retro_system_av_info instance. ```python @override def get_system_av_info(self) -> retro_system_av_info: """ Call the core's ``retro_get_system_av_info`` function. :return: A ``retro_system_av_info`` instance containing information about the core's audiovisual capabilities. It may be accessed even after unloading the core. """ system_av_info = retro_system_av_info() self._core.retro_get_system_av_info(byref(system_av_info)) return system_av_info ``` -------------------------------- ### Session.__init__ Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/session Initializes a new Libretro session with a specified core, optional game content, and various driver implementations. ```APIDOC ## Session.__init__ ### Description Initializes the session with a core, optional game content, and driver implementations. Each driver argument accepts the configured driver directly, a zero-argument callable that produces one, or a convenience value wrapped in a default driver. ### Parameters - **core** (Core | CDLL | str | PathLike) - Required - The core to load. Can be a Core instance, a path to a library, or an already-opened CDLL. - **game** (Content | SubsystemContent | None) - Optional - The content to load. Can be a file path, a buffer, a retro_game_info object, or SubsystemContent. - **audio** (AudioDriverArg) - Optional - The audio driver. Defaults to ArrayAudioDriver. - **input** (InputDriverArg) - Optional - The input driver. Defaults to IterableInputDriver. - **video** (VideoDriverArg) - Optional - The video driver. Defaults to MultiVideoDriver. ``` -------------------------------- ### Directory and System AV Info Callbacks Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/environment/composite Methods for retrieving core asset/save directories and setting system audio/video information. ```python @override def _get_core_assets_directory(self, dir: TypedPointer[c_char_p]) -> bool: if self._path is None or self._path.core_assets_dir is None: return False if not dir: raise ValueError("RETRO_ENVIRONMENT_GET_CORE_ASSETS_DIRECTORY doesn't accept NULL") dir[0] = self._path.core_assets_dir return True @override def _get_save_directory(self, dir: TypedPointer[c_char_p]) -> bool: if self._path is None or self._path.save_dir is None: return False if not dir: raise ValueError("RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY doesn't accept NULL") dir[0] = self._path.save_dir return True @override def _set_system_av_info(self, info: TypedPointer[retro_system_av_info]) -> bool: if not info: return False # TODO: Provide a way to disable this envcall av_info = info[0] self._video.system_av_info = av_info self._audio.system_av_info = av_info self._system_av_info = deepcopy(av_info) return True ``` -------------------------------- ### Language Enumeration Usage Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/user Example of using the Language IntEnum class to access language identifiers. ```python class Language(IntEnum): """ Enumeration of supported user interface languages. Corresponds to the ``RETRO_LANGUAGE_*`` constants in ``libretro.h``. >>> from libretro.api import Language >>> Language.ENGLISH """ ENGLISH = RETRO_LANGUAGE_ENGLISH JAPANESE = RETRO_LANGUAGE_JAPANESE FRENCH = RETRO_LANGUAGE_FRENCH SPANISH = RETRO_LANGUAGE_SPANISH GERMAN = RETRO_LANGUAGE_GERMAN ITALIAN = RETRO_LANGUAGE_ITALIAN DUTCH = RETRO_LANGUAGE_DUTCH PORTUGUESE_BRAZIL = RETRO_LANGUAGE_PORTUGUESE_BRAZIL PORTUGUESE_PORTUGAL = RETRO_LANGUAGE_PORTUGUESE_PORTUGAL RUSSIAN = RETRO_LANGUAGE_RUSSIAN KOREAN = RETRO_LANGUAGE_KOREAN CHINESE_TRADITIONAL = RETRO_LANGUAGE_CHINESE_TRADITIONAL CHINESE_SIMPLIFIED = RETRO_LANGUAGE_CHINESE_SIMPLIFIED ESPERANTO = RETRO_LANGUAGE_ESPERANTO POLISH = RETRO_LANGUAGE_POLISH VIETNAMESE = RETRO_LANGUAGE_VIETNAMESE ARABIC = RETRO_LANGUAGE_ARABIC GREEK = RETRO_LANGUAGE_GREEK TURKISH = RETRO_LANGUAGE_TURKISH SLOVAK = RETRO_LANGUAGE_SLOVAK PERSIAN = RETRO_LANGUAGE_PERSIAN HEBREW = RETRO_LANGUAGE_HEBREW ASTURIAN = RETRO_LANGUAGE_ASTURIAN FINNISH = RETRO_LANGUAGE_FINNISH INDONESIAN = RETRO_LANGUAGE_INDONESIAN SWEDISH = RETRO_LANGUAGE_SWEDISH UKRAINIAN = RETRO_LANGUAGE_UKRAINIAN CZECH = RETRO_LANGUAGE_CZECH CATALAN_VALENCIA = RETRO_LANGUAGE_CATALAN_VALENCIA CATALAN = RETRO_LANGUAGE_CATALAN BRITISH_ENGLISH = RETRO_LANGUAGE_BRITISH_ENGLISH HUNGARIAN = RETRO_LANGUAGE_HUNGARIAN BELARUSIAN = RETRO_LANGUAGE_BELARUSIAN GALICIAN = RETRO_LANGUAGE_GALICIAN NORWEGIAN = RETRO_LANGUAGE_NORWEGIAN IRISH = RETRO_LANGUAGE_IRISH ``` -------------------------------- ### Initialize ContentInfoOverrides Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/content Demonstrates initializing an empty ContentInfoOverrides object. ```python >>> from libretro.api.content import ContentInfoOverrides >>> len(ContentInfoOverrides([])) 0 ``` -------------------------------- ### retro_perf_register_t Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/perf Registers a performance counter with the frontend. This must be called once per counter before it is started or stopped. ```APIDOC ## retro_perf_register_t ### Description Registers a performance counter with the frontend. The counter's ident field must be set, and all other fields must be zero or False. ### Parameters - **counter** (retro_perf_counter*) - Required - Pointer to the performance counter to register. ``` -------------------------------- ### PointerState Initialization Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/input/pointer Demonstrates the default state of a pointer snapshot. ```python >>> from libretro.api.input import PointerState >>> state = PointerState() >>> state.pointers () ``` -------------------------------- ### Iterating retro_controller_info Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/input/device Demonstrates how to initialize a retro_controller_info instance and iterate over its controller descriptions. ```python >>> from libretro.api import retro_controller_description, retro_controller_info >>> descs = (retro_controller_description * 2)( ... retro_controller_description(b'Game Pad', 5), ... retro_controller_description(b'Analog Stick', 2), ... ) >>> info = retro_controller_info(descs, 2) >>> len(info) 2 >>> [d.desc for d in info] [b'Game Pad', b'Analog Stick'] ``` -------------------------------- ### Manage Core Variables Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/environment/composite Handles getting and setting core variables via the option driver. ```python @property def options(self) -> OptionDriver | None: """Return the :class:`.OptionDriver` supplied at construction time, or ``None`` if absent.""" return self._options @override def _get_variable(self, variable: TypedPointer[retro_variable]) -> bool: if self._options is None: return False if variable: key = variable[0].key if key is not None: variable[0].value = self._options.get_variable(key) # This envcall supports passing NULL to query for support return True @override def _set_variables(self, variables: TypedPointer[retro_variable]) -> bool: if self._options is None: return False if variables: definitions = tuple(deepcopy(s) for s in from_zero_terminated(variables)) self._options.set_variables(definitions) else: self._options.set_variables(None) ``` -------------------------------- ### Get Current Framebuffer Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/video/opengl/moderngl Retrieves the OpenGL object ID for the current hardware render framebuffer. ```python @property @override def current_framebuffer(self) -> int | None: if self._hw_render_fbo: return self._hw_render_fbo.glo return 0 ``` -------------------------------- ### StandardContentDriver.__init__ Source: https://libretropy.readthedocs.io/en/latest/api/libretro.drivers.content.standard Initializes a new instance of the StandardContentDriver. ```APIDOC ## StandardContentDriver.__init__(enable_extended_info=True) ### Description Initializes the driver. If enable_extended_info is set to True, the driver will provide extended content information to the core via the RETRO_ENVIRONMENT_GET_GAME_INFO_EXT environment call. ### Parameters - **enable_extended_info** (bool) - Optional - If True, the driver will provide extended content info to the core. ``` -------------------------------- ### WaveWriterAudioDriver.__init__ Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/audio/wave Initializes the driver and opens the specified file for writing WAV audio data. ```APIDOC ### Constructor WaveWriterAudioDriver(file: str | bytes | PathLike[str] | PathLike[bytes] | IO[bytes]) ### Description Opens the given file for writing WAV audio. The output file is configured as stereo, 16-bit PCM at 44,100 Hz. ### Parameters - **file** (str | bytes | PathLike | IO[bytes]) - Required - The output destination. Can be a file path or a writable binary I/O object. ### Exceptions - **ValueError**: If the provided IO object is not writable. - **TypeError**: If the provided file type is not supported. ``` -------------------------------- ### Get memory size Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/core Returns the size of a memory region in bytes. Requires an integer ID. ```python @override def get_memory_size(self, id: int) -> int: """ Call the core's ``retro_get_memory_size`` function for the given memory region. :param id: The ID of the memory region to get the size of. :raises TypeError: If ``id`` is not an ``int``. :return: The size of the memory region, in bytes. """ if not isinstance(id, int): raise TypeError(f"Expected int, got {type(id).__name__}") return self._core.retro_get_memory_size(id) ``` -------------------------------- ### Initialize retro_core_option_value Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/options Demonstrates creating a new retro_core_option_value instance and verifying its default value state. ```python >>> from libretro.api import retro_core_option_value >>> v = retro_core_option_value() >>> v.value is None True ``` -------------------------------- ### Get Serialization Size Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/core Returns the buffer size required for state serialization, or zero if unsupported. ```python @override def serialize_size(self) -> int: """ Call the core's ``retro_serialize_size`` function. :return: The length of the buffer needed to serialize the core's state, in bytes. If zero, the core does not support serialization. """ return self._core.retro_serialize_size() ``` -------------------------------- ### Initialize retro_microphone_interface Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/microphone Demonstrates initializing the microphone interface structure with a specific version. ```python >>> from libretro.api.microphone import retro_microphone_interface, INTERFACE_VERSION >>> mic = retro_microphone_interface(INTERFACE_VERSION) >>> mic.open_mic is None True ``` -------------------------------- ### Get API Version Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/core Retrieves the integer version number from the core's retro_api_version implementation. ```python @override def api_version(self) -> int: """ Call the core's ``retro_api_version`` function. :return: The integer returned by the core's implementation of ``retro_api_version``. :warning: This method does not validate the returned version number. """ return self._core.retro_api_version() ``` -------------------------------- ### AnalogState Axis Access Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/input/analog Examples for retrieving specific analog stick axis values from an AnalogState instance. ```python >>> from libretro.api.input import AnalogState >>> state = AnalogState(lstick=(123, 0)) >>> state.left_x 123 ``` ```python >>> from libretro.api.input import AnalogState >>> state = AnalogState(lstick=(0, 123)) >>> state.left_y 123 ``` ```python >>> from libretro.api.input import AnalogState >>> state = AnalogState(rstick=(123, 0)) >>> state.right_x 123 ``` ```python >>> from libretro.api.input import AnalogState >>> state = AnalogState(rstick=(0, 123)) >>> state.right_y 123 ``` -------------------------------- ### Initialize retro_subsystem_info with ROMs Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/content Demonstrates initializing a subsystem with a list of ROM info structures, which automatically sets the number of ROMs. ```python >>> from libretro.api import retro_subsystem_info, retro_subsystem_rom_info >>> roms = [retro_subsystem_rom_info(desc=b'BIOS'), retro_subsystem_rom_info(desc=b'Cart')] >>> sub = retro_subsystem_info(roms=roms) >>> len(sub) 2 ``` -------------------------------- ### Initialize and inspect retro_fastforwarding_override Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/timing Demonstrates creating an override structure and checking the default fast-forward state. ```python >>> from libretro.api import retro_fastforwarding_override >>> ff = retro_fastforwarding_override() >>> ff.fastforward False ``` -------------------------------- ### Get default timing driver Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/session Returns a default timing driver configured with unblocked throttle state. ```python def _default_timing_driver(): return DefaultTimingDriver(retro_throttle_state(ThrottleMode.UNBLOCKED, 0.0), 60.0) ``` -------------------------------- ### Get sensor input Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/sensor/iterable Retrieves the current sensor value based on the poll result and port configuration. ```python @override def get_sensor_input(self, port: Port, sensor: Sensor) -> float: if not self._generator: # An unassigned generator will default to 0 return 0.0 match (self._poll_result, port, sensor): case (None | [], _, _): # An empty result will default to 0 return 0.0 case _, _, sensor if not self._ports[port][sensor].enabled: # Disabled sensors will always return 0 return 0.0 case [*results], port, sensor: # Yielding a sequence of result types # will expose it to the port that corresponds to each index, # with unfilled ports defaulting to 0. return self._lookup_port_state(results[port], sensor) case result, port, sensor: # Yielding a type that's _not_ a sequence # will expose it to all ports. return self._lookup_port_state(result, sensor) case _, _, _: return 0.0 ``` -------------------------------- ### DictOptionDriver.__init__ Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/options/dict Initializes the driver with a specific core-options interface version and optional seed values. ```APIDOC ## DictOptionDriver.__init__(version=2, categories_supported=None, variables=None) ### Description Initializes the driver with a chosen interface version and seed values. ### Parameters - **version** (int) - Optional - The core-options interface version to advertise (0, 1, or 2). Defaults to 2. - **categories_supported** (bool) - Optional - Whether to advertise category support. Defaults to True for v2 and False otherwise. - **variables** (Mapping) - Optional - Initial option values, keyed by option key. String keys and values are encoded as UTF-8. ### Errors - **ValueError**: Raised if version is not 0, 1, or 2. ``` -------------------------------- ### Dirent get name operation Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/vfs/history Records a directory entry name retrieval operation in the history log. ```python [docs] @override def dirent_get_name(self, dir: retro_vfs_dir_handle) -> bytes | None: try: result = self._interface.dirent_get_name(dir) self._history.append(DirentGetName(dir=dir, result=result)) return result except: self._history.append(DirentGetName(dir=dir, result=None)) raise ``` -------------------------------- ### Initialize Hardware Rendering FBO Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/video/opengl/moderngl Sets up the framebuffer object, color attachments, and optional depth buffers for hardware rendering. ```python def __init_hw_render(self): assert self._context is not None with self._context.debug_scope("libretro.ModernGlVideoDriver.__init_hw_render"): assert self._callback is not None assert self._system_av_info is not None self._hw_render_fbo = None self._hw_render_color = None self._hw_render_depth = None size = self.__get_framebuffer_size() # Similar to glGenTextures, glBindTexture, and glTexImage2D self._hw_render_color = self._context.texture(size, 4) if self._callback.depth: # If the core is asking for a depth attachment... # Similar to glGenRenderbuffers, glBindRenderbuffer, and glRenderbufferStorage self._hw_render_depth = self._context.depth_renderbuffer(size) if self._callback.stencil: warnings.warn( "Core requested stencil attachment, but moderngl lacks support; ignoring" ) # TODO: Implement stencil buffer support in moderngl # Similar to glGenFramebuffers, glBindFramebuffer, and glFramebufferTexture2D self._hw_render_fbo = self._context.framebuffer( self._hw_render_color, self._hw_render_depth ) self._hw_render_fbo.clear() self._hw_render_fbo.label = "libretro.py Hardware Rendering FBO" self._hw_render_color.label = "libretro.py Hardware Rendering FBO Color Attachment" if self._hw_render_depth: self._hw_render_depth.label = "libretro.py Hardware Rendering FBO Depth Attachment" ``` -------------------------------- ### Get core library path Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/core Returns the file system path to the core's shared library. ```python @property def path(self) -> str: """The path to the core's shared library.""" return self._core._name ``` -------------------------------- ### Enter Session Context Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/session Initializes the core, registers necessary callbacks, and validates the API version within a context manager. ```python def __enter__(self): """ Initialize the core, register callbacks, and load content. :return: This session, suitable for use inside a ``with`` block. :raises RuntimeError: If the core's API version is incompatible, its system info is incomplete, or content loading fails. """ api_version = self._core.api_version() self._raise_pending_exceptions("retro_api_version") if api_version != API_VERSION: raise RuntimeError( f"libretro.py is only compatible with API version {API_VERSION}, but the core uses {api_version}" ) self._core.set_video_refresh(self.video_refresh) self._raise_pending_exceptions("retro_set_video_refresh") self._core.set_audio_sample(self.audio_sample) self._raise_pending_exceptions("retro_set_audio_sample") self._core.set_audio_sample_batch(self.audio_sample_batch) self._raise_pending_exceptions("retro_set_audio_sample_batch") self._core.set_input_poll(self.input_poll) self._raise_pending_exceptions("retro_set_input_poll") self._core.set_input_state(self.input_state) self._raise_pending_exceptions("retro_set_input_state") self._core.set_environment(self.environment) self._raise_pending_exceptions("retro_set_environment") system_info = self._core.get_system_info() self._raise_pending_exceptions("retro_get_system_info") self._core.init() self._raise_pending_exceptions("retro_init") if self._content is None: # Do nothing, we're testing something that doesn't need to load a game return self self._content.system_info = deepcopy(system_info) ``` -------------------------------- ### Get core region Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/core Retrieves the core region, returning a Region enum if known, otherwise an integer. ```python @override def get_region(self) -> Region | int: """ Call the core's ``retro_get_region`` function. :return: The returned region as a ``Region`` enum if it's a known value, or as a plain ``int`` if not. """ region: int = self._core.retro_get_region() return Region(region) if region in Region else region ``` -------------------------------- ### ModernGlVideoDriver.__init__ Source: https://libretropy.readthedocs.io/en/latest/api/libretro.drivers.video.opengl.moderngl Initializes the video driver with optional custom shaders and varying configurations. ```APIDOC ## ModernGlVideoDriver.__init__(vertex_shader=None, fragment_shader=None, varyings=('transformedTexCoord',), window=None) ### Description Initializes the video driver. Note that the OpenGL context is not created until reinit() is called. ### Parameters - **vertex_shader** (str | None) - Optional - The GLSL source of the vertex shader. - **fragment_shader** (str | None) - Optional - The GLSL source of the fragment shader. - **varyings** (Sequence[str]) - Optional - The names of the vertex value outputs. ``` -------------------------------- ### minimum_latency Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/audio/driver Property to get or set the minimum audio latency in milliseconds. Setting this to None clears the configuration. ```APIDOC ## Property: minimum_latency ### Description Gets or sets the minimum audio latency in milliseconds. This value is used to configure the audio driver's latency requirements. ### Parameters - **latency** (int | None) - The latency in milliseconds, or None to clear the setting. ### Exceptions - **UnsupportedEnvCall**: Raised if the driver does not support minimum latency configuration. ``` -------------------------------- ### GeneratorMicrophone.__init__ Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/microphone/generator Initializes the microphone with a sample source and capture parameters. ```APIDOC ## GeneratorMicrophone(generator, params) ### Description Initializes the microphone with a sample source and capture parameters. A generator function is called once to obtain its iterator; an iterable is used directly. If None is provided, it produces an infinite stream of silence. ### Parameters - **generator** (MicrophoneSource | None) - Required - The audio source (callable, iterable, or None). - **params** (retro_microphone_params | None) - Optional - The capture parameters to advertise, or None to default to 44.1 kHz mono. ### Raises - **TypeError** - If generator is neither a callable, an iterable, nor None. ``` -------------------------------- ### Define Hardware Render Interface Structure Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/video/render Structure representing the base hardware rendering interface with a usage example. ```python @dataclass(init=False, slots=True) class retro_hw_render_interface(Structure): """ Corresponds to :c:type:`retro_hw_render_interface` in ``libretro.h``. Base type for hardware-specific render interfaces. >>> from libretro.api.video import retro_hw_render_interface >>> iface = retro_hw_render_interface() >>> iface.interface_version 0 """ interface_type: HardwareRenderInterfaceType """Rendering API this interface is for.""" interface_version: int """Version of this rendering interface.""" _fields_ = ( ("interface_type", retro_hw_render_interface_type), ("interface_version", c_uint), ) ``` -------------------------------- ### Initialize retro_core_options_update_display_callback Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/api/options Demonstrates instantiation of the callback wrapper used to determine if option visibility should be refreshed. ```python >>> from libretro.api import retro_core_options_update_display_callback >>> cb = retro_core_options_update_display_callback() >>> cb.callback is None True ``` -------------------------------- ### Get and Set Sensor Interface Source: https://libretropy.readthedocs.io/en/latest/_modules/libretro/drivers/environment/composite Provides the sensor interface and handles state changes, including port validation. ```python @override def _get_sensor_interface(self, interface: TypedPointer[retro_sensor_interface]) -> bool: if not interface: raise ValueError("RETRO_ENVIRONMENT_GET_SENSOR_INTERFACE doesn't accept NULL") if not self._sensor: return False if not self._sensor_interface: self._sensor_interface = retro_sensor_interface( set_sensor_state=retro_set_sensor_state_t(self._set_sensor_state), get_sensor_input=retro_sensor_get_input_t(self._get_sensor_input), ) # So that even if the sensor/input drivers are swapped out, # the core still has valid function pointers tied to non-GC'd callable objects interface[0] = self._sensor_interface return True @_return_on_raise(False) def _set_sensor_state(self, port: Port, action: int, rate: int) -> bool: if self._sensor is None: return False if self._input.max_users is not None and port >= self._input.max_users: # If we have a max-user limit set, and the port number exceeds it... return False if action not in SensorAction: # If the action isn't a valid SensorAction, then we shouldn't pass it to the driver return False return self._sensor.set_sensor_state(port, SensorAction(action), rate) ```