How to use the moderngl.create_standalone_context function in moderngl

To help you get started, we’ve selected a few moderngl examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github c3nav / c3nav / src / c3nav / mapdata / render / engines / opengl.py View on Github external
def create(cls, width, height):
        ctx = moderngl.create_standalone_context()

        color_rbo = ctx.renderbuffer((width, height), samples=ctx.max_samples)
        fbo = ctx.framebuffer([color_rbo])
        fbo.use()

        prog = ctx.program(
            vertex_shader='''
                #version 330
                in vec3 in_vert;
                in vec4 in_color;
                out vec4 v_color;

                uniform mat4 mvp;

                void main() {
                    gl_Position = mvp * vec4(in_vert, 1.0);
github bhautikj / vrProjector / vrProjector / ModernGLWrapper.py View on Github external
def __init__(self, fragProg=SAMPLEFSPROG, outWidth=512, outHeight=512, texture=None):
    self.ctx = moderngl.create_standalone_context()

    ##
    ## add 
    ## uniform sampler2D Texture;
    ## to your fragment shader to access the texture
    ##
    if texture != None:
      textureSrc = Image.open(texture).transpose(Image.FLIP_TOP_BOTTOM).convert('RGB')
      self.texture = self.ctx.texture(textureSrc.size, 3, textureSrc.tobytes())
      #self.texture.filter = (moderngl.moderngl.LINEAR. moderngl.moderngl.LINEAR)
      #self.texture.build_mipmaps() - don't do this! converts sampling mode to mipmaps, expensive
      self.texture.use()
    
    self.quadVsProg = QUADVSPROG
    self.quadFsProg = fragProg
    self.vertices = VERTICES
github moderngl / moderngl / moderngl / __main__.py View on Github external
version = 'moderngl %s' % moderngl.__version__

    if os.path.isfile(os.path.join(os.path.dirname(__file__), 'README.md')):
        try:
            head = subprocess.check_output(['git', 'rev-parse', 'HEAD'], stderr=subprocess.DEVNULL)
            version += ' (%s)' % head.decode()[:8]
        except Exception:
            version += ' (archive)'

    parser = argparse.ArgumentParser(prog='moderngl')
    parser.add_argument('-v', '--version', action='version', version=version)
    parser.add_argument('--info', action='store_true', default=False)
    args = parser.parse_args(argv)

    ctx = moderngl.create_standalone_context()

    if args.info:
        print(json.dumps(ctx.info, sort_keys=True, indent=4))

    else:
        print(version)
        print('-' * len(version))
        print('vendor:', ctx.info['GL_VENDOR'])
        print('renderer:', ctx.info['GL_RENDERER'])
        print('version:', ctx.info['GL_VERSION'])
        print('python:', sys.version)
        print('platform:', sys.platform)
        print('code:', ctx.version_code)
github menpo / menpo3d / menpo3d / rasterize / opengl.py View on Github external
def __init__(self, width=1024, height=768, model_matrix=None,
                 view_matrix=None, projection_matrix=None):
        # Make a single OpenGL context that will be managed by the lifetime of
        # this class. We will dynamically create two default "pass through"
        # programs based on the type of the input mesh
        self.opengl_ctx = moderngl.create_standalone_context()
        self.width = width
        self.height = height

        self._model_matrix = model_matrix if model_matrix is not None else np.eye(4)
        self._view_matrix = view_matrix if view_matrix is not None else np.eye(4)
        self._projection_matrix = projection_matrix if projection_matrix is not None else np.eye(4)
        self._vertex_shader = None
        self._fragment_shader = None
        self._shader_type = None
        # We will dynamically build the program based on the mesh type
        self._active_program = None
        self._texture_program = None
        self._per_vertex_program = None

        self._f3v_renderbuffer = self.opengl_ctx.renderbuffer(
            self.size, components=3, dtype='f4'
github moderngl / moderngl / examples / context_manager.py View on Github external
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
github moderngl / moderngl / examples / compute_shader.py View on Github external
"W": W,
    "H": H,
    "X": X + 1,
    "Y": Y,
    "Z": Z,
}

FRAMES = 50
SOURCE_PATH = os.path.dirname(__file__)
OUTPUT_DIRPATH = os.path.join(SOURCE_PATH, "output")

if not os.path.isdir(OUTPUT_DIRPATH):
    os.makedirs(OUTPUT_DIRPATH)

glsl_file = os.path.join(SOURCE_PATH, 'gl/median_5x5.gl')
context = moderngl.create_standalone_context(require=430)
compute_shader = context.compute_shader(source(glsl_file, consts))

# init buffers
buffer_a_data = np.random.uniform(0.0, 1.0, (H, W, 4)).astype('f4')
buffer_a = context.buffer(buffer_a_data)
buffer_b_data = np.zeros((H, W, 4)).astype('f4')
buffer_b = context.buffer(buffer_b_data)

imgs = []
last_buffer = buffer_b
for i in range(FRAMES):
    toggle = True if i % 2 else False
    buffer_a.bind_to_storage_buffer(1 if toggle else 0)
    buffer_b.bind_to_storage_buffer(0 if toggle else 1)

    # toggle 2 buffers as input and output
github moderngl / moderngl / examples / window_tkinter.py View on Github external
import tkinter as tk

import moderngl
import numpy as np

from tkinter_framebuffer import FramebufferImage
from renderer_example import HelloWorld2D, PanTool

ctx = moderngl.create_standalone_context()

canvas = HelloWorld2D(ctx)
pan_tool = PanTool()


def vertices():
    x = np.linspace(-1.0, 1.0, 50)
    y = np.random.rand(50) - 0.5
    r = np.ones(50)
    g = np.zeros(50)
    b = np.zeros(50)
    a = np.ones(50)
    return np.dstack([x, y, r, g, b, a])


verts = vertices()
github moderngl / moderngl-window / moderngl_window / context / headless / window.py View on Github external
def init_mgl_context(self) -> None:
        """Create an standalone context and framebuffer"""
        self._ctx = moderngl.create_standalone_context(require=self.gl_version_code)
        self._fbo = self.ctx.framebuffer(
            color_attachments=self.ctx.texture(self.size, 4, samples=self._samples),
            depth_attachment=self.ctx.depth_texture(self.size, samples=self.samples),
        )
        self.use()