def _vispy_set_visible(self, visible): # Show or hide the window or widget glut.glutSetWindow(self._id) if visible: glut.glutShowWindow() else: glut.glutHideWindow()
def __init__(self, *args, **kwargs): BaseCanvasBackend.__init__(self) title, size, show, position = self._process_backend_kwargs(kwargs) glut.glutInitWindowSize(size[0], size[1]) self._id = glut.glutCreateWindow(title.encode('ASCII')) if not self._id: raise RuntimeError('could not create window') glut.glutSetWindow(self._id) _VP_GLUT_ALL_WINDOWS.append(self) # Cache of modifiers so we can send modifiers along with mouse motion self._modifiers_cache = () self._closed = False # Keep track whether the widget is closed # Register callbacks glut.glutDisplayFunc(self.on_draw) glut.glutReshapeFunc(self.on_resize) # glut.glutVisibilityFunc(self.on_show) glut.glutKeyboardFunc(self.on_key_press) glut.glutSpecialFunc(self.on_key_press) glut.glutKeyboardUpFunc(self.on_key_release) glut.glutMouseFunc(self.on_mouse_action) glut.glutMotionFunc(self.on_mouse_motion) glut.glutPassiveMotionFunc(self.on_mouse_motion) _set_close_fun(self._id, self.on_close) self._vispy_canvas_ = None if position is not None: self._vispy_set_position(*position) if not show: glut.glutHideWindow()
def hide(self): ''' The hide() method reverses the effects of the show() method, causing the window to be hidden (removed from the display). ''' glut.glutSetWindow( self._id ) glut.glutHideWindow() self.dispatch_event('on_hide')
def __init__( self, width=256, height=256, title=None, visible=True, aspect=None, decoration=True, fullscreen=False, config=None, context=None, color=(0,0,0,1), vsync=False): if vsync: log.warn('vsync not implemented for osxglut backend') if len(__windows__) > 0: log.critical( """OSXGLUT backend is unstable with more than one window.\n""" """Exiting...""") sys.exit(0) window.Window.__init__(self, width=width, height=height, title=title, visible=visible, aspect=aspect, decoration=decoration, fullscreen=fullscreen, config=config, context=context, color=color) if config is None: config = configuration.Configuration() set_configuration(config) self._native_window = glut.glutCreateWindow( self._title ) if bool(glut.glutSetOption): glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE, glut.GLUT_ACTION_CONTINUE_EXECUTION) glut.glutSetOption(glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS, glut.GLUT_ACTION_CONTINUE_EXECUTION) glut.glutWMCloseFunc( self._close ) glut.glutDisplayFunc( self._display ) glut.glutReshapeFunc( self._reshape ) glut.glutKeyboardFunc( self._keyboard ) glut.glutKeyboardUpFunc( self._keyboard_up ) glut.glutMouseFunc( self._mouse ) glut.glutMotionFunc( self._motion ) glut.glutPassiveMotionFunc( self._passive_motion ) glut.glutVisibilityFunc( self._visibility ) glut.glutEntryFunc( self._entry ) glut.glutSpecialFunc( self._special ) glut.glutSpecialUpFunc( self._special_up ) glut.glutReshapeWindow( self._width, self._height ) if visible: glut.glutShowWindow() else: glut.glutHideWindow() # This ensures glutCheckLoop never blocks def on_idle(): pass glut.glutIdleFunc(on_idle) __windows__.append(self)
def _close(self): __windows__.remove(self) # WARNING: This does not work on OSX 10.9 (seg fault or bus error) # glut.glutDestroyWindow(self._native_window) glut.glutSetWindow(self._native_window) glut.glutHideWindow() for i in range(len(self._timer_stack)): handler, interval = self._timer_stack[i] self._clock.unschedule(handler) self.dispatch_event('on_close')
def _close(self): __windows__.remove(self) # WARNING: This does not work on OSX 10.9 (seg fault or bus error) # glut.glutDestroyWindow(self._native_window) glut.glutSetWindow(self._native_window) glut.glutHideWindow() for i in range(len(self._timer_stack)): handler, interval = self._timer_stack[i] self._clock.unschedule(handler) self.dispatch_event("on_close")
def __init__(self, width=256, height=256, title=None, visible=True, decoration=True, fullscreen=False, config=None, context=None): if len(__windows__) > 0: log.critical( """OSXGLUT backend is unstable with more than one window.\n""" """Exiting...""") sys.exit(0) window.Window.__init__(self, width, height, title, visible, decoration, fullscreen, config, context) if config is None: config = configuration.Configuration() set_configuration(config) self._native_window = glut.glutCreateWindow(self._title) if bool(glut.glutSetOption): glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE, glut.GLUT_ACTION_CONTINUE_EXECUTION) glut.glutSetOption(glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS, glut.GLUT_ACTION_CONTINUE_EXECUTION) glut.glutWMCloseFunc(self._close) glut.glutDisplayFunc(self._display) glut.glutReshapeFunc(self._reshape) glut.glutKeyboardFunc(self._keyboard) glut.glutKeyboardUpFunc(self._keyboard_up) glut.glutMouseFunc(self._mouse) glut.glutMotionFunc(self._motion) glut.glutPassiveMotionFunc(self._passive_motion) glut.glutVisibilityFunc(self._visibility) glut.glutEntryFunc(self._entry) glut.glutSpecialFunc(self._special) glut.glutSpecialUpFunc(self._special_up) glut.glutReshapeWindow(self._width, self._height) if visible: glut.glutShowWindow() else: glut.glutHideWindow() # This ensures glutCheckLoop never blocks def on_idle(): pass glut.glutIdleFunc(on_idle) __windows__.append(self)
def enable(self, app=None): """DEPRECATED since IPython 5.0 Enable event loop integration with GLUT. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to integrate with terminal based applications like IPython. Due to GLUT limitations, it is currently not possible to start the event loop without first creating a window. You should thus not create another window but use instead the created one. See 'gui-glut.py' in the docs/examples/lib directory. The default screen mode is set to: glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH """ warn( "This function is deprecated since IPython 5.0 and will be removed in future versions.", DeprecationWarning, stacklevel=2) import OpenGL.GLUT as glut from IPython.lib.inputhookglut import glut_display_mode, \ glut_close, glut_display, \ glut_idle, inputhook_glut if GUI_GLUT not in self.manager.apps: glut.glutInit(sys.argv) glut.glutInitDisplayMode(glut_display_mode) # This is specific to freeglut if bool(glut.glutSetOption): glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE, glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS) glut.glutCreateWindow(sys.argv[0]) glut.glutReshapeWindow(1, 1) glut.glutHideWindow() glut.glutWMCloseFunc(glut_close) glut.glutDisplayFunc(glut_display) glut.glutIdleFunc(glut_idle) else: glut.glutWMCloseFunc(glut_close) glut.glutDisplayFunc(glut_display) glut.glutIdleFunc(glut_idle) self.manager.set_inputhook(inputhook_glut)
def __init__(self, *args, **kwargs): BaseCanvasBackend.__init__(self, *args) title, size, position, show, vsync, resize, dec, fs, parent, context, \ = self._process_backend_kwargs(kwargs) self._initialized = False # Deal with context if not context.istaken: context.take('glut', self) _set_config(context.config) else: raise RuntimeError('Glut cannot share contexts.') glut.glutInitWindowSize(size[0], size[1]) self._id = glut.glutCreateWindow(title.encode('ASCII')) if not self._id: raise RuntimeError('could not create window') glut.glutSetWindow(self._id) _VP_GLUT_ALL_WINDOWS.append(self) if fs is not False: self._fullscreen = True self._old_size = size if fs is not True: logger.warning('Cannot specify monitor for glut fullscreen, ' 'using default') glut.glutFullScreen() else: self._fullscreen = False # Cache of modifiers so we can send modifiers along with mouse motion self._modifiers_cache = () self._closed = False # Keep track whether the widget is closed # Register callbacks glut.glutDisplayFunc(self.on_draw) glut.glutReshapeFunc(self.on_resize) # glut.glutVisibilityFunc(self.on_show) glut.glutKeyboardFunc(self.on_key_press) glut.glutSpecialFunc(self.on_key_press) glut.glutKeyboardUpFunc(self.on_key_release) glut.glutMouseFunc(self.on_mouse_action) glut.glutMotionFunc(self.on_mouse_motion) glut.glutPassiveMotionFunc(self.on_mouse_motion) _set_close_fun(self._id, self.on_close) if position is not None: self._vispy_set_position(*position) if not show: glut.glutHideWindow() # Init self._initialized = True self._vispy_set_current() self._vispy_canvas.events.initialize()
def enable(self, app=None): """DEPRECATED since IPython 5.0 Enable event loop integration with GLUT. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to integrate with terminal based applications like IPython. Due to GLUT limitations, it is currently not possible to start the event loop without first creating a window. You should thus not create another window but use instead the created one. See 'gui-glut.py' in the docs/examples/lib directory. The default screen mode is set to: glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH """ warn( "This function is deprecated since IPython 5.0 and will be removed in future versions.", DeprecationWarning, stacklevel=2, ) import OpenGL.GLUT as glut from IPython.lib.inputhookglut import glut_display_mode, glut_close, glut_display, glut_idle, inputhook_glut if GUI_GLUT not in self.manager.apps: glut.glutInit(sys.argv) glut.glutInitDisplayMode(glut_display_mode) # This is specific to freeglut if bool(glut.glutSetOption): glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE, glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS) glut.glutCreateWindow(sys.argv[0]) glut.glutReshapeWindow(1, 1) glut.glutHideWindow() glut.glutWMCloseFunc(glut_close) glut.glutDisplayFunc(glut_display) glut.glutIdleFunc(glut_idle) else: glut.glutWMCloseFunc(glut_close) glut.glutDisplayFunc(glut_display) glut.glutIdleFunc(glut_idle) self.manager.set_inputhook(inputhook_glut)
def disable(self): """Disable event loop integration with glut. This sets PyOS_InputHook to NULL and set the display function to a dummy one and set the timer to a dummy timer that will be triggered very far in the future. """ import OpenGL.GLUT as glut from glut_support import glutMainLoopEvent glut.glutHideWindow() # This is an event to be processed below glutMainLoopEvent() super(GlutInputHook, self).disable()
def enable_glut(self, app=None): """ Enable event loop integration with GLUT. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to integrate with terminal based applications like IPython. Due to GLUT limitations, it is currently not possible to start the event loop without first creating a window. You should thus not create another window but use instead the created one. See 'gui-glut.py' in the docs/examples/lib directory. The default screen mode is set to: glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH """ import OpenGL.GLUT as glut # @UnresolvedImport from pydev_ipython.inputhookglut import glut_display_mode, \ glut_close, glut_display, \ glut_idle, inputhook_glut if GUI_GLUT not in self._apps: argv = getattr(sys, 'argv', []) glut.glutInit(argv) glut.glutInitDisplayMode(glut_display_mode) # This is specific to freeglut if bool(glut.glutSetOption): glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE, glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS) glut.glutCreateWindow(argv[0] if len(argv) > 0 else '') glut.glutReshapeWindow(1, 1) glut.glutHideWindow() glut.glutWMCloseFunc(glut_close) glut.glutDisplayFunc(glut_display) glut.glutIdleFunc(glut_idle) else: glut.glutWMCloseFunc(glut_close) glut.glutDisplayFunc(glut_display) glut.glutIdleFunc(glut_idle) self.set_inputhook(inputhook_glut) self._current_gui = GUI_GLUT self._apps[GUI_GLUT] = True
def __init__(self, width=None, height=None, caption=None, visible=True, fullscreen=False): event.EventDispatcher.__init__(self) self._event_queue = [] if width and width > 0: self._width = width else: self._width = Window._default_width if height and height > 0: self._height = height else: self._height = Window._default_height if caption is None: caption = sys.argv[0] self._caption = caption self._saved_width = self._width self._saved_height = self._height if _window is None: glut.glutInit(sys.argv) glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH) self._window_id = glut.glutCreateWindow(self._caption) glut.glutDisplayFunc(self._display) glut.glutReshapeFunc(self._reshape) glut.glutKeyboardFunc(self._keyboard) glut.glutKeyboardUpFunc(self._keyboard_up) glut.glutMouseFunc(self._mouse) glut.glutMotionFunc(self._motion) glut.glutPassiveMotionFunc(self._passive_motion) glut.glutVisibilityFunc(self._visibility) glut.glutEntryFunc(self._entry) glut.glutSpecialFunc(self._special) glut.glutSpecialUpFunc(self._special_up) gl.glClearColor(0,0,0,0) self._visible = visible self._time = glut.glutGet(glut.GLUT_ELAPSED_TIME) if not visible: glut.glutHideWindow() else: glut.glutShowWindow() self.set_size(self._width, self._height) screen_width = glut.glutGet(glut.GLUT_SCREEN_WIDTH) screen_height= glut.glutGet(glut.GLUT_SCREEN_HEIGHT) glut.glutPositionWindow((screen_width-self._width)//2, (screen_height-self._height)//2) self.fullscreen = fullscreen
def disable(self): """DEPRECATED since IPython 5.0 Disable event loop integration with glut. This sets PyOS_InputHook to NULL and set the display function to a dummy one and set the timer to a dummy timer that will be triggered very far in the future. """ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.", DeprecationWarning, stacklevel=2) import OpenGL.GLUT as glut from glut_support import glutMainLoopEvent glut.glutHideWindow() # This is an event to be processed below glutMainLoopEvent() super(GlutInputHook, self).disable()
def run(self, _width=None, _height=None, _show_window=True): # Init glut self._show_window = _show_window GLUT.glutInit(()) GLUT.glutInitDisplayMode(GLUT.GLUT_RGBA | GLUT.GLUT_DOUBLE | GLUT.GLUT_ALPHA | GLUT.GLUT_DEPTH) if _width is not None and _height is not None: GLUT.glutInitWindowSize(_width, _height) #self.resizeGL(_width, _height) # this line crashes my program ?? else: GLUT.glutInitWindowSize(*self.window_size) GLUT.glutInitWindowPosition(0, 0) self.window = GLUT.glutCreateWindow(self.title) if not _show_window: GLUT.glutHideWindow() GLUT.glutDisplayFunc(self.drawGL) GLUT.glutReshapeFunc(self.resizeGL) GLUT.glutKeyboardFunc(self.mykeyboard) GLUT.glutMouseFunc(self.mouseFunc) GLUT.glutMotionFunc(self.motionFunc) self.initGL(*self.window_size)
def init_window(): global ASPECT_RATIO, WIN_ID disp_w = glut.glutGet(glut.GLUT_SCREEN_WIDTH) disp_h = glut.glutGet(glut.GLUT_SCREEN_HEIGHT) # Fixes an issue on where the display width/height of a multi-monitor # setup is calculated as a total of the width/height of all display # monitors. # Without the below, the result is a window with an ASPECT_RATIO ratio # stretched across multiple monitors. if int(disp_w * ASPECT_RATIO**(-1)) > disp_h: disp_w = int(disp_h * ASPECT_RATIO) elif int(disp_h * ASPECT_RATIO) > disp_w: disp_h = int(disp_w * ASPECT_RATIO**(-1)) # Set the window position & size, and create the window. percent = 0.75 width = int(disp_w * percent) height = int(disp_h * percent) win_x = width - int(width * 0.85) win_y = height - int(height * 0.85) glut.glutInitWindowSize(width, height) glut.glutInitWindowPosition(win_x, win_y) WIN_ID = glut.glutCreateWindow('Glovelet 3D Demo') glut.glutHideWindow()
def __init__(self, **kwargs): BaseCanvasBackend.__init__(self, capability, SharedContext) title, size, position, show, vsync, resize, dec, fs, context = \ self._process_backend_kwargs(kwargs) _set_config(context) glut.glutInitWindowSize(size[0], size[1]) self._id = glut.glutCreateWindow(title.encode('ASCII')) if not self._id: raise RuntimeError('could not create window') glut.glutSetWindow(self._id) _VP_GLUT_ALL_WINDOWS.append(self) if fs is not False: if isinstance(fs, int): logger.warn('Cannot specify monitor for glut fullscreen, ' 'using default') glut.glutFullScreen() # Cache of modifiers so we can send modifiers along with mouse motion self._modifiers_cache = () self._closed = False # Keep track whether the widget is closed # Register callbacks glut.glutDisplayFunc(self.on_draw) glut.glutReshapeFunc(self.on_resize) # glut.glutVisibilityFunc(self.on_show) glut.glutKeyboardFunc(self.on_key_press) glut.glutSpecialFunc(self.on_key_press) glut.glutKeyboardUpFunc(self.on_key_release) glut.glutMouseFunc(self.on_mouse_action) glut.glutMotionFunc(self.on_mouse_motion) glut.glutPassiveMotionFunc(self.on_mouse_motion) _set_close_fun(self._id, self.on_close) self._vispy_canvas_ = None if position is not None: self._vispy_set_position(*position) if not show: glut.glutHideWindow()
def glut_close(): # Close function only hides the current window glut.glutHideWindow() glutMainLoopEvent()
def __init__(self, param): # set the parameters if 'width' in param.keys(): self.width = param["width"] else: self.width = 640 if 'height' in param.keys(): self.height = param["height"] else: self.height = 480 if 'resource_path' in param.keys(): self.resource_path = param['resource_path'] else: self.resource_path = 'resources/' if 'ground_w' in param.keys(): self.ground_size_w = param['ground_w'] else: self.ground_size_w = 0.55 if 'ground_d' in param.keys(): self.ground_size_d = param['ground_d'] else: self.ground_size_d = 0.5 if 'camera_pos' in param.keys(): # make sure that the camera pose is ok if np.linalg.norm(np.array(param['camera_pos'])) > 1.: log.error('Invalid Camera pose: The norm of the camera ' + 'position should not exceed 1!') log.warning('Setting camera position to ' + str([0., 0., 0.6])) self.cam_pos = [0., 0., 0.6] elif param['camera_pos'][2] < 0.1: log.error('Invalid Camera pose: The z coordinate needs ' + 'to be between 0.1 and 1.') log.warning('Setting camera position to ' + str([0., 0., 0.6])) self.cam_pos = [0., 0., 0.6] self.cam_pos = param['camera_pos'] else: self.cam_pos = [0., 0., 0.6] if 'shadows' in param.keys(): self.shadows = param['shadows'] else: self.shadows =True # init a glut window as context glut.glutInit(sys.argv) glut.glutInitWindowSize(self.width, self.height) # Select type of Display mode: glut.glutInitDisplayMode(glut.GLUT_RGBA | glut.GLUT_DOUBLE | glut.GLUT_DEPTH | glut.GLUT_STENCIL) self.window = glut.glutCreateWindow("") # hide the glut window glut.glutHideWindow() # scan for available resources resources = [os.path.join(self.resource_path, f) for f in os.listdir(self.resource_path)] if 'texture_files' in param.keys(): self.texture_files = param['texture_files'] self.texture_files = \ filter(lambda f: os.path.basename(f), resources) else: # if no textures are specified, load everything self.texture_files = \ filter(lambda f: f.endswith('jpg') or f.endswith('jpeg') or f.endswith('png') or f.endswith('bmp'), resources) self.material_files = filter(lambda f: f.endswith('mtl'), resources) if 'object_files' in param.keys(): self.object_files = param['object_files'] for f in self.object_files: if not os.path.exists(f): raise ValueError("Object file not found: " + f) sys.exit() else: # if no files are specified, load all self.object_files = filter(lambda f: f.endswith('obj'), resources) self.texture_keys = dict() self.object_keys = dict() self.materials = dict() self.objects = [] # load required textures for tex in self.texture_files: ind = self._load_texture(tex) name = os.path.basename(tex)[:os.path.basename(tex).find('.')] # register the texture twice, with and without file ending self.texture_keys[os.path.basename(tex)] = ind self.texture_keys[name] = ind # load required materials for mat in self.material_files: material = self._load_material(mat) name = os.path.basename(mat)[:os.path.basename(mat).find('.')] self.materials[name] = material self.materials[os.path.basename(mat)] = material # load object(s) for obj in self.object_files: ob = MeshObject(obj, self.texture_keys, self.materials) ind = len(self.objects) self.objects.append(ob) name = os.path.basename(obj)[:os.path.basename(obj).find('.')] self.object_keys[name] = ind # initialize the framebuffers that we will render to self._init_render() self._init_shadow() # some configuration self.z_far = max(1.1, np.linalg.norm(np.array(self.cam_pos)) + 1.) self.z_near = 0.05 gl.glEnable(gl.GL_DEPTH_TEST) gl.glDepthFunc(gl.GL_LEQUAL) gl.glClearColor(0.1, 0.2, 0.3, 1.0) # initialize the shaders if self.shadows: self.scene_shader = Shader(SCENE_VS_SHADER, SCENE_F_SHADER) else: self.scene_shader = Shader(SCENE_VS_SHADER, SCENE_F_SHADER_SIMPLE) self.shadow_depth_shader = Shader(SHADOW_VS_SHADER, SHADOW_F_SHADER) # shader configuration self.scene_shader.use() self._set_light() self.scene_shader.set_value("shadowMap", 1) self.scene_shader.set_value("diffuseTexture", 0)
def hide(self): self.activate() glut.glutHideWindow() self.dispatch_event("on_hide")
def __init__(self, param): # set the parameters if 'width' in param.keys(): self.width = param["width"] else: self.width = 640 if 'height' in param.keys(): self.height = param["height"] else: self.height = 480 if 'resource_path' in param.keys(): self.resource_path = param['resource_path'] else: self.resource_path = '../../resources/' if 'ground_w' in param.keys(): self.ground_size_w = param['ground_w'] else: self.ground_size_w = 0.55 if 'ground_d' in param.keys(): self.ground_size_d = param['ground_d'] else: self.ground_size_d = 0.5 if 'camera_pos' in param.keys(): # make sure that the camera pose is ok if np.linalg.norm(np.array(param['camera_pos'])) > 1.: log.error('Invalid Camera pose: The norm of the camera ' + 'position should not exceed 1!') log.warning('Setting camera position to ' + str([0., 0., 0.6])) self.cam_pos = [0., 0., 0.6] elif param['camera_pos'][2] < 0.1: log.error('Invalid Camera pose: The z coordinate needs ' + 'to be between 0.1 and 1.') log.warning('Setting camera position to ' + str([0., 0., 0.6])) self.cam_pos = [0., 0., 0.6] self.cam_pos = param['camera_pos'] else: self.cam_pos = [0., 0., 0.6] if 'shadows' in param.keys(): self.shadows = param['shadows'] else: self.shadows =True # init a glut window as context glut.glutInit(sys.argv) glut.glutInitWindowSize(self.width, self.height) # Select type of Display mode: glut.glutInitDisplayMode(glut.GLUT_RGBA | glut.GLUT_DOUBLE | glut.GLUT_DEPTH | glut.GLUT_STENCIL) self.window = glut.glutCreateWindow("") # hide the glut window glut.glutHideWindow() # scan for available resources resources = [os.path.join(self.resource_path, f) for f in os.listdir(self.resource_path)] if 'texture_files' in param.keys(): self.texture_files = param['texture_files'] self.texture_files = \ filter(lambda f: os.path.basename(f), resources) else: # if no textures are specified, load everything self.texture_files = \ filter(lambda f: f.endswith('jpg') or f.endswith('jpeg') or f.endswith('png') or f.endswith('bmp'), resources) self.material_files = filter(lambda f: f.endswith('mtl'), resources) if 'object_files' in param.keys(): self.object_files = param['object_files'] for f in self.object_files: if not os.path.exists(f): raise ValueError("Object file not found: " + f) sys.exit() else: # if no files are specified, load all self.object_files = filter(lambda f: f.endswith('obj'), resources) self.texture_keys = dict() self.object_keys = dict() self.materials = dict() self.objects = [] # load required textures for tex in self.texture_files: ind = self._load_texture(tex) name = os.path.basename(tex)[:os.path.basename(tex).find('.')] # register the texture twice, with and without file ending self.texture_keys[os.path.basename(tex)] = ind self.texture_keys[name] = ind # load required materials for mat in self.material_files: material = self._load_material(mat) name = os.path.basename(mat)[:os.path.basename(mat).find('.')] self.materials[name] = material self.materials[os.path.basename(mat)] = material # load object(s) for obj in self.object_files: ob = MeshObject(obj, self.texture_keys, self.materials) ind = len(self.objects) self.objects.append(ob) name = os.path.basename(obj)[:os.path.basename(obj).find('.')] self.object_keys[name] = ind # initialize the framebuffers that we will render to self._init_render() self._init_shadow() # some configuration self.z_far = max(1.1, np.linalg.norm(np.array(self.cam_pos)) + 1.) self.z_near = 0.05 gl.glEnable(gl.GL_DEPTH_TEST) gl.glDepthFunc(gl.GL_LEQUAL) gl.glClearColor(0.1, 0.2, 0.3, 1.0) # initialize the shaders if self.shadows: self.scene_shader = Shader(SCENE_VS_SHADER, SCENE_F_SHADER) else: self.scene_shader = Shader(SCENE_VS_SHADER, SCENE_F_SHADER_SIMPLE) self.shadow_depth_shader = Shader(SHADOW_VS_SHADER, SHADOW_F_SHADER) # shader configuration self.scene_shader.use() self._set_light() self.scene_shader.set_value("shadowMap", 1) self.scene_shader.set_value("diffuseTexture", 0)
def glut_int_handler(signum, frame): # Catch sigint and print the defaultipyt message signal.signal(signal.SIGINT, signal.default_int_handler) print('\nKeyboardInterrupt') # Need to reprint the prompt at this stage # Initialisation code glut.glutInit( sys.argv ) glut.glutInitDisplayMode( glut_display_mode ) # This is specific to freeglut if bool(glut.glutSetOption): glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE, glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS ) glut.glutCreateWindow( b'ipython' ) glut.glutReshapeWindow( 1, 1 ) glut.glutHideWindow( ) glut.glutWMCloseFunc( glut_close ) glut.glutDisplayFunc( glut_display ) glut.glutIdleFunc( glut_idle ) def inputhook(context): """Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass.
def keyboard(self, key, x, y): global ALPHA global COLORMAP global CONTRAST global FULLSCREEN global POINT_SIZE global RECORDSCREEN global TRACEORBITS global ZOOM_FACTOR (ps_min, ps_max) = gl.glGetFloatv(gl.GL_ALIASED_POINT_SIZE_RANGE) if key == ' ': self.rotate['x'] = 0 self.rotate['y'] = 0 self.rotate['z'] = 0 elif key == '+': POINT_SIZE += 1 if POINT_SIZE > ps_max: POINT_SIZE = ps_max elif key == '-': POINT_SIZE -= 1 if POINT_SIZE < ps_min: POINT_SIZE = ps_min elif key == '<': self.rotate['z'] -= 1 elif key == '>': self.rotate['z'] += 1 elif key in '0123456789': COLORMAP = int(key) elif key == 'a': ALPHA /= 1.03125 if ALPHA < 0.0: ALPHA = 0.0 elif key == 'A': ALPHA *= 1.03125 if ALPHA > 1.0: ALPHA = 1.0 elif key == 'c': CONTRAST *= 1.015625 if CONTRAST > 256.0: CONTRAST = 256.0 elif key == 'C': CONTRAST /= 1.015625 if CONTRAST < 0.0625: CONTRAST = 0.0625 elif key == 'r': if not COLORMASK['r']: COLORMASK['r'] = True COLORMASK['g'] = False COLORMASK['b'] = False else: COLORMASK['r'] = False elif key == 'g': if not COLORMASK['g']: COLORMASK['r'] = False COLORMASK['g'] = True COLORMASK['b'] = False else: COLORMASK['g'] = False elif key == 'b': if not COLORMASK['b']: COLORMASK['r'] = False COLORMASK['g'] = False COLORMASK['b'] = True else: COLORMASK['b'] = False elif key == 'Z': ZOOM_FACTOR *= 1.03125 elif key == 'z': ZOOM_FACTOR /= 1.03125 elif key == 'o' or key == 'O': if not TRACEORBITS: TRACEORBITS = True else: TRACEORBITS = False elif key == 'f' or key == 'F': if not FULLSCREEN: glut.glutFullScreen() FULLSCREEN = True else: glut.glutReshapeWindow(WINDOW_WIDTH, WINDOW_HEIGHT) FULLSCREEN = False elif key == 's' or key == 'S': if not RECORDSCREEN: RECORDSCREEN = True else: RECORDSCREEN = False elif key == ESCAPE: self.exitgl = True glut.glutLeaveMainLoop() glut.glutHideWindow() glut.glutSetWindow(self.window_handle) glut.glutPostRedisplay()
def keyboard(self, key, x, y): global ALPHA global COLORMAP global CONTRAST global FULLSCREEN global POINT_SIZE global RECORDSCREEN global TRACEORBITS global ZOOM_FACTOR (ps_min, ps_max) = gl.glGetFloatv(gl.GL_ALIASED_POINT_SIZE_RANGE) if key == " ": self.rotate["x"] = 0 self.rotate["y"] = 0 self.rotate["z"] = 0 elif key == "+": POINT_SIZE += 1 if POINT_SIZE > ps_max: POINT_SIZE = ps_max elif key == "-": POINT_SIZE -= 1 if POINT_SIZE < ps_min: POINT_SIZE = ps_min elif key == "<": self.rotate["z"] -= 1 elif key == ">": self.rotate["z"] += 1 elif key in "0123456789": COLORMAP = int(key) elif key == "a": ALPHA /= 1.03125 if ALPHA < 0.0: ALPHA = 0.0 elif key == "A": ALPHA *= 1.03125 if ALPHA > 1.0: ALPHA = 1.0 elif key == "c": CONTRAST *= 1.015625 if CONTRAST > 256.0: CONTRAST = 256.0 elif key == "C": CONTRAST /= 1.015625 if CONTRAST < 0.0625: CONTRAST = 0.0625 elif key == "r": if not COLORMASK["r"]: COLORMASK["r"] = True COLORMASK["g"] = False COLORMASK["b"] = False else: COLORMASK["r"] = False elif key == "g": if not COLORMASK["g"]: COLORMASK["r"] = False COLORMASK["g"] = True COLORMASK["b"] = False else: COLORMASK["g"] = False elif key == "b": if not COLORMASK["b"]: COLORMASK["r"] = False COLORMASK["g"] = False COLORMASK["b"] = True else: COLORMASK["b"] = False elif key == "Z": ZOOM_FACTOR *= 1.03125 elif key == "z": ZOOM_FACTOR /= 1.03125 elif key == "o" or key == "O": if not TRACEORBITS: TRACEORBITS = True else: TRACEORBITS = False elif key == "f" or key == "F": if not FULLSCREEN: glut.glutFullScreen() FULLSCREEN = True else: glut.glutReshapeWindow(WINDOW_WIDTH, WINDOW_HEIGHT) FULLSCREEN = False elif key == "s" or key == "S": if not RECORDSCREEN: RECORDSCREEN = True else: RECORDSCREEN = False elif key == ESCAPE: self.exitgl = True glut.glutLeaveMainLoop() glut.glutHideWindow() glut.glutSetWindow(self.window_handle) glut.glutPostRedisplay()
def hide(self): self.activate() glut.glutHideWindow() self.dispatch_event('on_hide')
def startGL(): if GLUT.glutInit() == (): return # once only GLUT.glutInitDisplayMode(GLUT.GLUT_RGBA | GLUT.GLUT_DEPTH) GLUT.glutInitWindowSize(1, 1) GLUT.glutCreateWindow('offscreen rendering context window') GLUT.glutHideWindow()