### Create and Manage Windows Source: https://context7.com/florianrhiem/pyglfw/llms.txt Provides examples for creating windowed and fullscreen windows, setting OpenGL context hints, and running the main event loop. ```python import glfw def create_windowed_window(): if not glfw.init(): return None glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.RESIZABLE, glfw.TRUE) window = glfw.create_window(800, 600, "My Window", None, None) if not window: glfw.terminate() return None glfw.make_context_current(window) return window window = create_windowed_window() if window: while not glfw.window_should_close(window): glfw.swap_buffers(window) glfw.poll_events() glfw.terminate() ``` -------------------------------- ### Install pyGLFW with preview support Source: https://github.com/florianrhiem/pyglfw/blob/master/README.rst This command installs pyGLFW with support for preview features, which may include wrappers for unreleased GLFW macros and functions. This is useful for development or testing with the latest GLFW features. ```sh pip install glfw[preview] ``` -------------------------------- ### GLFW Initialization and Window Creation Source: https://github.com/florianrhiem/pyglfw/blob/master/README.rst This example demonstrates how to initialize the GLFW library, create a windowed mode window, and enter the main event loop. ```APIDOC ## Initialization and Window Lifecycle ### Description Initializes the GLFW library and creates a window with an OpenGL context. The application runs a loop to process events and swap buffers until the window is closed. ### Method N/A (Python Library Function Calls) ### Parameters - **width** (int) - Required - Width of the window in pixels. - **height** (int) - Required - Height of the window in pixels. - **title** (str) - Required - Title of the window. ### Request Example ```python import glfw if not glfw.init(): return window = glfw.create_window(640, 480, "Hello World", None, None) ``` ### Response - **window** (object) - Returns a window handle or None if creation failed. ``` -------------------------------- ### Install pyGLFW via pip Source: https://context7.com/florianrhiem/pyglfw/llms.txt Commands to install the pyGLFW library and optional preview features using the Python package manager. ```bash pip install glfw # For development/preview features pip install glfw[preview] ``` -------------------------------- ### Install pyGLFW using pip Source: https://github.com/florianrhiem/pyglfw/blob/master/README.rst This command installs the pyGLFW package using pip. It is the standard method for installing Python packages. ```sh pip install glfw ``` -------------------------------- ### Check Vulkan Support and Get Extensions in PyGLFW Source: https://context7.com/florianrhiem/pyglfw/llms.txt Shows how to check if Vulkan is supported on the system using glfw.vulkan_supported() and retrieve the required instance extensions for GLFW using glfw.get_required_instance_extensions(). ```python import glfw def glfw_init(): glfw.init() def glfw_terminate(): glfw.terminate() def glfw_vulkan_supported(): return glfw.vulkan_supported() def glfw_get_required_instance_extensions(): return glfw.get_required_instance_extensions() # --- Example Usage --- glwf_init() if glfw_vulkan_supported(): print("Vulkan is supported!") # Get required instance extensions for GLFW extensions = glfw_get_required_instance_extensions() print(f"Required extensions: {extensions}") else: print("Vulkan is not supported") glwf_terminate() ``` -------------------------------- ### Get Framebuffer Size Source: https://context7.com/florianrhiem/pyglfw/llms.txt Explains the difference between window size and framebuffer size, which is critical for correctly setting the OpenGL viewport on HiDPI/Retina displays. ```python import glfw glfw.init() glfw.window_hint(glfw.SCALE_FRAMEBUFFER, glfw.TRUE) window = glfw.create_window(640, 480, "HiDPI Aware", None, None) win_width, win_height = glfw.get_window_size(window) fb_width, fb_height = glfw.get_framebuffer_size(window) print(f"Window: {win_width}x{win_height}") print(f"Framebuffer: {fb_width}x{fb_height}") glfw.terminate() ``` -------------------------------- ### Joystick Input and Gamepad State Source: https://context7.com/florianrhiem/pyglfw/llms.txt This section covers checking for connected joysticks, retrieving their names and GUIDs, and accessing raw input data for axes, buttons, and hats. It also explains how to get gamepad state using a standard mapping. ```APIDOC ## Joystick Presence and Information ### Description Checks for connected joysticks (0-15) and retrieves their names, GUIDs, and whether they are recognized as gamepads. ### Method GET (Implicit) ### Endpoint N/A (Function calls) ### Parameters None ### Request Example ```python import glfw glfw.init() for jid in range(16): if glfw.joystick_present(jid): name = glfw.get_joystick_name(jid).decode() guid = glfw.get_joystick_guid(jid).decode() is_gamepad = glfw.joystick_is_gamepad(jid) print(f"Joystick {jid}: {name}") print(f" GUID: {guid}") print(f" Gamepad: {is_gamepad}") if is_gamepad: gamepad_name = glfw.get_gamepad_name(jid) print(f" Gamepad name: {gamepad_name}") g glfw.terminate() ``` ### Response Prints information about connected joysticks to the console. ### Response Example ``` Joystick 0: Xbox 360 Controller (XInput) GUID: 05000000fe4000000100000000000000 Gamepad: True Gamepad name: Xbox 360 Controller (XInput) ``` ## glfw.get_joystick_axes / glfw.get_joystick_buttons ### Description Gets the raw input values for joystick axes (analog sticks, triggers) and buttons. Also retrieves D-pad/hat states. ### Method GET (Implicit) ### Endpoint N/A (Function calls) ### Parameters - **jid** (int) - Required - The joystick ID (0-15). ### Request Example ```python import glfw glfw.init() window = glfw.create_window(640, 480, "Joystick", None, None) while not glfw.window_should_close(window): for jid in range(16): if not glfw.joystick_present(jid): continue axes, axis_count = glfw.get_joystick_axes(jid) axes_values = [axes[i] for i in range(axis_count)] buttons, button_count = glfw.get_joystick_buttons(jid) buttons_values = [buttons[i] for i in range(button_count)] hats, hat_count = glfw.get_joystick_hats(jid) if any(b == glfw.PRESS for b in buttons_values[:4]): print(f"Button pressed on joystick {jid}") glfw.poll_events() glfw.swap_buffers(window) glwf.terminate() ``` ### Response Returns tuples containing arrays of axis values, button states, and hat states. #### Success Response (200) - **axes** (list of float) - Values for analog axes (-1.0 to 1.0). - **axis_count** (int) - Number of axes. - **buttons** (list of int) - Button states (0 for released, 1 for pressed). - **button_count** (int) - Number of buttons. - **hats** (list of int) - Hat states (bitmask). - **hat_count** (int) - Number of hats. ### Response Example ``` # Example output when a button is pressed: Button pressed on joystick 0 ``` ## glfw.get_gamepad_state ### Description Retrieves the current state of a gamepad using a standard mapping for buttons and axes. This is the recommended way to handle gamepad input. ### Method GET (Implicit) ### Endpoint N/A (Function calls) ### Parameters - **jid** (int) - Required - The joystick ID (0-15). ### Request Example ```python import glfw glfw.init() window = glfw.create_window(640, 480, "Gamepad", None, None) while not glfw.window_should_close(window): for jid in range(16): if not glfw.joystick_present(jid) or not glfw.joystick_is_gamepad(jid): continue state = glfw.get_gamepad_state(jid) if state is None: continue buttons, axes = state if buttons[glfw.GAMEPAD_BUTTON_A]: print("A/Cross pressed") if buttons[glfw.GAMEPAD_BUTTON_B]: print("B/Circle pressed") left_trigger = axes[glfw.GAMEPAD_AXIS_LEFT_TRIGGER] right_trigger = axes[glfw.GAMEPAD_AXIS_RIGHT_TRIGGER] left_x = axes[glfw.GAMEPAD_AXIS_LEFT_X] left_y = axes[glfw.GAMEPAD_AXIS_LEFT_Y] right_x = axes[glfw.GAMEPAD_AXIS_RIGHT_X] right_y = axes[glfw.GAMEPAD_AXIS_RIGHT_Y] deadzone = 0.2 if abs(left_x) > deadzone or abs(left_y) > deadzone: print(f"Left stick: ({left_x:.2f}, {left_y:.2f})") glfw.poll_events() glfw.swap_buffers(window) glwf.terminate() ``` ### Response Returns a tuple containing the gamepad's button and axis states, or None if the gamepad is not present or not recognized. #### Success Response (200) - **state** (tuple) - Contains two lists: `buttons` (list of bool) and `axes` (list of float). - **buttons** (list of bool) - State of each gamepad button. - **axes** (list of float) - Values for each gamepad axis (-1.0 to 1.0). ### Response Example ``` A/Cross pressed Left stick: (0.55, -0.12) ``` ``` -------------------------------- ### glfw.set_window_opacity / glfw.get_window_opacity Source: https://context7.com/florianrhiem/pyglfw/llms.txt Functions to set and get the transparency level of a window. ```APIDOC ## glfw.set_window_opacity / glfw.get_window_opacity ### Description Sets or gets the opacity of a window. The opacity value ranges from 0.0 (fully transparent) to 1.0 (fully opaque). ### Method - `glfw.get_window_opacity(window)`: Returns the current opacity of the window. - `glfw.set_window_opacity(window, opacity)`: Sets the opacity of the window. ### Parameters - **window**: The window whose opacity is to be retrieved or set. - **opacity** (float): The desired opacity value (0.0 to 1.0). ### Request Example ```python import glfw glwf.init() window = glfw.create_window(640, 480, "Transparent", None, None) # Get current opacity opacity = glfw.get_window_opacity(window) print(f"Current opacity: {opacity}") # Make window semi-transparent glwf.set_window_opacity(window, 0.8) # Animate opacity import time for i in range(10): glfw.set_window_opacity(window, 0.5 + (i * 0.05)) glfw.poll_events() time.sleep(0.1) glwf.terminate() ``` ``` -------------------------------- ### Clipboard Access Source: https://context7.com/florianrhiem/pyglfw/llms.txt This section explains how to set and get text content from the system clipboard. ```APIDOC ## Clipboard Access ### glfw.set_clipboard_string / glfw.get_clipboard_string ### Description Allows you to set text content to the system clipboard and retrieve text content from it. ### Method SET / GET ### Endpoint N/A (Function calls) ### Parameters - **`glfw.set_clipboard_string`**: - **`window`** (object or None) - The window that is the focus of clipboard operations. Can be None. - **`string`** (bytes) - Required - The string to be set to the clipboard. - **`glfw.get_clipboard_string`**: - **`window`** (object or None) - The window that is the focus of clipboard operations. Can be None. ### Request Example ```python import glfw glwf.init() window = glfw.create_window(640, 480, "Clipboard", None, None) # Set clipboard content glwf.set_clipboard_string(None, b"Hello from pyGLFW!") # Get clipboard content content = glfw.get_clipboard_string(None) if content: print(f"Clipboard: {content.decode()}") else: print("Clipboard is empty or contains non-text data") glwf.terminate() ``` ### Response - **`glfw.set_clipboard_string`**: Returns nothing on success. - **`glfw.get_clipboard_string`**: Returns the clipboard content as bytes, or None if empty or non-text. #### Success Response (200) - **content** (bytes or None) - The content retrieved from the clipboard. ### Response Example ``` Clipboard: Hello from pyGLFW! ``` ``` -------------------------------- ### Get Gamepad State with Standard Mapping Source: https://context7.com/florianrhiem/pyglfw/llms.txt Initializes GLFW and creates a window, then enters a loop to poll for gamepad input. It checks for connected gamepads and retrieves their state using the standard mapping. The code demonstrates how to check face buttons, bumpers, triggers, and analog sticks, including applying a deadzone to the analog stick values. ```python import glfw glfw.init() window = glfw.create_window(640, 480, "Gamepad", None, None) while not glfw.window_should_close(window): for jid in range(16): if not glfw.joystick_present(jid) or not glfw.joystick_is_gamepad(jid): continue state = glfw.get_gamepad_state(jid) if state is None: continue buttons, axes = state # Check face buttons (A, B, X, Y / Cross, Circle, Square, Triangle) if buttons[glfw.GAMEPAD_BUTTON_A]: print("A/Cross pressed") if buttons[glfw.GAMEPAD_BUTTON_B]: print("B/Circle pressed") # Check bumpers and triggers if buttons[glfw.GAMEPAD_BUTTON_LEFT_BUMPER]: print("Left bumper") left_trigger = axes[glfw.GAMEPAD_AXIS_LEFT_TRIGGER] # -1 to 1 right_trigger = axes[glfw.GAMEPAD_AXIS_RIGHT_TRIGGER] # Check analog sticks left_x = axes[glfw.GAMEPAD_AXIS_LEFT_X] # -1 to 1 left_y = axes[glfw.GAMEPAD_AXIS_LEFT_Y] right_x = axes[glfw.GAMEPAD_AXIS_RIGHT_X] right_y = axes[glfw.GAMEPAD_AXIS_RIGHT_Y] # Apply deadzone deadzone = 0.2 if abs(left_x) > deadzone or abs(left_y) > deadzone: print(f"Left stick: ({left_x:.2f}, {left_y:.2f})") glfw.poll_events() glfw.swap_buffers(window) glfw.terminate() ``` -------------------------------- ### Get Video Modes - PyGLFW Source: https://context7.com/florianrhiem/pyglfw/llms.txt Fetches the current and all available video modes for a given monitor, including resolution and refresh rate. This allows querying display capabilities. Requires GLFW initialization and a monitor handle. ```python import glfw glfw.init() monitor = glfw.get_primary_monitor() # Get current video mode current = glfw.get_video_mode(monitor) print(f"Current mode: {current.size.width}x{current.size.height} @ {current.refresh_rate}Hz") print(f" Color bits: R{current.bits.red} G{current.bits.green} B{current.bits.blue}") # Get all available video modes modes = glfw.get_video_modes(monitor) print(f"\nAvailable modes ({len(modes)}):") for mode in modes[-5:]: # Show last 5 (usually highest resolutions) print(f" {mode.size.width}x{mode.size.height} @ {mode.refresh_rate}Hz") glfw.terminate() ``` -------------------------------- ### Get High-Resolution Timer Values Source: https://context7.com/florianrhiem/pyglfw/llms.txt Initializes GLFW. This snippet is intended to demonstrate the retrieval of high-resolution timer values using `glfw.get_timer_value` and `glfw.get_timer_frequency`. Further implementation would involve using these values for precise time measurements. ```python import glfw gglfw.init() ``` -------------------------------- ### Get Raw Joystick Input (Axes and Buttons) Source: https://context7.com/florianrhiem/pyglfw/llms.txt Initializes GLFW, creates a window, and enters a loop to continuously poll for joystick input. It retrieves raw axes (analog sticks, triggers) and button states for connected joysticks. It also checks for D-pad/hat input and prints messages when specific buttons are pressed. ```python import glfw glfw.init() window = glfw.create_window(640, 480, "Joystick", None, None) while not glfw.window_should_close(window): for jid in range(16): if not glfw.joystick_present(jid): continue # Get axes (analog sticks, triggers) axes, axis_count = glfw.get_joystick_axes(jid) axes_values = [axes[i] for i in range(axis_count)] # Get buttons buttons, button_count = glfw.get_joystick_buttons(jid) buttons_values = [buttons[i] for i in range(button_count)] # Get D-pad/hat hats, hat_count = glfw.get_joystick_hats(jid) if any(b == glfw.PRESS for b in buttons_values[:4]): print(f"Button pressed on joystick {jid}") glfw.poll_events() glfw.swap_buffers(window) glfw.terminate() ``` -------------------------------- ### Get and Set GLFW Timer Value Source: https://context7.com/florianrhiem/pyglfw/llms.txt Initializes GLFW and creates a window. It resets the GLFW timer to 0.0 and then enters a loop that continuously measures the elapsed time. It calculates and prints the frames per second (FPS) and frame time every second, resetting the timer after each calculation. ```python import glfw gglfw.init() window = glfw.create_window(640, 480, "Timer", None, None) # Reset timer gglfw.set_time(0.0) last_time = glfw.get_time() frame_count = 0 while not glfw.window_should_close(window): current_time = glfw.get_time() delta_time = current_time - last_time frame_count += 1 if current_time >= 1.0: fps = frame_count / current_time print(f"FPS: {fps:.1f}, Frame time: {delta_time * 1000:.2f}ms") frame_count = 0 glfw.set_time(0.0) current_time = 0.0 last_time = current_time glfw.poll_events() glfw.swap_buffers(window) gglfw.terminate() ``` -------------------------------- ### Get Monitor Information - PyGLFW Source: https://context7.com/florianrhiem/pyglfw/llms.txt Retrieves details about connected monitors, including their names, positions, physical dimensions, content scaling factors, and work areas. It also identifies the primary monitor. Requires GLFW initialization. ```python import glfw glfw.init() # Get all monitors monitors = glfw.get_monitors() print(f"Found {len(monitors)} monitor(s)") # Get primary monitor primary = glfw.get_primary_monitor() for i, monitor in enumerate(monitors): name = glfw.get_monitor_name(monitor).decode() pos_x, pos_y = glfw.get_monitor_pos(monitor) phys_width, phys_height = glfw.get_monitor_physical_size(monitor) scale_x, scale_y = glfw.get_monitor_content_scale(monitor) # Get work area (excluding taskbar/dock) work_x, work_y, work_w, work_h = glfw.get_monitor_workarea(monitor) is_primary = " (Primary)" if monitor == primary else "" print(f"\nMonitor {i}{is_primary}: {name}") print(f" Position: ({pos_x}, {pos_y})") print(f" Physical size: {phys_width}mm x {phys_height}mm") print(f" Content scale: {scale_x}x, {scale_y}x") print(f" Work area: ({work_x}, {work_y}) {work_w}x{work_h}") glfw.terminate() ``` -------------------------------- ### Check Joystick Presence and Information Source: https://context7.com/florianrhiem/pyglfw/llms.txt Iterates through all possible joystick slots (0-15) to check if a joystick is present. If found, it retrieves and prints the joystick's name, GUID, and whether it's recognized as a gamepad. For gamepads, it also fetches the specific gamepad name. ```python import glfw # Check all joystick slots (0-15) for jid in range(16): if glfw.joystick_present(jid): name = glfw.get_joystick_name(jid).decode() guid = glfw.get_joystick_guid(jid).decode() is_gamepad = glfw.joystick_is_gamepad(jid) print(f"Joystick {jid}: {name}") print(f" GUID: {guid}") print(f" Gamepad: {is_gamepad}") if is_gamepad: gamepad_name = glfw.get_gamepad_name(jid) print(f" Gamepad name: {gamepad_name}") glfw.terminate() ``` -------------------------------- ### Configure Window Hints Source: https://context7.com/florianrhiem/pyglfw/llms.txt Demonstrates how to set various window creation hints, such as OpenGL version, profile, and window decoration settings, before creating a window. ```python import glfw glfw.init() glfw.default_window_hints() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, glfw.TRUE) glfw.window_hint(glfw.RESIZABLE, glfw.TRUE) glfw.window_hint(glfw.VISIBLE, glfw.TRUE) glfw.window_hint(glfw.DECORATED, glfw.TRUE) glfw.window_hint(glfw.FOCUSED, glfw.TRUE) glfw.window_hint(glfw.FLOATING, glfw.FALSE) glfw.window_hint(glfw.MAXIMIZED, glfw.FALSE) glfw.window_hint(glfw.TRANSPARENT_FRAMEBUFFER, glfw.FALSE) ``` -------------------------------- ### Initialize and Run Application Source: https://context7.com/florianrhiem/pyglfw/llms.txt This endpoint-like structure demonstrates how to initialize a GLFW window, set up event callbacks for input handling, and execute the main application loop. ```APIDOC ## Initialization and Event Loop ### Description Initializes the GLFW library, creates a window with specific OpenGL version hints, registers event callbacks for user interaction, and runs the main event loop. ### Method N/A (Library Initialization) ### Endpoint Application.init() / Application.run() ### Parameters #### Request Body - **width** (int) - Optional - Window width in pixels - **height** (int) - Optional - Window height in pixels - **title** (string) - Optional - Window title string ### Request Example { "width": 1024, "height": 768, "title": "My Game" } ### Response #### Success Response (200) - **status** (boolean) - Returns True if initialization and loop execution succeed. #### Response Example { "status": true } ``` -------------------------------- ### Configure and Create GLFW Window Source: https://context7.com/florianrhiem/pyglfw/llms.txt Demonstrates how to set framebuffer hints such as bit depth, stencil bits, and MSAA samples before creating a window. This ensures the rendering context meets specific graphical requirements. ```python import glfw glfw.window_hint(glfw.RED_BITS, 8) glfw.window_hint(glfw.GREEN_BITS, 8) glfw.window_hint(glfw.BLUE_BITS, 8) glfw.window_hint(glfw.ALPHA_BITS, 8) glfw.window_hint(glfw.DEPTH_BITS, 24) glfw.window_hint(glfw.STENCIL_BITS, 8) glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.DOUBLEBUFFER, glfw.TRUE) window = glfw.create_window(800, 600, "Configured Window", None, None) glfw.terminate() ``` -------------------------------- ### Get Timer Frequency and Value in PyGLFW Source: https://context7.com/florianrhiem/pyglfw/llms.txt Demonstrates how to get the timer frequency (ticks per second) and the current timer value using glfw.get_timer_frequency() and glfw.get_timer_value(). It calculates the elapsed time for a given operation. ```python import glfw # Get timer frequency (ticks per second) frequency = glfw.get_timer_frequency() print(f"Timer frequency: {frequency:,} Hz") # Get current timer value start = glfw.get_timer_value() # Do some work... for _ in range(1000000): pass end = glfw.get_timer_value() # Calculate elapsed time elapsed_ticks = end - start elapsed_seconds = elapsed_ticks / frequency print(f"Elapsed: {elapsed_seconds * 1000:.3f} ms") glfw.terminate() ``` -------------------------------- ### Initialize Window and Handle Input with pyGLFW Source: https://context7.com/florianrhiem/pyglfw/llms.txt This snippet demonstrates how to create an Application class that initializes a GLFW window and registers callbacks for keyboard, mouse, and window resize events. It includes a main loop that processes events and manages window state. ```python import glfw import sys class Application: def __init__(self, width=800, height=600, title="pyGLFW Application"): self.width = width self.height = height self.title = title self.window = None self.mouse_x = 0 self.mouse_y = 0 self.keys = {} def init(self): if not glfw.init(): return False glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, glfw.TRUE) self.window = glfw.create_window(self.width, self.height, self.title, None, None) if not self.window: glfw.terminate() return False glfw.make_context_current(self.window) glfw.swap_interval(1) glfw.set_window_user_pointer(self.window, self) glfw.set_key_callback(self.window, Application._key_callback) glfw.set_cursor_pos_callback(self.window, Application._cursor_callback) glfw.set_mouse_button_callback(self.window, Application._mouse_button_callback) glfw.set_framebuffer_size_callback(self.window, Application._resize_callback) glfw.set_drop_callback(self.window, Application._drop_callback) return True @staticmethod def _key_callback(window, key, scancode, action, mods): app = glfw.get_window_user_pointer(window) app.keys[key] = action != glfw.RELEASE if key == glfw.KEY_ESCAPE and action == glfw.PRESS: glfw.set_window_should_close(window, True) @staticmethod def _cursor_callback(window, x, y): app = glfw.get_window_user_pointer(window) app.mouse_x, app.mouse_y = x, y @staticmethod def _mouse_button_callback(window, button, action, mods): app = glfw.get_window_user_pointer(window) if action == glfw.PRESS: print(f"Click at ({app.mouse_x:.0f}, {app.mouse_y:.0f})") @staticmethod def _resize_callback(window, width, height): app = glfw.get_window_user_pointer(window) app.width, app.height = width, height @staticmethod def _drop_callback(window, paths): print(f"Dropped: {paths}") def is_key_pressed(self, key): return self.keys.get(key, False) def run(self): while not glfw.window_should_close(self.window): if self.is_key_pressed(glfw.KEY_W): print("Moving forward") glfw.swap_buffers(self.window) glfw.poll_events() glfw.terminate() if __name__ == "__main__": app = Application(1024, 768, "My Game") if app.init(): app.run() else: sys.exit(1) ``` -------------------------------- ### Show and Hide Window Source: https://context7.com/florianrhiem/pyglfw/llms.txt Demonstrates creating a window in a hidden state and toggling its visibility programmatically. ```python import glfw glfw.init() glfw.window_hint(glfw.VISIBLE, glfw.FALSE) window = glfw.create_window(640, 480, "Hidden Initially", None, None) glfw.show_window(window) glfw.hide_window(window) glfw.terminate() ``` -------------------------------- ### Access System Clipboard Source: https://context7.com/florianrhiem/pyglfw/llms.txt Initializes GLFW and creates a window. It then demonstrates setting the system clipboard's text content using `glfw.set_clipboard_string` and retrieving it using `glfw.get_clipboard_string`. The retrieved content is decoded and printed, or a message indicating an empty clipboard is shown. ```python import glfw gglfw.init() window = glfw.create_window(640, 480, "Clipboard", None, None) # Set clipboard content gglfw.set_clipboard_string(None, "Hello from pyGLFW!") # Get clipboard content content = glfw.get_clipboard_string(None) if content: print(f"Clipboard: {content.decode()}") else: print("Clipboard is empty or contains non-text data") gglfw.terminate() ``` -------------------------------- ### Manage Window Position Source: https://context7.com/florianrhiem/pyglfw/llms.txt Demonstrates how to query window position and programmatically center a window on the primary monitor. ```python import glfw glfw.init() window = glfw.create_window(640, 480, "Positioned", None, None) x, y = glfw.get_window_pos(window) monitor = glfw.get_primary_monitor() mode = glfw.get_video_mode(monitor) win_width, win_height = glfw.get_window_size(window) new_x = (mode.size.width - win_width) // 2 new_y = (mode.size.height - win_height) // 2 glfw.set_window_pos(window, new_x, new_y) glfw.terminate() ``` -------------------------------- ### Basic GLFW Window Creation and Event Loop in Python Source: https://github.com/florianrhiem/pyglfw/blob/master/README.rst This Python code demonstrates the fundamental usage of pyGLFW to initialize the library, create a window, set up an OpenGL context, and run a basic event loop. It includes error handling for initialization and window creation, and demonstrates swapping buffers and polling events. ```python import glfw def main(): # Initialize the library if not glfw.init(): return # Create a windowed mode window and its OpenGL context window = glfw.create_window(640, 480, "Hello World", None, None) if not window: glfw.terminate() return # Make the window's context current glfw.make_context_current(window) # Loop until the user closes the window while not glfw.window_should_close(window): # Render here, e.g. using pyOpenGL # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate() if __name__ == "__main__": main() ``` -------------------------------- ### Check Joystick Presence and Get Name - PyGLFW Source: https://context7.com/florianrhiem/pyglfw/llms.txt Provides functions to check if a joystick is connected and to retrieve its name. This is the first step in handling joystick input. Requires GLFW initialization. ```python import glfw gglfw.init() # Example usage would follow to check specific joystick IDs # if glfw.joystick_present(glfw.JOYSTICK_1): # name = glfw.get_joystick_name(glfw.JOYSTICK_1) # print(f"Joystick 1: {name}") # glfw.terminate() ``` -------------------------------- ### Manage OpenGL Context with glfw.make_context_current Source: https://context7.com/florianrhiem/pyglfw/llms.txt Shows how to initialize GLFW, create multiple windows, and manage their OpenGL contexts using glfw.make_context_current() and glfw.get_current_context(). This allows for shared contexts and rendering to different windows. ```python import glfw glViewport = None # Placeholder for actual glViewport function def glfw_init(): glfw.init() def glfw_terminate(): glfw.terminate() def glfw_create_window(width, height, title, monitor, share): return glfw.create_window(width, height, title, monitor, share) def glfw_make_context_current(window): glfw.make_context_current(window) def glfw_get_current_context(): return glfw.get_current_context() def glfw_window_should_close(window): return glfw.window_should_close(window) def glfw_swap_buffers(window): glfw.swap_buffers(window) def glfw_poll_events(): glfw.poll_events() # --- Example Usage --- glwf_init() # Create multiple windows with shared context window1 = glfw_create_window(640, 480, "Window 1", None, None) glwf_make_context_current(window1) window2 = glfw_create_window(640, 480, "Window 2", None, window1) # Share with window1 # Make window1's context current glwf_make_context_current(window1) # Get current context current = glfw_get_current_context() print(f"Current context: {current}") # Switch to window2 glwf_make_context_current(window2) # Render loop for both windows while not glfw_window_should_close(window1) and not glfw_window_should_close(window2): # Render to window1 glfw_make_context_current(window1) # ... OpenGL rendering ... glfw_swap_buffers(window1) # Render to window2 glfw_make_context_current(window2) # ... OpenGL rendering ... glfw_swap_buffers(window2) glfw_poll_events() glwf_terminate() ``` -------------------------------- ### Manage Window Size and Constraints Source: https://context7.com/florianrhiem/pyglfw/llms.txt Covers retrieving and setting window dimensions, as well as applying constraints like size limits and aspect ratios. ```python import glfw glfw.init() window = glfw.create_window(640, 480, "Resizable", None, None) width, height = glfw.get_window_size(window) glfw.set_window_size(window, 1024, 768) glfw.set_window_size_limits(window, 320, 240, 1920, 1080) glfw.set_window_aspect_ratio(window, 16, 9) glfw.terminate() ``` -------------------------------- ### Create Custom and Standard Cursors - PyGLFW Source: https://context7.com/florianrhiem/pyglfw/llms.txt Demonstrates creating both standard cursors (like arrow, I-beam) and custom cursors from pixel data using PyGLFW. It shows how to set these cursors for a window and how to clean them up. Requires GLFW initialization and a window context. ```python import glfw glfw.init() window = glfw.create_window(640, 480, "Custom Cursor", None, None) # Standard cursors arrow_cursor = glfw.create_standard_cursor(glfw.ARROW_CURSOR) ibeam_cursor = glfw.create_standard_cursor(glfw.IBEAM_CURSOR) hand_cursor = glfw.create_standard_cursor(glfw.POINTING_HAND_CURSOR) crosshair_cursor = glfw.create_standard_cursor(glfw.CROSSHAIR_CURSOR) resize_h_cursor = glfw.create_standard_cursor(glfw.RESIZE_EW_CURSOR) resize_v_cursor = glfw.create_standard_cursor(glfw.RESIZE_NS_CURSOR) # Set cursor glfw.set_cursor(window, hand_cursor) # Custom cursor from pixel data width, height = 16, 16 pixels = [[[255, 255, 255, 255] if (x + y) % 2 == 0 else [0, 0, 0, 255] for x in range(width)] for y in range(height)] custom_cursor = glfw.create_cursor((width, height, pixels), 8, 8) # hotspot at center glfw.set_cursor(window, custom_cursor) # Reset to default cursor glfw.set_cursor(window, None) # Clean up cursors glfw.destroy_cursor(custom_cursor) glfw.destroy_cursor(arrow_cursor) glfw.terminate() ``` -------------------------------- ### Window Icon Management Source: https://context7.com/florianrhiem/pyglfw/llms.txt Demonstrates how to set a window icon using either PIL/Pillow Image or raw pixel data. ```APIDOC ## Window Icon Management ### Description This section shows how to set a window icon using either the PIL/Pillow library for image loading or by providing raw RGBA pixel data. ### Usage ```python try: from PIL import Image icon = Image.open("icon.png") glfw.set_window_icon(window, 1, icon) except ImportError: # Using raw pixel data: (width, height, pixels) # pixels is a 3D array: [row][col][rgba] width, height = 16, 16 pixels = [[[255, 0, 0, 255] for _ in range(width)] for _ in range(height)] glfw.set_window_icon(window, 1, (width, height, pixels)) ``` ``` -------------------------------- ### Set Window Icon with PyGLFW Source: https://context7.com/florianrhiem/pyglfw/llms.txt Demonstrates how to set a window icon using either a PIL/Pillow image or raw pixel data. Requires the PIL library for the recommended image-based approach. ```python try: from PIL import Image icon = Image.open("icon.png") glfw.set_window_icon(window, 1, icon) except ImportError: width, height = 16, 16 pixels = [[[255, 0, 0, 255] for _ in range(width)] for _ in range(height)] glfw.set_window_icon(window, 1, (width, height, pixels)) ``` -------------------------------- ### Initialize and Terminate GLFW Source: https://context7.com/florianrhiem/pyglfw/llms.txt Demonstrates the mandatory initialization and termination lifecycle for a GLFW application to ensure resources are managed correctly. ```python import glfw def main(): if not glfw.init(): raise RuntimeError("Failed to initialize GLFW") try: print(f"GLFW initialized successfully") print(f"Version: {glfw.get_version_string().decode()}") finally: glfw.terminate() if __name__ == "__main__": main() ``` -------------------------------- ### Set Scroll Callback for Mouse Wheel Events in Python Source: https://context7.com/florianrhiem/pyglfw/llms.txt Implements a callback function that triggers on mouse scroll wheel events, capturing horizontal (xoffset) and vertical (yoffset) scroll amounts. This example demonstrates adjusting a zoom level based on vertical scroll. Dependencies include the glfw library. ```python import glfw zoom_level = 1.0 def scroll_callback(window, xoffset, yoffset): """ xoffset: Horizontal scroll (touchpad) yoffset: Vertical scroll (positive = up) """ global zoom_level zoom_level += yoffset * 0.1 zoom_level = max(0.1, min(10.0, zoom_level)) print(f"Zoom: {zoom_level:.1f}x") glwf.init() window = glfw.create_window(640, 480, "Scroll Zoom", None, None) glwf.set_scroll_callback(window, scroll_callback) while not glfw.window_should_close(window): glfw.poll_events() glfw.swap_buffers(window) glwf.terminate() ``` -------------------------------- ### Control Window State Source: https://context7.com/florianrhiem/pyglfw/llms.txt Shows how to iconify, restore, and maximize windows, as well as how to query the current state of a window. ```python import glfw glfw.init() window = glfw.create_window(640, 480, "Window State", None, None) glfw.iconify_window(window) glfw.restore_window(window) glfw.maximize_window(window) is_iconified = glfw.get_window_attrib(window, glfw.ICONIFIED) is_maximized = glfw.get_window_attrib(window, glfw.MAXIMIZED) glfw.terminate() ``` -------------------------------- ### Handle Keyboard Input with PyGLFW Source: https://context7.com/florianrhiem/pyglfw/llms.txt Demonstrates keyboard input handling using both event-driven callbacks and direct state polling. Callbacks are useful for discrete triggers, while polling is ideal for continuous movement. ```python # Callback approach def key_callback(window, key, scancode, action, mods): if action == glfw.PRESS and key == glfw.KEY_ESCAPE: glfw.set_window_should_close(window, True) # Polling approach if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS: player_y += speed ``` -------------------------------- ### Vulkan Support Source: https://context7.com/florianrhiem/pyglfw/llms.txt Checks for Vulkan support and retrieves required instance extensions. ```APIDOC ## glfw.vulkan_supported ### Description Determines if the Vulkan API is supported on the current machine. ### Method Function Call ### Response #### Success Response (200) - **supported** (boolean) - True if Vulkan is supported, False otherwise. ``` -------------------------------- ### Retrieve GLFW Version Information Source: https://context7.com/florianrhiem/pyglfw/llms.txt Shows how to fetch the library version as a tuple or a full version string for debugging or compatibility checks. ```python import glfw if glfw.init(): major, minor, revision = glfw.get_version() print(f"GLFW Version: {major}.{minor}.{revision}") version_string = glfw.get_version_string() print(f"Version String: {version_string.decode()}") glfw.terminate() ``` -------------------------------- ### Set Window Resize Callbacks in PyGLFW Source: https://context7.com/florianrhiem/pyglfw/llms.txt Demonstrates setting up callbacks for window resize events using glfw.set_window_size_callback() and glfw.set_framebuffer_size_callback(). These functions are invoked when the window's screen coordinates or pixel dimensions change, respectively. ```python import glfw def window_size_callback(window, width, height): """Called when window size changes (in screen coordinates).""" print(f"Window resized to {width}x{height}") def framebuffer_size_callback(window, width, height): """Called when framebuffer size changes (in pixels).""" print(f"Framebuffer resized to {width}x{height}") # Update OpenGL viewport # glViewport(0, 0, width, height) def glfw_init(): glfw.init() def glfw_terminate(): glfw.terminate() def glfw_create_window(width, height, title, monitor, share): return glfw.create_window(width, height, title, monitor, share) def glfw_set_window_size_callback(window, callback): glfw.set_window_size_callback(window, callback) def glfw_set_framebuffer_size_callback(window, callback): glfw.set_framebuffer_size_callback(window, callback) def glfw_window_should_close(window): return glfw.window_should_close(window) def glfw_poll_events(): glfw.poll_events() def glfw_swap_buffers(window): glfw.swap_buffers(window) # --- Example Usage --- glwf_init() window = glfw_create_window(640, 480, "Resize Events", None, None) glwf_set_window_size_callback(window, window_size_callback) glwf_set_framebuffer_size_callback(window, framebuffer_size_callback) while not glfw_window_should_close(window): glfw_poll_events() glfw_swap_buffers(window) glwf_terminate() ``` -------------------------------- ### Use GLFW C-Style API Source: https://context7.com/florianrhiem/pyglfw/llms.txt Demonstrates using the original GLFW C naming convention within Python by importing from glfw.GLFW. This is useful for developers familiar with the native C library. ```python from glfw.GLFW import * def main(): if not glfwInit(): return glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3) glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3) glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE) window = glfwCreateWindow(640, 480, "C-Style API", None, None) if not window: glfwTerminate() return glfwMakeContextCurrent(window) glfwSwapInterval(1) while not glfwWindowShouldClose(window): glfwSwapBuffers(window) glfwPollEvents() glfwDestroyWindow(window) glfwTerminate() if __name__ == "__main__": main() ``` -------------------------------- ### Window User Pointers Source: https://context7.com/florianrhiem/pyglfw/llms.txt Associates arbitrary Python objects with GLFW windows for state management. ```APIDOC ## FUNCTION glfw.set_window_user_pointer ### Description Stores a Python object in the window instance. ### Parameters - **window** (GLFWwindow) - Required - The target window. - **pointer** (object) - Required - The object to store. ## FUNCTION glfw.get_window_user_pointer ### Description Retrieves the object associated with the window. ### Response - **object** (any) - The stored user object. ``` -------------------------------- ### Set Input Modes for Cursor and Keys in Python Source: https://context7.com/florianrhiem/pyglfw/llms.txt Demonstrates how to set various input modes for a GLFW window, including cursor visibility (normal, hidden, disabled/captured) and enabling sticky keys/mouse buttons. Dependencies include the glfw library. ```python import glfw glwf.init() window = glfw.create_window(640, 480, "Input Modes", None, None) # Cursor modes glwf.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_NORMAL) # Normal cursor glwf.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_HIDDEN) # Hidden cursor glwf.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) # Captured cursor (FPS games) glwf.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_CAPTURED) # Captured but visible # Sticky keys - PRESS state persists until get_key is called glwf.set_input_mode(window, glfw.STICKY_KEYS, glfw.TRUE) # Sticky mouse buttons glwf.set_input_mode(window, glfw.STICKY_MOUSE_BUTTONS, glfw.TRUE) ``` -------------------------------- ### Manage Window Opacity with PyGLFW Source: https://context7.com/florianrhiem/pyglfw/llms.txt Shows how to retrieve and modify the opacity of a window. Opacity values range from 0.0 (transparent) to 1.0 (opaque). ```python opacity = glfw.get_window_opacity(window) print(f"Current opacity: {opacity}") glfw.set_window_opacity(window, 0.8) for i in range(10): glfw.set_window_opacity(window, 0.5 + (i * 0.05)) glfw.poll_events() time.sleep(0.1) ``` -------------------------------- ### Window Resize Callbacks Source: https://context7.com/florianrhiem/pyglfw/llms.txt Sets callbacks to handle window and framebuffer size changes. ```APIDOC ## glfw.set_window_size_callback / glfw.set_framebuffer_size_callback ### Description Registers callback functions that are triggered when the user resizes the window or when the underlying framebuffer changes size. ### Method Function Call ### Parameters #### Path Parameters - **window** (object) - Required - The window handle. - **callback** (function) - Required - The function to execute on resize. ### Request Example ```python glfw.set_window_size_callback(window, window_size_callback) ``` ### Response #### Success Response (200) - **status** (null) - Returns None. ``` -------------------------------- ### Query OpenGL Extensions and Function Addresses in PyGLFW Source: https://context7.com/florianrhiem/pyglfw/llms.txt Demonstrates how to check for OpenGL extension support using glfw.extension_supported() and retrieve function pointers with glfw.get_proc_address(). This is crucial for using advanced OpenGL features. ```python import glfw def glfw_init(): glfw.init() def glfw_terminate(): glfw.terminate() def glfw_create_window(width, height, title, monitor, share): return glfw.create_window(width, height, title, monitor, share) def glfw_make_context_current(window): glfw.make_context_current(window) def glfw_extension_supported(extension_name): return glfw.extension_supported(extension_name) def glfw_get_proc_address(proc_name): return glfw.get_proc_address(proc_name) # --- Example Usage --- glwf_init() window = glfw_create_window(640, 480, "Extensions", None, None) glwf_make_context_current(window) # Check if extension is supported if glfw_extension_supported("GL_ARB_debug_output"): print("Debug output extension is supported") # Get function pointer addr = glfw_get_proc_address("glDebugMessageCallback") print(f"Function address: {addr}") glwf_terminate() ```