def glfw_initialization(glsl_version=None, window_size=None, title=None): """Initializes GLFW, OpenGL Context and creates a Window""" major, minor = glsl_version or (3, 3) width, height = window_size or (1280, 720) title = title or 'ModernGL Test Window' if not glfw.init(): raise RuntimeError('GLFW could not be initialized.') glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, major) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, minor) profile = glfw.OPENGL_CORE_PROFILE if (major, minor) > ( 3, 2) else glfw.GLFW_OPENGL_ANY_PROFILE compat = True if (major, minor) >= (3, 0) else False glfw.window_hint(glfw.OPENGL_PROFILE, profile) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, compat) glfw.window_hint(glfw.VISIBLE, True) win = glfw.create_window(width, height, title, None, None) if not win: glfw.terminate() raise RuntimeError('GLFW could not create window.') glfw.make_context_current(win) glfw.swap_interval(1) glfw.set_error_callback(error_callback) glfw.set_key_callback(win, key_callback) return win
def main(): # Initialize the library if not glfw.init(): return glfw.set_error_callback(error_callback) # 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) program = common2d.init_shader_program() # Loop until the user closes the window while not glfw.window_should_close(window): # Render here common2d.display(program) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def main(self): glfw.set_error_callback(error_callback) if not glfw.init(): raise RuntimeError('glfw.init()') glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.RESIZABLE, False) self.window = glfw.create_window(self.screen_x, self.screen_y, self.title, None, None) if not self.window: raise RuntimeError('glfw.CreateWindow())') glfw.make_context_current(self.window) glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED) glfw.set_cursor_pos(self.window, 0, 0) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) glClearColor(0, 0, 0, 1) # print(b'OpenGL version: ' + glGetString(GL_VERSION)) # print(b'GLSL version: ' + glGetString(GL_SHADING_LANGUAGE_VERSION)) # print(b'Vendor: ' + glGetString(GL_VENDOR)) # print(b'Renderer: ' + glGetString(GL_RENDERER)) self.init() old_time = glfw.get_time() try: while not glfw.window_should_close(self.window): glfw.poll_events() if any(( ( glfw.get_key(self.window, glfw.KEY_LEFT_ALT) and \ glfw.get_key(self.window, glfw.KEY_F4) ), ( glfw.get_key(self.window, glfw.KEY_LEFT_CONTROL) and \ glfw.get_key(self.window, glfw.KEY_Q) ) )): glfw.set_window_should_close(self.window, True) now = glfw.get_time() self.update(float(now - old_time)) old_time = now self.render() glfw.swap_buffers(self.window) except KeyboardInterrupt: pass glfw.terminate()
def init(self): if self.initialized: return if not glfw.init(): print('GLFW initialization failed') sys.exit(-1) glfw.set_error_callback(lambda error, description: self.error_callback(error, description)) self.initialized = True
def glfwInit(self, button_callback=None, mouse_down_callback=None, mouse_move_callback=None): glfw.set_error_callback(error_callback) if not glfw.init(): print("glfw Error: init glfw failed!") return False glfw.window_hint(glfw.RESIZABLE, GL_FALSE) glfw.window_hint(glfw.SAMPLES, 1) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) if self.is_visible: glfw.window_hint(glfw.VISIBLE, GL_TRUE) else: glfw.window_hint(glfw.VISIBLE, GL_FALSE) self.window = glfw.create_window(self.wndWidth, self.wndHeight, self.title, None, None) if not self.window: print("glfw Error: create window failed!") glfw.terminate() return False glfw.make_context_current(self.window) glfw.swap_interval(0) glfw.set_input_mode(self.window, glfw.STICKY_KEYS, GL_TRUE) if button_callback is not None and hasattr(button_callback, "__call__"): glfw.set_key_callback(self.window, button_callback) if mouse_down_callback is not None and hasattr(mouse_down_callback, "__call__"): glfw.set_mouse_button_callback(self.window, mouse_down_callback) if mouse_move_callback is not None and hasattr(mouse_move_callback, "__call__"): glfw.set_cursor_pos_callback(self.window, mouse_move_callback) # Enable the Depth test glEnable(GL_DEPTH_TEST) glDisable(GL_MULTISAMPLE) glEnable(GL_PROGRAM_POINT_SIZE) glDepthFunc(GL_LESS) # glEnable(GL_LINE_SMOOTH) return True
def init(): global window, imgui_renderer, _ui_state glfw.set_error_callback(error_callback) imgui.create_context() if not glfw.init(): print("GLFW Initialization fail!") return graphics_settings = configuration.get_graphics_settings() loader_settings = configuration.get_loader_settings() if graphics_settings is None: print("bla") return screen_utils.WIDTH = graphics_settings.getint("width") screen_utils.HEIGHT = graphics_settings.getint("height") screen_utils.MAX_FPS = graphics_settings.getint("max_fps") screen = None if graphics_settings.getboolean("full_screen"): screen = glfw.get_primary_monitor() hints = { glfw.DECORATED: glfw.TRUE, glfw.RESIZABLE: glfw.FALSE, glfw.CONTEXT_VERSION_MAJOR: 4, glfw.CONTEXT_VERSION_MINOR: 5, glfw.OPENGL_DEBUG_CONTEXT: glfw.TRUE, glfw.OPENGL_PROFILE: glfw.OPENGL_CORE_PROFILE, glfw.SAMPLES: 4, } window = _create_window(size=(screen_utils.WIDTH, screen_utils.HEIGHT), pos="centered", title="Tremor", monitor=screen, hints=hints, screen_size=glfw.get_monitor_physical_size( glfw.get_primary_monitor())) imgui_renderer = GlfwRenderer(window, attach_callbacks=False) glutil.log_capabilities() glEnable(GL_CULL_FACE) glCullFace(GL_BACK) glEnable(GL_DEPTH_TEST) glDepthMask(GL_TRUE) glDepthFunc(GL_LEQUAL) glDepthRange(0.0, 1.0) glEnable(GL_MULTISAMPLE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) create_branched_programs() # create the uniforms _create_uniforms() # initialize all the uniforms for all the prpograms init_all_uniforms()
def _vispy_get_native_app(self): global _GLFW_INITIALIZED if not _GLFW_INITIALIZED: cwd = os.getcwd() glfw.set_error_callback(_error_callback) try: if not glfw.init(): # only ever call once raise OSError('Could not init glfw:\n%r' % _glfw_errors) finally: os.chdir(cwd) glfw.set_error_callback(None) atexit.register(glfw.terminate) _GLFW_INITIALIZED = True return glfw
window = glfw.create_window(width, height, "LearnOpenGL", None, None) if not window: print("Failed to create GLFW window") glfw.terminate() glfw.make_context_current(window) glfw.set_framebuffer_size_callback(window, inputMgr.get_framebuffer_size_callback()) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) glfw.set_cursor_pos_callback(window, inputMgr.get_mouse_callback()) glfw.set_scroll_callback(window, inputMgr.get_scroll_callback()) glfw.set_mouse_button_callback(window, inputMgr.get_mousebutton_callback()) glfw.set_error_callback(inputMgr.get_error_callback()) ## Load, compile, link shaders shaders = myshader.shader("shaders/basiclight-texture.vert", "shaders/texturedobj.frag") shaders.linkShaders() lightshader = myshader.shader("shaders/hellolightingcol.vert", "shaders/hellolight.frag") lightshader.linkShaders() # ## Textures t1 = mytexture.texture('resources/equirectangular.jpg', GL_TEXTURE0) t2 = mytexture.texture('resources/container2.png', GL_TEXTURE1) t3 = mytexture.texture('resources/container2_specular.png', GL_TEXTURE2)
def __init__(self, specification: WindowSpecs, startImgui: bool = False): start = time.perf_counter() self.isActive = True self.baseTitle = specification.title self.frameTime = 1.0 if not glfw.init(): raise GraphicsException("Cannot initialize GLFW.") glfw.set_error_callback(self.__GlfwErrorCb) ver = ".".join(str(x) for x in glfw.get_version()) Debug.Log(f"GLFW version: {ver}", LogLevel.Info) self.__SetDefaultWindowFlags(specification) if specification.fullscreen: self.__handle = self.__CreateWindowFullscreen(specification) Debug.Log("Window started in fulscreen mode.", LogLevel.Info) else: self.__handle = self.__CreateWindowNormal(specification) glfw.make_context_current(self.__handle) self.__GetScreenInfo(specification) # enginePreview.RenderPreview() # glfw.swap_buffers(self.__handle) glfw.set_input_mode( self.__handle, glfw.CURSOR, glfw.CURSOR_NORMAL if specification.cursorVisible else glfw.CURSOR_HIDDEN) glfw.set_framebuffer_size_callback(self.__handle, self.__ResizeCb) glfw.set_cursor_pos_callback(self.__handle, self.__CursorPosCb) glfw.set_window_iconify_callback(self.__handle, self.__IconifyCb) glfw.set_mouse_button_callback(self.__handle, self.__MouseCb) glfw.set_scroll_callback(self.__handle, self.__MouseScrollCb) glfw.set_key_callback(self.__handle, self.__KeyCb) glfw.set_window_pos_callback(self.__handle, self.__WindowPosCallback) glfw.set_window_focus_callback(self.__handle, self.__WindowFocusCallback) #set icon if specification.iconFilepath: if not os.path.endswith(".ico"): raise SpykeException( f"Invalid icon extension: {os.path.splitext(specification.iconFilepath)}." ) self.__LoadIcon(specification.iconFilepath) else: self.__LoadIcon(DEFAULT_ICON_FILEPATH) self.SetVsync(specification.vsync) self.positionX, self.positionY = glfw.get_window_pos(self.__handle) Renderer.Initialize(Renderer.screenStats.width, Renderer.screenStats.height, specification.samples) self.OnLoad() if startImgui: Imgui.Initialize() atexit.register(Imgui.Close) gc.collect() Debug.Log( f"GLFW window initialized in {time.perf_counter() - start} seconds.", LogLevel.Info)
glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) window = glfw.create_window(width, height, "LearnOpenGL", None, None) if not window: print("Failed to create GLFW window") glfw.terminate() glfw.make_context_current(window) glfw.set_framebuffer_size_callback(window, framebuffer_size_callback) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) glfw.set_cursor_pos_callback(window, mouse_callback) glfw.set_scroll_callback(window, scroll_callback) glfw.set_mouse_button_callback(window, mousebutton_callback) glfw.set_error_callback(error_callback) ## Load, compile, link shaders import myshader shaders = myshader.shader("shaders/hellocoord.vert", "shaders/hellocoord.frag") shaders.linkShaders() # ## Textures import mytexture t1 = mytexture.texture('resources/wall.jpg', GL_TEXTURE0) # t2 = mytexture.texture('awesomeface.png', GL_TEXTURE1) ## Scene import mycube import numpy as np
def init(): glfw.set_error_callback(error_callback) if not glfw.init(): exit(1)
def __init__(self, model_vertices: typing.List[float], model_uvmap: typing.List[float], texture_filename: str, window_title: str): """ @fn __init__() @brief Initialization of viewer. @param model_vertices The list of vertices in the model. @param model_uvmap the uvmapping which associate model_vertices with textures @param texture_filename The path to the texture file. @param window_title The title of the window. @note The format of model_vertices is [X1, Y1, Z1, X2, Y2, ...]. @note The format of model_uvmap is [U1, V1, U2, V2, ...]. """ print("Initializing Viewer...") # set callback function on error glfw.set_error_callback(Viewer.on_error) # Initialize if glfw.init() != gl.GL_TRUE: print("[GLFW Error] Failed to initialize GLFW. ") sys.exit() #======================================== # Prepare Window #======================================== print("- Creating a window.") # Window hints glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) # Create window self.window_size = (640, 480) self.window = glfw.create_window( self.window_size[0], # width self.window_size[1], # height window_title, # window title None, None) if self.window == None: print("[GLFW Error] Failed to Create a window. ") sys.exit() # Create OpenGL context glfw.make_context_current(self.window) # Set background color. gl.glClearColor(0.0, 1.0, 1.0, 1.0) #gl.glViewport(0, 0, 480, 480) # Set callback functions glfw.set_window_size_callback(self.window, self.window_size_callback) glfw.set_scroll_callback(self.window, self.mouse_scroll_callback) #======================================== # Prepare Buffers #======================================== print("- Preparing buffers.") # --- Vertex buffer --- # Generate & bind buffer vertex_buffer = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vertex_buffer) # Allocate memory c_vertex_buffer = (ctypes.c_float * len(model_vertices))(*model_vertices) gl.glBufferData(gl.GL_ARRAY_BUFFER, c_vertex_buffer, gl.GL_DYNAMIC_DRAW) size_expected = ctypes.sizeof(ctypes.c_float) * len(model_vertices) size_allocated = gl.glGetBufferParameteriv(gl.GL_ARRAY_BUFFER, gl.GL_BUFFER_SIZE) if size_allocated != size_expected: print("[GL Error] Failed to allocate memory for buffer. ") gl.glDeleteBuffers(1, vertex_buffer) sys.exit() # --- UV buffer --- # Generate & bind buffer uv_buffer = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, uv_buffer) # Allocate memory c_uv_buffer = (ctypes.c_float * len(model_uvmap))(*model_uvmap) gl.glBufferData(gl.GL_ARRAY_BUFFER, c_uv_buffer, gl.GL_DYNAMIC_DRAW) size_expected = ctypes.sizeof(ctypes.c_float) * len(model_uvmap) size_allocated = gl.glGetBufferParameteriv(gl.GL_ARRAY_BUFFER, gl.GL_BUFFER_SIZE) if size_allocated != size_expected: print("[GL Error] Failed to allocate memory for buffer. ") gl.glDeleteBuffers(1, uv_buffer) sys.exit() # --- Bind to vertex array object --- self.va_object = gl.glGenVertexArrays(1) gl.glBindVertexArray(self.va_object) gl.glEnableVertexAttribArray(0) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vertex_buffer) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, None) gl.glEnableVertexAttribArray(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, uv_buffer) gl.glVertexAttribPointer(1, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, None) gl.glBindVertexArray(0) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0) #======================================== # Prepare Texture #======================================== print("- Preparing textures.") # Load image image = cv2.imread(texture_filename) if image is None: print(f"[CV Error] Cannot open image: {texture_filename}") sys.exit() image = cv2.flip(image, 0) # Create texture self.texture = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture) # Generate texture gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1) gl.glTexImage2D( gl.GL_TEXTURE_2D, # target texture 0, # Mipmap Level gl.GL_RGBA, # The number of color components in the texture image.shape[1], # the width of texture image.shape[0], # the height of texture 0, # border (this value must be 0) gl.GL_BGR, # the format of the pixel data gl.GL_UNSIGNED_BYTE, # the type of pixel data image) # a pointer to the image # Set parameters gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_BORDER) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_BORDER) # Unbind gl.glBindTexture(gl.GL_TEXTURE_2D, 0) #======================================== # Prepare Camera Parameters #======================================== print("- Setting camera parameters.") # Transform matrix trans = glm.vec3(0., 0., 50.) rot = glm.vec3(0.) transform_matrix = glm.mat4(1.) transform_matrix = glm.translate(transform_matrix, trans) transform_matrix = glm.rotate(transform_matrix, glm.radians(rot.x), glm.vec3(1., 0., 0.)) transform_matrix = glm.rotate(transform_matrix, glm.radians(rot.y), glm.vec3(0., 1., 0.)) transform_matrix = glm.rotate(transform_matrix, glm.radians(rot.z), glm.vec3(0., 0., 1.)) self.default_camera_property = CameraProperty( transform_matrix=transform_matrix, clipping_distance=glm.vec2(10., 1000.), field_of_view=60.) self.camera_property = self.default_camera_property.clone() #======================================== # Prepare Shader Programs #======================================== print("- Preparing shaders.") is_loaded: bool = False vert_shader = gl.glCreateShader(gl.GL_VERTEX_SHADER) is_loaded = Viewer.load_shader(vert_shader, "glsl/vertex.glsl") if not is_loaded: sys.exit() frag_shader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER) is_loaded = Viewer.load_shader(frag_shader, "glsl/fragment.glsl") if not is_loaded: sys.exit() # Create shader program self.shader_program = gl.glCreateProgram() # Bind shader objects gl.glAttachShader(self.shader_program, vert_shader) gl.glAttachShader(self.shader_program, frag_shader) gl.glDeleteShader(vert_shader) gl.glDeleteShader(frag_shader) # Link shader program gl.glLinkProgram(self.shader_program) result = gl.glGetProgramiv(self.shader_program, gl.GL_LINK_STATUS) if result != gl.GL_TRUE: print(f"[GLFW Error] {gl.glGetShaderInfoLog(shader_id)}") sys.exit() # Specify uniform variables gl.glUseProgram(self.shader_program) gl.glUniform1i(gl.glGetUniformLocation(self.shader_program, "sampler"), 0) #======================================== # Prepare Other Instance Variables #======================================== # Cursor status self.previous_cursor_status = CursorStatus(button={ glfw.MOUSE_BUTTON_LEFT: False, glfw.MOUSE_BUTTON_RIGHT: False }, position=glm.vec3(0.)) print("Initialization done. ") Viewer.help()
def start(self): logger.info('initializing glfw@%s', glfw.get_version()) glfw.set_error_callback(_glfw_error_callback) if not glfw.init(): raise Exception('glfw failed to initialize') window = None if self.visible: glfw.window_hint(glfw.SAMPLES, 4) else: glfw.window_hint(glfw.VISIBLE, 0); # try stereo if refresh rate is at least 100Hz stereo_available = False _, _, refresh_rate = glfw.get_video_mode(glfw.get_primary_monitor()) if refresh_rate >= 100: glfw.window_hint(glfw.STEREO, 1) window = glfw.create_window( self.init_width, self.init_height, "Simulate", None, None) if window: stereo_available = True # no stereo: try mono if not window: glfw.window_hint(glfw.STEREO, 0) window = glfw.create_window( self.init_width, self.init_height, "Simulate", None, None) if not window: glfw.terminate() return self.running = True # Make the window's context current glfw.make_context_current(window) self._init_framebuffer_object() width, height = glfw.get_framebuffer_size(window) width1, height = glfw.get_window_size(window) self._scale = width * 1.0 / width1 self.window = window mjlib.mjv_makeObjects(byref(self.objects), 1000) mjlib.mjv_defaultCamera(byref(self.cam)) mjlib.mjv_defaultOption(byref(self.vopt)) mjlib.mjr_defaultOption(byref(self.ropt)) mjlib.mjr_defaultContext(byref(self.con)) if self.model: mjlib.mjr_makeContext(self.model.ptr, byref(self.con), 150) self.autoscale() else: mjlib.mjr_makeContext(None, byref(self.con), 150) glfw.set_cursor_pos_callback(window, self.handle_mouse_move) glfw.set_mouse_button_callback(window, self.handle_mouse_button) glfw.set_scroll_callback(window, self.handle_scroll)