From 87cc4584371cfba38e213d770e6aa138104a1bde Mon Sep 17 00:00:00 2001 From: Ayesh Ahmad Date: Sun, 5 Jan 2025 00:53:19 +0500 Subject: [PATCH] Add error message when terminating the MuJoCo renderer without calling `env.close` (#1283) Co-authored-by: Ayesh Ahmad --- gymnasium/envs/mujoco/mujoco_rendering.py | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/gymnasium/envs/mujoco/mujoco_rendering.py b/gymnasium/envs/mujoco/mujoco_rendering.py index d6b888103..7427a1499 100644 --- a/gymnasium/envs/mujoco/mujoco_rendering.py +++ b/gymnasium/envs/mujoco/mujoco_rendering.py @@ -7,6 +7,8 @@ import mujoco import numpy as np +from gymnasium.logger import warn + def _import_egl(width, height): from mujoco.egl import GLContext @@ -356,11 +358,22 @@ def make_context_current(self): glfw.make_context_current(self.window) def free(self): - if self.window: - if glfw.get_current_context() == self.window: - glfw.make_context_current(None) - glfw.destroy_window(self.window) - self.window = None + """ + Safely frees the OpenGL context and destroys the GLFW window, + handling potential issues during interpreter shutdown or resource cleanup. + """ + try: + if self.window: + if glfw.get_current_context() == self.window: + glfw.make_context_current(None) + glfw.destroy_window(self.window) + self.window = None + except AttributeError: + # Handle cases where attributes are missing due to improper environment closure + warn( + "Environment was not properly closed using 'env.close()'. Please ensure to close the environment explicitly. " + "GLFW module or dependencies are unloaded. Window cleanup might not have completed." + ) def __del__(self): """Eliminate all of the OpenGL glfw contexts and windows"""