def setup_gl(self): if platform.system() == "Darwin": self.ctx = moderngl.create_context(standalone=True) else: self.ctx = moderngl.create_context(standalone=True, backend='egl') self.fbo = self.ctx.simple_framebuffer((self.width, self.height), components=3) self.fbo.use() self.vertices = np.array([ -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, ], dtype='f4') self.prog = self.ctx.program( vertex_shader=open('equirectangular.vert', 'r').read(), fragment_shader=open('equirectangular.frag', 'r').read())
def test_share(self): """Create resources with shared context""" if platform.system().lower() in ["darwin", "linux"]: self.skipTest('Context sharing not supported on darwin') data1 = numpy.array([1, 2, 3, 4], dtype='u1') data2 = numpy.array([4, 3, 2, 1], dtype='u1') ctx1 = moderngl.create_context(standalone=True) ctx2 = moderngl.create_context(standalone=True, share=True) with ctx1 as ctx: b1 = ctx.buffer(data=data1) with ctx2 as ctx: b2 = ctx.buffer(data=data2) # Because the resources are shared the name should increment self.assertEqual(b1.glo, 1) self.assertEqual(b2.glo, 2) # Ensure we can read the same buffer data in both contexts with ctx1: self.assertEqual(b1.read(), b'\x01\x02\x03\x04') self.assertEqual(b2.read(), b'\x04\x03\x02\x01') with ctx2: self.assertEqual(b1.read(), b'\x01\x02\x03\x04') self.assertEqual(b2.read(), b'\x04\x03\x02\x01') ctx1.release() ctx2.release()
def init_scene(self, scene): self.partial_movie_files = [] self.file_writer = self._file_writer_class( self, scene.__class__.__name__, ) self.scene = scene if not hasattr(self, "window"): if config["preview"]: from .opengl_renderer_window import Window self.window = Window(self) self.context = self.window.ctx self.frame_buffer_object = self.context.detect_framebuffer() else: self.window = None try: self.context = moderngl.create_context(standalone=True) except Exception: self.context = moderngl.create_context(standalone=True, backend="egl") self.frame_buffer_object = self.get_frame_buffer_object( self.context, 0) self.frame_buffer_object.use() self.context.enable(moderngl.BLEND) self.context.blend_func = ( moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA, moderngl.ONE, moderngl.ONE, )
def initializeGL(self): # retrieve global shared context if available global global_context if QApplication.testAttribute(Qt.AA_ShareOpenGLContexts): if not global_context: global_context = mgl.create_context() self.scene.ctx = global_context # or create a context else: self.scene.ctx = mgl.create_context() self.init() self.preload()
def test_exit(self): """Ensure the previous context was activated on exit""" ctx1 = moderngl.create_context(standalone=True) ctx2 = moderngl.create_context(standalone=True) with ctx1 as ctx: ctx.buffer(reserve=1024) # Will error out if no context is active "moderngl.error.Error: cannot create buffer" ctx1.buffer(reserve=1024) ctx1.release() ctx2.release()
def setup_gl(self): if platform.system() == "Darwin": self.ctx = moderngl.create_context(standalone=True) else: self.ctx = moderngl.create_context(standalone=True, backend='egl') self.fbo = self.ctx.simple_framebuffer((self.width, self.height), components=3) self.fbo.use() self.vertices = np.array([ -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, ], dtype='f4') self.prog = self.ctx.program( vertex_shader=open('equirectangular.vert', 'r').read(), fragment_shader=open('equirectangular.frag', 'r').read()) # set constants self.prog['FOV'].value = PI * fov / 180.0 self.prog['cam1_radius'].value = cam1_radius self.prog['cam2_radius'].value = cam2_radius self.prog['cam1_margin'].value = cam1_margin self.prog['cam2_margin'].value = cam2_margin self.prog['yaw'].value = 0.0 self.prog['pitch'].value = 0.0 self.prog['roll'].value = 0.0 self.prog['camTex1'].value = 0 self.prog['camTex2'].value = 1 # setup textures self.tex1 = self.ctx.texture((self.width, self.height), components=3) self.tex2 = self.ctx.texture((self.width, self.height), components=3) self.tex1.use(self.prog['camTex1'].value) self.tex2.use(self.prog['camTex2'].value) # setup vertex array and frame buffer self.vao = self.ctx.simple_vertex_array(self.prog, self.ctx.buffer(self.vertices), 'in_vert') self.frame = np.empty((self.height, self.width, 3), dtype='u1')
def test_context_switch(self): """Ensure context switching is working""" ctx1 = moderngl.create_context(standalone=True) ctx2 = moderngl.create_context(standalone=True) with ctx1 as ctx: buffer1 = ctx.buffer(reserve=1024) with ctx2 as ctx: buffer2 = ctx.buffer(reserve=1024) self.assertEqual(buffer1.glo, buffer2.glo) ctx1.release() ctx2.release()
def __init__(self): super().__init__() if not glfw.init(): raise ValueError("Failed to initialize glfw") self.check_glfw_version() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, self.gl_version.major) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, self.gl_version.minor) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) glfw.window_hint(glfw.RESIZABLE, self.resizable) glfw.window_hint(glfw.DOUBLEBUFFER, True) glfw.window_hint(glfw.DEPTH_BITS, 24) glfw.window_hint(glfw.SAMPLES, self.samples) monitor = None if self.fullscreen: # Use the primary monitors current resolution monitor = glfw.get_primary_monitor() mode = glfw.get_video_mode(monitor) self.width, self.height = mode.size.width, mode.size.height print("picked fullscreen mode:", mode) print("Window size:", self.width, self.height) self.window = glfw.create_window(self.width, self.height, self.title, monitor, None) if not self.window: glfw.terminate() raise ValueError("Failed to create window") if not self.cursor: glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED) # Get the actual buffer size of the window # This is important for some displays like Apple's Retina as reported window sizes are virtual self.buffer_width, self.buffer_height = glfw.get_framebuffer_size( self.window) print("Frame buffer size:", self.buffer_width, self.buffer_height) print("Actual window size:", glfw.get_window_size(self.window)) glfw.make_context_current(self.window) # The number of screen updates to wait from the time glfwSwapBuffers # was called before swapping the buffers and returning if self.vsync: glfw.swap_interval(1) glfw.set_key_callback(self.window, self.key_event_callback) glfw.set_cursor_pos_callback(self.window, self.mouse_event_callback) glfw.set_window_size_callback(self.window, self.window_resize_callback) # Create mederngl context from existing context self.ctx = moderngl.create_context(require=self.gl_version.code) context.WINDOW = self self.fbo = self.ctx.screen self.set_default_viewport()
def __init__(self, width, height): super(Render, self).__init__() self.width, self.height = width, height self.gl = mg.create_context() n_particles = 256 * 64 width, height, depth = 32, 32, 32 vector_field_info = VectorFieldInfo(width, height, depth) particles_data = np.zeros(shape=(n_particles, 12)) particles_data[:, 0:3] = np.random.uniform(-1.0, +1.0, particles_data[:, 0:3].shape) particles_data[:, 3] = 1.0 self.particles = self.gl.buffer( particles_data.astype(np.float32).tobytes()) self.particles.bind_to_storage_buffer(0) self.vector_field = self.gl.buffer( reserve=vector_field_info.get_size()) self.vector_field.bind_to_storage_buffer(1) self.cs = self.gl.compute_shader( read_file("./gl/advance_particles.glsl")) self.uniform(self.cs, {"u_grid_res": uvec3(width, height, depth)}) self.gx = n_particles // 64 self.particles_prog = self.gl.program( vertex_shader=read_file("./gl/passthrough.vert.glsl"), geometry_shader=read_file("./gl/particle_to_quad.geo.glsl"), fragment_shader=read_file("./gl/color.frag.glsl"), ) self.particles_va = self.gl.vertex_array( self.particles_prog, [(self.particles, "4f 4f", "in_pos", "in_vel")], skip_errors=True, ) self.screen_program = self.gl.program( vertex_shader=read_file("./gl/screen_verts.glsl"), fragment_shader=read_file("./gl/screen_frag.glsl"), ) self.screen_vbo = self.gl.buffer( np.array([-1.0, -1.0, +1.0, -1.0, -1.0, +1.0, +1.0, +1.0]).astype(np.float32).tobytes()) self.screen_ibo = self.gl.buffer( np.array([0, 1, 2, 2, 1, 3]).astype(np.int32).tobytes()) self.screen_va = self.gl.vertex_array( self.screen_program, [(self.screen_vbo, "2f", "in_pos")], self.screen_ibo) self.uniform(self.particles_prog, {"u_aspect": width / height})
def test_extensions(self): ctx = moderngl.create_context(standalone=True) print(ctx.extensions) self.assertTrue("GL_ARB_gpu_shader5" in ctx.extensions) self.assertTrue("GL_ARB_transform_feedback2" in ctx.extensions) self.assertTrue("GL_ARB_shader_subroutine" in ctx.extensions) ctx.release()
def __init__(self, gl_win, width, height): super(Renderer, self).__init__() self.window = gl_win self.width, self.height = width, height self.gl = mg.create_context() self.vbo = self.gl.buffer(reserve=4 * 4 * 4) self.ibo = self.gl.buffer(reserve=6 * 4) self.vbo.bind_to_storage_buffer(0) self.ibo.bind_to_storage_buffer(1) self.const = self.gl.buffer(reserve=1024) self.const.bind_to_storage_buffer(15) self.build_vao() def onmod(e): self.should_compile = True h = FileSystemEventHandler() h.on_modified = onmod o = Observer() o.schedule(h, "./gl/", True) o.start()
def __init__(self): self.ctx = moderngl.create_context() self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); } ''', fragment_shader=''' #version 330 out vec4 f_color; void main() { f_color = vec4(0.1, 0.1, 0.1, 1.0); } ''', ) self.camera = Camera(self.wnd.ratio) self.mvp = self.prog['Mvp'] self.vbo = self.ctx.buffer(grid(15, 10).astype('f4').tobytes()) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, 'in_vert')
def __init__(self, width, height): super(Context, self).__init__() self.recorder = None self.GL = mg.create_context() self.width, self.height = width, height self.screenvbo = self.GL.buffer(reserve=4 * 4 * 4) self.screenibo = self.GL.buffer(reserve=6 * 4) self.screenvbo.bind_to_storage_buffer(0) self.screenibo.bind_to_storage_buffer(1) self.programs = [] self.vertex_arrays = [] self.recompile() def on_mod(e): self._should_recomile = True handler = FileSystemEventHandler() handler.on_modified = on_mod observer = Observer() observer.schedule(handler, "./gl") observer.start()
def __init__(self, wnd): self.wnd = wnd self.ctx = moderngl.create_context() self.prog = self.ctx.program( vertex_shader=''' #version 330 in vec2 in_vert; out vec2 v_text; void main() { gl_Position = vec4(in_vert, 0.0, 1.0); v_text = in_vert; } ''', fragment_shader=''' #version 330 in vec2 v_text; out vec4 f_color; uniform sampler2D Texture; uniform vec2 Seed; uniform int Iter; void main() { vec2 c = Seed; int i; vec2 z = vec2(3.0 * v_text.x, 2.0 * v_text.y); for (i = 0; i < Iter; i++) { float x = (z.x * z.x - z.y * z.y) + c.x; float y = (z.y * z.x + z.x * z.y) + c.y; if ((x * x + y * y) > 4.0) { break; } z.x = x; z.y = y; } f_color = texture(Texture, vec2((i == Iter ? 0.0 : float(i)) / 100.0, 0.0)); } ''', ) self.seed = self.prog['Seed'] self.iter = self.prog['Iter'] img = Image.open(local('data', 'pal.png')).convert('RGB') self.texture = self.ctx.texture(img.size, 3, img.tobytes()) self.texture.use() vertices = np.array([-1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0]) self.vbo = self.ctx.buffer(vertices.astype('f4').tobytes()) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, 'in_vert')
def _make_context(self, width, height): """Create the ModernGL context.""" glconfig = { 'GL_CONTEXT_MAJOR_VERSION': 4, 'GL_CONTEXT_PROFILE_MASK': pygame.GL_CONTEXT_PROFILE_CORE, } for k, v in glconfig.items(): k = getattr(pygame, k) pygame.display.gl_set_attribute(k, v) flags = pygame.OPENGL | pygame.DOUBLEBUF if self._scaler: flags |= pygame.SCALED pygame.display.set_mode( (width, height), flags=flags, depth=24 ) ctx = moderngl.create_context(require=410) real_size = pygame.display.get_window_size() if real_size != (width, height): self.drawer = self._make_scaler(ctx, (width, height)) return ctx
def __init__(self, window): super().__init__() self.window = window self.width, self.height = WIDTH, HEIGHT self.gl = mg.create_context() self.rotation = vec2(0.0, 0.0) self.u_campos = vec3(-2.0, 2.0, 5.0) self._prevpos = ivec2(0, 0) self._isdrag = False self.compile_shaders() def _on_mod(e): self.should_compile = True handler = FileSystemEventHandler() handler.on_modified = _on_mod observer = Observer() observer.schedule(handler, "./gl", True) observer.schedule(handler, "./tex", True) observer.start() imgui.create_context() self.imgui = ModernGLGLFWRenderer(ctx=self.gl, display_size=(WIDTH, HEIGHT)) self.imgui.wire_events(self.gl, window) self.imgui.on_mouse_button = self.on_mouse_button self.imgui.on_cursor_pos = self.on_cursor_pos
def init(self): self.gl = mg.create_context() self.vbo = [ ( self.gl.buffer( np.array([-1.0, -1.0, -1.0, +1.0, +1.0, -1.0, +1.0, +1.0]) .astype(np.float32) .tobytes() ), "2f", "in_pos", ) ] self.ibo = self.gl.buffer( np.array([0, 1, 2, 2, 1, 3]).astype(np.int32).tobytes() ) self.recompile() handler = FileSystemEventHandler() handler.on_modified = lambda e: self.set_recompile_flag(True) observer = Observer() observer.schedule(handler, "./gl/") observer.start()
def __init__(self, world): self.world = world self.ctx = moderngl.create_context() self.vaos = {} self.shader = None world.on_add_entity.subscribe(self.add_entity) self.frames = 0
def __init__(self): super().__init__() # Disable all error checking pyglet.options['debug_gl'] = False # Set context parameters config = pyglet.gl.Config() config.double_buffer = True config.major_version = self.gl_version.major config.minor_version = self.gl_version.minor config.forward_compatible = True config.sample_buffers = 1 if self.samples > 1 else 0 config.samples = self.samples # Find monitor # Open window self.window = PygletWrapper( width=self.width, height=self.height, caption=self.title, resizable=self.resizable, vsync=self.vsync, fullscreen=self.fullscreen, ) self.window.set_mouse_visible(self.cursor) self.window.event(self.on_key_press) self.window.event(self.on_key_release) self.window.event(self.on_mouse_motion) self.window.event(self.on_resize) self.ctx = moderngl.create_context(require=self.gl_version.code) context.WINDOW = self self.fbo = self.ctx.screen self.set_default_viewport()
def initializeGL(self): """ called only once when start """ self.gl = mg.create_context() self.recompile() self.to_capture = False self.capture_texture = self.gl.texture((capture_width, capture_height), 4, dtype="f4") capture_framebuffer = self.gl.framebuffer([self.capture_texture]) self.capture_scope = self.gl.scope(capture_framebuffer) self.to_record = False self.record_texture = self.gl.texture((record_width, record_height), 4, dtype="f4") record_framebuffer = self.gl.framebuffer([self.record_texture]) self.record_scope = self.gl.scope(record_framebuffer) self.recording = None self.to_capture_buffer_in = False self.to_capture_buffer_out = False
def _make_context(self, width, height): """Create the ModernGL context.""" glconfig = { 'GL_CONTEXT_MAJOR_VERSION': 4, 'GL_CONTEXT_PROFILE_MASK': pygame.GL_CONTEXT_PROFILE_CORE, } for k, v in glconfig.items(): k = getattr(pygame, k) pygame.display.gl_set_attribute(k, v) dims = width, height flags = pygame.OPENGL | pygame.DOUBLEBUF if self.fullscreen: # SDL's detection for "legacy" fullscreen seems to fail on # Ubuntu 16.04 at least. Set an environment variable so that it # asks the Window Manager for full screen mode instead. # https://github.com/spurious/SDL-mirror/blob/c8b01e282dfd49ea8bbf1faec7fd65d869ea547f/src/video/x11/SDL_x11window.c#L1468 os.environ['SDL_VIDEO_X11_LEGACY_FULLSCREEN'] = "0" flags |= pygame.FULLSCREEN if not self._scaler: self._scaler = 'linear' dims = 0, 0 elif self._scaler: flags |= pygame.SCALED pygame.display.set_mode(dims, flags=flags, depth=24, vsync=True) ctx = moderngl.create_context(require=410) self._real_size = pygame.display.get_window_size() if self._real_size != (width, height): self.drawer = self._make_scaler(ctx, (width, height)) return ctx
def __init__(self, background_color=dark_gray, clock=mono_clock.get_time): # lazy load, partially to avoid auto-formatter that wants to # do imports, *then* dict setting from pyglet import gl from pyglet.window import Window self._background_color = Vector4f(background_color) self.clock = clock self.current_time = 0 self.prev_time = 0 # can bump down `samples` if performance is hurting config = gl.Config(depth_size=0, double_buffer=True, alpha_size=8, sample_buffers=1, samples=4, vsync=False, major_version=3, minor_version=3) display = pyglet.canvas.get_display() screen = display.get_screens()[0] self._win = Window(resizable=False, fullscreen=True, screen=screen, config=config, style='borderless', vsync=True) self._win.event(self.on_key_press) atexit.register(self._on_close) self.context = mgl.create_context(require=int('%i%i0' % (config.major_version, config.minor_version))) self.context.viewport = (0, 0, self.width, self.height) self.context.enable(mgl.BLEND) self.frame_period # do this before we've drawn anything # in principle, should be disconnected from the window # but we're saving time & mental energy self.cam = Camera(projection=height_ortho(self.width, self.height))
def init_gl(self): self.gl = mg.create_context() self.vbo = self.gl.buffer( np.array( [-1.0, -1.0, 0.0, -1.0, +1.0, 0.0, +1.0, -1.0, 0.0, +1.0, +1.0, 0.0] ) .astype(np.float32) .tobytes() ) self.ibo = self.gl.buffer( np.array([0, 1, 2, 2, 1, 3]).astype(np.int32).tobytes() ) self.recompile() width, height = glfw.get_window_size(self.window) self.uniform("u_resolution", vec2(width, height)) self.wire_events() def on_mod(e): self.should_recompile = True handler = FileSystemEventHandler() handler.on_modified = on_mod self.observer = Observer() self.observer.schedule(handler, "./gl/", True) self.observer.start()
def initializeGL(self): self.context = mg.create_context() self.context.viewport = self.viewport program = self.context.program(vertex_shader=vertex_shader, fragment_shader=fragment_shader) verts = np.array([ -1.0, -1.0, +0.0, 0.0, 0.0, -1.0, +1.0, +0.0, 0.0, 1.0, +1.0, -1.0, +0.0, 1.0, 0.0, +1.0, +1.0, +0.0, 1.0, 1.0 ]).astype('f4') indices = np.array([0, 1, 2, 1, 2, 3]).astype('i4') self.vao = self.context.vertex_array( program, [(self.context.buffer( verts.tobytes()), "3f 2f", "in_verts", "in_uv")], self.context.buffer(indices.tobytes())) self.out_texture = self.context.texture((self.W, self.H), 4, dtype='f4') self.framebuffer = self.context.framebuffer(self.out_texture) self.unif_t = program['T'] self.prev_time = time.time() self.elapsed_time = 0.0 if self.RECORDING: self.writer = ii.get_writer("output.mp4", fps=60)
def paintGL(self): self.ctx = moderngl.create_context() self.screen = self.ctx.detect_framebuffer( self.defaultFramebufferObject()) self.init() self.render() self.paintGL = self.render
def initializeGL(self): self.gl = mg.create_context() self.vertices = self.gl.buffer( np.array( [ (-1.0, -1.0, 0.0, 1.0), (+1.0, -1.0, 0.0, 1.0), (-1.0, +1.0, 0.0, 1.0), (+1.0, +1.0, 0.0, 1.0), ], dtype=np.float32, ) ) self.indices = self.gl.buffer(np.array([0, 1, 2, 2, 1, 3], dtype=np.int32)) self.reload_textures() self.recompile_shaders() handler_gl = FileSystemEventHandler() handler_gl.on_modified = self.on_gl_src_modified handler_resources = FileSystemEventHandler() handler_resources.on_modified = self.on_resources_modified oberver = Observer() oberver.schedule(handler_gl, "./gl", True) oberver.schedule(handler_resources, "./resources", True) oberver.start()
def initializeGL(self): self.context = mg.create_context() program = self.context.program(vertex_shader=vertex_shader, fragment_shader=fragment_shader) vertex_data = np.array([ # x, y, z, u, v -1.0, -1.0, 0.0, 0.0, 0.0, +1.0, -1.0, 0.0, 1.0, 0.0, -1.0, +1.0, 0.0, 0.0, 1.0, +1.0, +1.0, 0.0, 1.0, 1.0, ]).astype(np.float32) content = [(self.context.buffer(vertex_data.tobytes()), '3f 2f', 'in_vert', 'in_uv')] idx_data = np.array([0, 1, 2, 1, 2, 3]).astype(np.int32) idx_buffer = self.context.buffer(idx_data.tobytes()) self.vao = self.context.vertex_array(program, content, idx_buffer) self.u_time = program.get("T", 0.0)
def main(): gl = mg.create_context(standalone=True, require=460) cs = gl.compute_shader(source=""" #version 460 layout(local_size_x=8, local_size_y=8) in; layout(binding=0) buffer b_0 { vec4 x[]; }; void main() { uvec2 xy = gl_LocalInvocationID.xy + gl_WorkGroupID.xy * gl_WorkGroupSize.xy; vec2 uv = vec2(xy) / 512.0; uint index = xy.x * 512 + xy.y; x[index] = vec4(uv.xy, 0.0, 1.0); } """) gl_buffer = gl.buffer(reserve=SIZE * SIZE * 4 * 4) gl_buffer.bind_to_storage_buffer(0) cs.run(SIZE // 8, SIZE // 8) data = np.multiply(np.frombuffer(gl_buffer.read(), dtype=np.float32), 255.0) data = data.reshape(SIZE, SIZE, 4).astype(np.uint8) ii.imwrite("output.png", data)
def initializeGL(self): context = mg.create_context() program = context.program( vertex_shader=vertex_shader, fragment_shader=fragment_shader) vertex_data = np.array([ # x y z u v (-1.0, -1.0, +0.0, 0.0, 0.0), (-1.0, +1.0, +0.0, 1.0, 0.0), (+1.0, -1.0, +0.0, 0.0, 1.0), (+1.0, +1.0, +0.0, 1.0, 1.0), ]).astype(np.float32) index_data = np.array([ 0, 1, 2, 1, 2, 3 ]).astype(np.int32) vb = context.buffer(vertex_data.tobytes()) ib = context.buffer(index_data.tobytes()) content = [( vb, '3f 2f', 'in_vert', 'in_texcoord0' )] self.vaos.append( context.vertex_array(program, content, ib))
def test_attributes(self): """Ensure enums are present in the context instance""" ctx = moderngl.create_context(standalone=True) # Flags self.assertIsInstance(ctx.NOTHING, int) self.assertIsInstance(ctx.BLEND, int) self.assertIsInstance(ctx.DEPTH_TEST, int) self.assertIsInstance(ctx.CULL_FACE, int) self.assertIsInstance(ctx.RASTERIZER_DISCARD, int) self.assertIsInstance(ctx.PROGRAM_POINT_SIZE, int) # Primitive modes self.assertIsInstance(ctx.POINTS, int) self.assertIsInstance(ctx.LINES, int) self.assertIsInstance(ctx.LINE_LOOP, int) self.assertIsInstance(ctx.LINE_STRIP, int) self.assertIsInstance(ctx.TRIANGLES, int) self.assertIsInstance(ctx.TRIANGLE_STRIP, int) self.assertIsInstance(ctx.TRIANGLE_FAN, int) self.assertIsInstance(ctx.LINES_ADJACENCY, int) self.assertIsInstance(ctx.LINE_STRIP_ADJACENCY, int) self.assertIsInstance(ctx.TRIANGLES_ADJACENCY, int) self.assertIsInstance(ctx.TRIANGLE_STRIP_ADJACENCY, int) self.assertIsInstance(ctx.PATCHES, int) # Texture filters self.assertIsInstance(ctx.LINEAR, int) self.assertIsInstance(ctx.NEAREST, int) self.assertIsInstance(ctx.NEAREST_MIPMAP_NEAREST, int) self.assertIsInstance(ctx.LINEAR_MIPMAP_LINEAR, int) self.assertIsInstance(ctx.LINEAR_MIPMAP_NEAREST, int) self.assertIsInstance(ctx.NEAREST_MIPMAP_LINEAR, int) # Blend functions self.assertIsInstance(ctx.ZERO, int) self.assertIsInstance(ctx.ONE, int) self.assertIsInstance(ctx.SRC_COLOR, int) self.assertIsInstance(ctx.ONE_MINUS_SRC_COLOR, int) self.assertIsInstance(ctx.SRC_ALPHA, int) self.assertIsInstance(ctx.ONE_MINUS_SRC_ALPHA, int) self.assertIsInstance(ctx.DST_ALPHA, int) self.assertIsInstance(ctx.ONE_MINUS_DST_ALPHA, int) self.assertIsInstance(ctx.DST_COLOR, int) self.assertIsInstance(ctx.ONE_MINUS_DST_COLOR, int) # Blend shortcuts self.assertIsInstance(ctx.DEFAULT_BLENDING, tuple) self.assertIsInstance(ctx.ADDITIVE_BLENDING, tuple) self.assertIsInstance(ctx.PREMULTIPLIED_ALPHA, tuple) # Blend equations self.assertIsInstance(ctx.FUNC_ADD, int) self.assertIsInstance(ctx.FUNC_SUBTRACT, int) self.assertIsInstance(ctx.FUNC_REVERSE_SUBTRACT, int) self.assertIsInstance(ctx.MIN, int) self.assertIsInstance(ctx.MAX, int) # Provoking vertex self.assertIsInstance(ctx.FIRST_VERTEX_CONVENTION, int) self.assertIsInstance(ctx.LAST_VERTEX_CONVENTION, int)
def __init__(self, **kwargs): super().__init__(**kwargs) if not glfw.init(): raise ValueError("Failed to initialize glfw") # Configure the OpenGL context glfw.window_hint(glfw.CONTEXT_CREATION_API, glfw.NATIVE_CONTEXT_API) glfw.window_hint(glfw.CLIENT_API, glfw.OPENGL_API) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, self.gl_version[0]) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, self.gl_version[1]) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) glfw.window_hint(glfw.RESIZABLE, self.resizable) glfw.window_hint(glfw.DOUBLEBUFFER, True) glfw.window_hint(glfw.DEPTH_BITS, 24) glfw.window_hint(glfw.SAMPLES, self.samples) monitor = None if self.fullscreen: # Use the primary monitors current resolution monitor = glfw.get_primary_monitor() mode = glfw.get_video_mode(monitor) self.width, self.height = mode.size.width, mode.size.height # Make sure video mode switching will not happen by # matching the desktops current video mode glfw.window_hint(glfw.RED_BITS, mode.bits.red) glfw.window_hint(glfw.GREEN_BITS, mode.bits.green) glfw.window_hint(glfw.BLUE_BITS, mode.bits.blue) glfw.window_hint(glfw.REFRESH_RATE, mode.refresh_rate) self.window = glfw.create_window(self.width, self.height, self.title, monitor, None) if not self.window: glfw.terminate() raise ValueError("Failed to create window") if not self.cursor: glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED) self.buffer_width, self.buffer_height = glfw.get_framebuffer_size(self.window) glfw.make_context_current(self.window) if self.vsync: glfw.swap_interval(1) glfw.set_key_callback(self.window, self.key_event_callback) glfw.set_cursor_pos_callback(self.window, self.mouse_event_callback) glfw.set_mouse_button_callback(self.window, self.mouse_button_callback) glfw.set_window_size_callback(self.window, self.window_resize_callback) self.ctx = moderngl.create_context(require=self.gl_version_code) self.print_context_info() self.set_default_viewport()
def __init__(self, **kwargs): super().__init__(**kwargs) if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: raise ValueError("Failed to initialize sdl2") # Configure OpenGL context sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MAJOR_VERSION, self.gl_version[0]) sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MINOR_VERSION, self.gl_version[1]) sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_PROFILE_MASK, sdl2.SDL_GL_CONTEXT_PROFILE_CORE) sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG, 1) sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_DOUBLEBUFFER, 1) sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_DEPTH_SIZE, 24) # Display/hide mouse cursor sdl2.SDL_ShowCursor(sdl2.SDL_ENABLE if self.cursor else sdl2.SDL_DISABLE) # Configure multisampling if self.samples > 1: sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_MULTISAMPLEBUFFERS, 1) sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_MULTISAMPLESAMPLES, self.samples) # Built the window flags flags = sdl2.SDL_WINDOW_OPENGL if self.fullscreen: # Use primary desktop screen resolution flags |= sdl2.SDL_WINDOW_FULLSCREEN_DESKTOP else: if self.resizable: flags |= sdl2.SDL_WINDOW_RESIZABLE # Create the window self.window = sdl2.SDL_CreateWindow( self.title.encode(), sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, self.width, self.height, flags, ) if not self.window: raise ValueError("Failed to create window:", sdl2.SDL_GetError()) self.context = sdl2.SDL_GL_CreateContext(self.window) sdl2.video.SDL_GL_SetSwapInterval(1 if self.vsync else 0) self.ctx = moderngl.create_context(require=self.gl_version_code) self.set_default_viewport() self.print_context_info()
def get_default_context(allow_fallback_standalone_context=True) -> moderngl.Context: ''' Default context ''' if ContextManager.ctx is None: try: ContextManager.ctx = moderngl.create_context() except moderngl.Error: if allow_fallback_standalone_context: ContextManager.ctx = moderngl.create_standalone_context() else: raise return ContextManager.ctx
def __init__(self, **kwargs): super().__init__(**kwargs) # Disable all error checking pyglet.options['debug_gl'] = False # Set context parameters config = pyglet.gl.Config() config.double_buffer = True config.major_version = self.gl_version[0] config.minor_version = self.gl_version[1] config.forward_compatible = True # MISSING: Core context flag config.sample_buffers = 1 if self.samples > 1 else 0 config.samples = self.samples # Obtain the default destop screen's resolution if self.fullscreen: platform = pyglet.window.get_platform() display = platform.get_default_display() screen = display.get_default_screen() self.width, self.height = screen.width, screen.height # Create window wrapper self.window = PygletWrapper( width=self.width, height=self.height, caption=self.title, resizable=self.resizable, vsync=self.vsync, fullscreen=self.fullscreen, ) # Show/hide mouse cursor self.window.set_mouse_visible(self.cursor) # Override the default event callbacks self.window.event(self.on_key_press) self.window.event(self.on_key_release) self.window.event(self.on_mouse_motion) self.window.event(self.on_resize) self.window.event(self.on_mouse_press) self.window.event(self.on_mouse_release) self.ctx = moderngl.create_context(require=self.gl_version_code) self.set_default_viewport() self.print_context_info()
def initializeGL(self): self.context = mg.create_context() self.program = self.context.program( vertex_shader=simple_vertex_shader_code, fragment_shader=simple_fragment_shader_code ) index_data = np.array([ 0, 1, 2, 1, 2, 3, ]).astype('i4') self.index_buffer = self.context.buffer(index_data.tobytes()) self.vbo_data = np.array([ # x y u v r g b [-1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0], [-1.0, +1.0, 0.0, 1.0, 0.0, 0.0, 0.0], [+1.0, -1.0, 1.0, 0.0, 0.0, 0.0, 0.0], [+1.0, +1.0, 1.0, 1.0, 0.0, 0.0, 0.0], ]).astype('f4') compute_shader_code_parsed = compute_worker_shader_code.replace("%COMPUTE_SIZE%", str(Renderer.COUNT)) self.compute_shader = self.context.compute_shader(compute_shader_code_parsed) compute_data = [] for i in range(Renderer.COUNT): _angle = (i / Renderer.COUNT) * math.pi * 2.0 _dist = 0.125 radius = random.random() * 0.02 + 0.02 x = math.cos(_angle) * _dist y = math.sin(_angle) * _dist z = 0.0 w = radius _v = random.random() * 0.005 + 0.01 vx = math.cos(_angle) * _v vy = math.sin(_angle) * _v vz = 0.0 vw = 0.0 r = 1.0 * random.random() g = 1.0 * random.random() b = 1.0 * random.random() a = 1.0 # match bytes compute_data.append( [[x, y, z, w], [vx, vy, vz, vw], [r, g, b, a]]) compute_data = np.array(compute_data).astype('f4') compute_data_bytes = compute_data.tobytes() self.compute_buffer_a = self.context.buffer(compute_data_bytes) self.compute_buffer_b = self.context.buffer(compute_data_bytes) self.target_buffer = self.compute_buffer_b self.timer_thread = ComputeToggleTimer() self.timer_thread.compute_update_signal.connect(self.update_computeworker) self.timer_thread.start() self.item_vertex_buffer = self.context.buffer(reserve=112) self.vertex_array = self.context.vertex_array( self.program, [( self.item_vertex_buffer, '2f 2f 3f', 'in_vert', 'in_uv', 'in_col' )], self.index_buffer, )
import struct import moderngl import pygame from pygame.locals import DOUBLEBUF, OPENGL pygame.init() pygame.display.set_mode((800, 600), DOUBLEBUF | OPENGL) ctx = moderngl.create_context() prog = ctx.program( vertex_shader=''' #version 310 es in vec2 vert; void main() { gl_Position = vec4(vert, 0.0, 1.0); } ''', fragment_shader=''' #version 310 es precision mediump float; out vec4 color; void main() { color = vec4(0.3, 0.5, 1.00, 1.0); } ''') vbo = ctx.buffer(struct.pack('6f', 0.0, 0.8, -0.6, -0.8, 0.6, -0.8))
def paintGL(self): self.ctx = moderngl.create_context() self.screen = self.ctx.detect_framebuffer(self.defaultFramebufferObject()) self.init() self.render() self.paintGL = self.render