Beispiel #1
0
    def __init__(self, title, width, height):

        settings.WINDOW['class'] = 'moderngl_window.context.glfw.Window'
        settings.WINDOW['gl_version'] = (4, 6)
        settings.WINDOW['size'] = (width, height)
        settings.WINDOW['aspect_ratio'] = width / height
        settings.WINDOW['title'] = title
        settings.WINDOW['resizable'] = True
        settings.WINDOW['vsync'] = True

        path = os.path.abspath(__file__)
        dirPath = os.path.dirname(os.path.dirname(path))
        resources.register_dir(os.path.normpath(dirPath))

        self.wnd = moderngl_window.create_window_from_settings()
        self.ctx = self.wnd.ctx
        self.wnd.key_event_func = self.key_event
        self.wnd.mouse_press_event_func = self.mouse_press_event
        self.wnd.mouse_release_event_func = self.mouse_release_event
        self.wnd.position = (1640 - self.wnd.size[0]) // 2, (
            1140 - self.wnd.size[1]) // 2
        self.height = height
        self.width = width
        self.frames = 0
        self.oldTime = 0

        self.wnd.set_icon('resources/icon.png')
        self.camera = camera.Camera(self.wnd.keys)
Beispiel #2
0
    def __init__(self,
                 ctx: moderngl.Context = None,
                 wnd: BaseWindow = None,
                 timer: BaseTimer = None,
                 **kwargs):
        """Initialize the window config

        Keyword Args:
            ctx (moderngl.Context): The moderngl context
            wnd: The window instance
            timer: The timer instance
        """
        self.ctx = ctx
        self.wnd = wnd
        self.timer = timer

        if self.resource_dir:
            resources.register_dir(Path(self.resource_dir).resolve())

        if not self.ctx or not isinstance(self.ctx, moderngl.Context):
            raise ValueError(
                "WindowConfig requires a moderngl context. ctx={}".format(
                    self.ctx))

        if not self.wnd or not isinstance(self.wnd, BaseWindow):
            raise ValueError("WindowConfig requires a window. wnd={}".format(
                self.wnd))
Beispiel #3
0
 def test_reister_path_duplicates(self):
     """Ensure search path only occur once if registered multipel times"""
     with settings_context(self.settings):
         resources.register_dir(self.absolute_path)
         resources.register_dir(self.absolute_path)
         resources.register_dir(self.absolute_path)
         self.assertEqual(len(settings.DATA_DIRS), 1)
Beispiel #4
0
from pyrr import matrix44

from pathlib import Path

import moderngl
from moderngl_window.opengl.vao import VAO
from moderngl_window import resources
from moderngl_window.meta import (
    DataDescription,
    TextureDescription,
    ProgramDescription,
)

from .base import BaseText, FontMeta

resources.register_dir(Path(__file__).parent.resolve())


class TextWriter2D(BaseText):
    """Simple monspaced bitmapped text renderer"""
    def __init__(self):
        super().__init__()

        meta = FontMeta(
            resources.data.load(
                DataDescription(path="bitmapped/text/meta.json")))
        self._texture = resources.textures.load(
            TextureDescription(
                path="bitmapped/textures/VeraMono.png",
                kind="array",
                mipmap=True,
from pathlib import Path

import moderngl
from headless import HeadlessTestCase
from moderngl_window import resources
from moderngl_window.meta import TextureDescription
from moderngl_window.exceptions import ImproperlyConfigured

resources.register_dir(
    (Path(__file__).parent / 'fixtures' / 'resources').resolve())


class TextureLoadersTestCase(HeadlessTestCase):
    window_size = (16, 16)
    aspect_ratio = 1.0

    def test_texture_2d(self):
        """Load standard 2d texture"""
        texture = resources.textures.load(
            TextureDescription(path='textures/crate.png'))
        self.assertEqual(texture.size, (192, 192))
        self.assertIsInstance(texture.extra.get('meta'), TextureDescription)

    def test_texture_2d_8bit(self):
        """Test loading 8 bit texture with palette"""
        texture = resources.textures.load(
            TextureDescription(path='textures/8bit.png'))
        self.assertIsInstance(texture, moderngl.Texture)

    def test_texture_not_found(self):
        """Ensure ImproperlyConfigured is raised if texture is not found"""
Beispiel #6
0
 def test_register_file(self):
     """Attempt to register a file as a search path"""
     with settings_context(self.settings):
         with self.assertRaises(ImproperlyConfigured):
             resources.register_dir(self.file_path)
Beispiel #7
0
 def test_non_dir(self):
     """Register nonexistent path"""
     with settings_context(self.settings):
         with self.assertRaises(ImproperlyConfigured):
             resources.register_dir(self.nonexist_path)
Beispiel #8
0
 def test_relative_path(self):
     """Raise error if relative path is passed"""
     with settings_context(self.settings):
         with self.assertRaises(ImproperlyConfigured):
             resources.register_dir(self.relative_path)
Beispiel #9
0
import math
from pathlib import Path
from pyrr import matrix44

from moderngl_window import resources
from moderngl_window.meta import ProgramDescription
from track import EventType

RESOURCE_DIR = Path(__file__).parent.resolve() / 'resources'
resources.register_dir(RESOURCE_DIR)


class BSScene:
    def __init__(self, scene, camera, track):
        self.scene = scene
        self.track = track
        self.camera = camera

        static_color = 0.01, 0.01, 0.01, 1.0

        # light/laser shaders
        self.light_static_prog = resources.programs.load(
            ProgramDescription(path='programs/light_static.glsl'))
        self.laser_prog = resources.programs.load(
            ProgramDescription(path='programs/laser.glsl'))

        self.highway = self.scene.find_node('Highway')
        self.highway.mesh.material.color = static_color

        # Inner rings
        self.inner_ring_prog = resources.programs.load(
    def __init__(self,
                 lines=None,
                 line_colors=None,
                 lw=1,
                 points=None,
                 point_colors=None,
                 point_r=1):
        self.point_r = point_r
        # Configure to use pyglet window
        window_str = 'moderngl_window.context.pyglet.Window'
        window_cls = moderngl_window.get_window_cls(window_str)
        window = window_cls(
            title="My Window",
            gl_version=(3, 3),
            # aspect_ratio=1.0,
            # resizable=False,
            # size=(1600, 800),
        )
        self.wnd = window
        moderngl_window.activate_context(ctx=window.ctx)
        # self.wnd.gl_version = (3, 3)
        resources.register_dir(Path(__file__).parent.absolute())
        self.ctx = self.wnd.ctx

        # register event methods
        self.wnd.resize_func = self.resize
        # self.wnd.iconify_func = self.iconify
        # self.wnd.key_event_func = self.key_event
        # self.wnd.mouse_position_event_func = self.mouse_position_event
        # self.wnd.mouse_drag_event_func = self.mouse_drag_event
        # self.wnd.mouse_scroll_event_func = self.mouse_scroll_event
        # self.wnd.mouse_press_event_func = self.mouse_press_event
        # self.wnd.mouse_release_event_func = self.mouse_release_event
        # self.wnd.unicode_char_entered_func = self.unicode_char_entered

        self.line_prog = programs.load(
            ProgramDescription(path="rich_lines.glsl"))
        self.point_prog = programs.load(ProgramDescription(path="points.glsl"))

        bbox = drawing_bbox(lines + points)
        bbox = drawing_bbox(lines + points, padding=0.05 * bbox[2])
        self.bbox = bbox
        self.drawing_W = bbox[2]
        self.drawing_H = bbox[3]

        if len(lines) > 0:
            vertex, index, colors = build_buffers(lines, line_colors)

            vbo = self.ctx.buffer(vertex)
            ibo = self.ctx.buffer(index)
            cbo = self.ctx.buffer(colors)
            self.line_vao = self.ctx.vertex_array(self.line_prog, [
                (vbo, "2f", "in_position"),
                (cbo, "4f", "in_color"),
            ],
                                                  index_buffer=ibo)
        else:
            self.line_vao = None

        if len(points) > 0:
            point_vertex, point_color = build_point_buffers(
                points, point_colors)
            vbo = self.ctx.buffer(point_vertex)
            cbo = self.ctx.buffer(point_color)
            self.point_vao = self.ctx.vertex_array(self.point_prog, [
                (vbo, "2f", "in_position"),
                (cbo, "4f", "in_color"),
            ])
        else:
            self.point_vao = None

        # Set the desired properties for the lines.
        # Note:
        # - round cap/ends are used if miter_limit < 0
        # - antialias value is in model space and should probably be scaled to be ~1.5px in
        #   screen space

        self.line_prog["linewidth"].value = lw
        self.line_prog["antialias"].value = 1.5
        self.line_prog["miter_limit"].value = -1
        # self.line_prog["color"].value = 0, 0, 0, 1

        self.update_projection()
Beispiel #11
0
from moderngl_window import resources
from pathlib import Path
from typing import Any, Tuple

import datetime
import moderngl_window as mglw
import numpy as np

resources.register_dir((Path(__file__).parent / "resources").resolve())


class FakeUniform:
    def __init__(self, value: Any) -> None:
        self.value = value


class NPS(mglw.WindowConfig):
    title: str = "Nano Pixel Shader"
    gl_version: Tuple[int, int] = (3, 3)
    window_size: Tuple[int, int] = (1280, 720)
    aspect_ratio: float = 16 / 9
    vsync: bool = False
    resizable: bool = False
    samples: int = 8

    def __init__(self, program: str, *args, **kwargs) -> None:
        super(NPS, self).__init__(*args, **kwargs)
        program = self.load_program(program)

        faces = np.array([0, 1, 2, 1, 2, 3], dtype=np.int32)
        verts = np.array(
Beispiel #12
0
    def mode(self, window_class, msaa=1, vsync=True, strict=False, icon=None):
        debug_prefix = "[MMVShaderMGLWindowHandlers.mode]"

        logging.info(
            f"{debug_prefix} \"i\" Set window mode [window_class={window_class}] [msaa={msaa}] [vsync={vsync}] [strict={strict}] [icon={icon}]"
        )

        # Get function arguments
        self.headless = window_class == "headless"
        self.strict = strict
        self.vsync = vsync
        self.msaa = msaa

        # Headless we disable vsync because we're rendering only..?
        # And also force aspect ratio just in case (strict option)
        if self.headless:
            self.strict = True
            self.vsync = False

        # Assign the function arguments
        settings.WINDOW[
            "class"] = f"moderngl_window.context.{window_class}.Window"
        settings.WINDOW[
            "aspect_ratio"] = self.mmv_shader_mgl.width / self.mmv_shader_mgl.height
        settings.WINDOW["vsync"] = self.vsync
        settings.WINDOW["title"] = "MMVShaderMGL Real Time Window"
        settings.WINDOW["size"] = (self.mmv_shader_mgl.width,
                                   self.mmv_shader_mgl.height)

        # Create the window
        self.window = moderngl_window.create_window_from_settings()

        # Make sure we render strictly into the resolution we asked
        if strict:
            self.window.fbo.viewport = (0, 0, self.mmv_shader_mgl.width,
                                        self.mmv_shader_mgl.height)
            # self.window.set_default_viewport()

        # Set the icon
        if icon is not None:
            # Absolute path
            icon = Path(icon).resolve()
            resources.register_dir(icon.parent)
            self.window.set_icon(icon_path=icon.name)

        # The context we'll use is the one from the window
        self.gl_context = self.window.ctx
        self.mmv_shader_mgl.gl_context = self.gl_context
        self.window_should_close = False

        # Functions of the window if not headless
        if not self.headless:
            self.window.resize_func = self.window_resize
            self.window.key_event_func = self.key_event
            self.window.mouse_position_event_func = self.mouse_position_event
            self.window.mouse_drag_event_func = self.mouse_drag_event
            self.window.mouse_scroll_event_func = self.mouse_scroll_event
            self.window.mouse_press_event_func = self.mouse_press_event
            self.window.mouse_release_event_func = self.mouse_release_event
            self.window.unicode_char_entered_func = self.unicode_char_entered
            self.window.close_func = self.close
            imgui.create_context()
            self.imgui = ModernglWindowRenderer(self.window)
Beispiel #13
0
from pathlib import Path

import moderngl_window
from moderngl_window.resources import programs
from moderngl_window import geometry
from moderngl_window import resources
from moderngl_window.finders.program import FilesystemFinder

# Register system resource directory in this package
resources.register_dir(Path(__file__).parent / 'resources')


class ShaderToyWindow(moderngl_window.WindowConfig):
    title = "Python Shadertoy"
    resource_dir = Path(__file__).parent
    # Don't enforce a specific aspect ratio
    aspect_ratio = None
    main_program = None

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._main_program_mtime = 0
        self._main_program_path = FilesystemFinder().find(
            Path(self.main_program))
        self._main_program = None
        self.load_main_program()

        self._quad_fs = geometry.quad_fs()

        self._fallback_program = self.load_program(
            'shadertoy/programs/fallback.glsl')