Skip to content

Commit

Permalink
Rename callback functions (on_ prefix) (#203)
Browse files Browse the repository at this point in the history
* Rename callback functions (on_ prefix)

* Lingering import

* Update CHANGELOG

* basic docs + example

* Deleted setup.cfg

* docs: install

* type and test fixes

* typos

* More formatting

* Clarify on_close

* Example tweaks
  • Loading branch information
einarf authored Nov 28, 2024
1 parent e215368 commit 6ef9bff
Show file tree
Hide file tree
Showing 69 changed files with 498 additions and 529 deletions.
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@

## 3.0.0

* All callback functions now has an `on_` prefix meaning existing code will need updating. The old names was somewhat unambiguous and was a source of confusion. It also makes it easier to separate the callback functions from other methods.
* `render` -> `on_render`
* `resize` -> `on_resize`
* `close` -> `on_close`
* `iconify` -> `on_iconify`
* `key_event` -> `on_key_event`
* `mouse_position_event` -> `on_mouse_position_event`
* `mouse_press_event` -> `on_mouse_press_event`
* `mouse_release_event` -> `on_mouse_release_event`
* `mouse_drag_event` -> `on_mouse_drag_event`
* `mouse_scroll_event` -> `on_mouse_scroll_event`
* `unicode_char_entered` -> `on_unicode_char_entered`
* `files_dropped_event` -> `on_files_dropped_event`
* Pyrr is now replaced with PyGLM
* imgui is replaced with imgui-bundle
* Numpy version is no longer restricted
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ import moderngl_window as mglw
class Test(mglw.WindowConfig):
gl_version = (3, 3)

def render(self, time, frametime):
def on_render(self, time: float, frametime: float):
self.ctx.clear(1.0, 0.0, 0.0, 0.0)

Test.run()
Expand Down
26 changes: 13 additions & 13 deletions docs/guide/basic_usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,12 @@ and access simpler shortcut methods for loading resources.
self.vao = self.ctx.vertex_array(...)
self.texture = self.ctx.texture(self.wnd.size, 4)
def render(self, time, frametime):
def on_render(self, time: float, frametime: float):
# This method is called every frame
self.vao.render()
# Blocking call entering rendering/event loop
mglw.run_window_config(Test)
Test.run()
The :py:class:`~moderngl_window.context.base.window.WindowConfig`
instance will by default receive three external instances in ``__init__``
Expand Down Expand Up @@ -125,24 +125,24 @@ Window events

.. code:: python
def resize(self, width: int, height: int):
def on_resize(self, width: int, height: int):
print("Window was resized. buffer size is {} x {}".format(width, height))
def close(self):
def on_close(self):
print("The window is closing")
def iconify(self, iconify: bool):
def on_iconify(self, iconify: bool):
print("Window was iconified:", iconify)
Keyboard input
--------------

Implement the ``key_event`` and ``unicode_char_entered`` method to handle
Implement the ``on_key_event`` and ``on_unicode_char_entered`` method to handle
key events.

.. code:: python
def key_event(self, key, action, modifiers):
def on_key_event(self, key, action, modifiers):
# Key presses
if action == self.wnd.keys.ACTION_PRESS:
if key == self.wnd.keys.SPACE:
Expand All @@ -161,7 +161,7 @@ key events.
if key == self.wnd.keys.SPACE:
print("SPACE key was released")
def unicode_char_entered(self, char: str):
def on_unicode_char_entered(self, char: str):
print('character entered:', char)
Expand All @@ -172,17 +172,17 @@ Implement the ``mouse_*`` methods to handle mouse input.

.. code:: python
def mouse_position_event(self, x, y, dx, dy):
def on_mouse_position_event(self, x, y, dx, dy):
print("Mouse position:", x, y, dx, dy)
def mouse_drag_event(self, x, y, dx, dy):
def on_mouse_drag_event(self, x, y, dx, dy):
print("Mouse drag:", x, y, dx, dy)
def mouse_scroll_event(self, x_offset: float, y_offset: float):
def on_mouse_scroll_event(self, x_offset: float, y_offset: float):
print("Mouse wheel:", x_offset, y_offset)
def mouse_press_event(self, x, y, button):
def on_mouse_press_event(self, x, y, button):
print("Mouse button {} pressed at {}, {}".format(button, x, y))
def mouse_release_event(self, x: int, y: int, button: int):
def on_mouse_release_event(self, x: int, y: int, button: int):
print("Mouse button {} released at {}, {}".format(button, x, y))
14 changes: 11 additions & 3 deletions docs/guide/install.rst
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,19 @@ Optional dependencies for loaders::
# STL loading
pip install moderngl-window[trimesh]

imgui::

# imgui-bundle
pip install moderngl-window[imgui]

Installing dependencies for window types::

pip install moderngl-window[glfw]
pip install moderngl-window[pygame-ce]
pip install moderngl-window[pygame]
pip install moderngl-window[tk]
pip install moderngl-window[PySide2]
pip install moderngl-window[pyqt5]
pip install moderngl-window[glfw]
pip install moderngl-window[PySDL2]

Installing optional dependencies this way should ensure
Expand Down Expand Up @@ -78,6 +86,6 @@ Running tests

Assuming dev requirements are installed.

Run tests with ``tox``::
Run tests with ``pytest``::

pytest
pytest tests
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
"""
Loads two gif files into texture arrays and renders them into an offscreen buffer
that is then displayed on the screen using nearest neighbor filtering.
Possible improvements:
- Make the example configurable to load any gif file(s)
- Load the raw byte data for each frame and instead use a palette texture to
reduce the memory footprint
- Take the gif transparency key into account?
"""

from pathlib import Path

import glm
Expand All @@ -6,12 +17,8 @@
import moderngl_window as mglw
from moderngl_window import geometry

# from moderngl_window.conf import settings
# settings.SCREENSHOT_PATH = 'screenshots'
# from moderngl_window import screenshot


class Test(mglw.WindowConfig):
class AnimatedGif(mglw.WindowConfig):
title = "Animated Sprite"
resource_dir = (Path(__file__) / "../../resources").resolve()
aspect_ratio = 320 / 256
Expand All @@ -21,13 +28,12 @@ def __init__(self, **kwargs):
super().__init__(**kwargs)
self.buffer_size = 320, 256
# Textures
self.background_texture = self.load_texture_array(
"textures/animated_sprites/giphy.gif"
)
self.background_texture = self.load_texture_array("textures/animated_sprites/giphy.gif")
self.background_texture.repeat_x = False
self.background_texture.repeat_y = False
self.caveman_texture = self.load_texture_array(
"textures/animated_sprites/player_2.gif", layers=35
"textures/animated_sprites/player_2.gif",
layers=35, # Number of frames in the gif
)
self.caveman_texture.repeat_x = False
self.caveman_texture.repeat_y = False
Expand All @@ -39,22 +45,18 @@ def __init__(self, **kwargs):
self.quad_fs = geometry.quad_fs()

# Programs
self.sprite_program = self.load_program(
"programs/animated_sprites/sprite_array.glsl"
)
self.sprite_program = self.load_program("programs/animated_sprites/sprite_array.glsl")
self.texture_program = self.load_program("programs/texture.glsl")

# Offscreen buffer
self.offscreen_texture = self.ctx.texture(self.buffer_size, 4)
self.offscreen_texture.filter = moderngl.NEAREST, moderngl.NEAREST
self.offscreen = self.ctx.framebuffer(
color_attachments=[self.offscreen_texture]
)
self.offscreen = self.ctx.framebuffer(color_attachments=[self.offscreen_texture])

self.projection = glm.ortho(0, 320, 0, 256, -1.0, 1.0)
self.sprite_program["projection"].write(self.projection)

def render(self, time, frame_time):
def on_render(self, time, frame_time):
# Render sprite of offscreen
self.offscreen.use()
self.ctx.clear(0.5, 0.5, 0.5, 0.0)
Expand All @@ -75,10 +77,7 @@ def render(self, time, frame_time):
self.offscreen_texture.use(location=0)
self.quad_fs.render(self.texture_program)

# if self.wnd.frames < 100:
# screenshot.create(self.ctx.screen)

def render_sprite(self, texture, blend=False, frame=0, position=(0, 0)):
def render_sprite(self, texture: moderngl.TextureArray, blend=False, frame=0, position=(0, 0)):
if blend:
self.ctx.enable(moderngl.BLEND)

Expand All @@ -92,5 +91,4 @@ def render_sprite(self, texture, blend=False, frame=0, position=(0, 0)):


if __name__ == "__main__":
mglw.run_window_config(Test)
# Test.run()
AnimatedGif.run()
6 changes: 3 additions & 3 deletions examples/advanced/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def __init__(self, **kwargs):
self.camera = KeyboardCamera(self.wnd.keys, aspect_ratio=self.wnd.aspect_ratio)
self.camera_enabled = True

def key_event(self, key, action, modifiers):
def on_key_event(self, key, action, modifiers):
keys = self.wnd.keys

if self.camera_enabled:
Expand All @@ -24,9 +24,9 @@ def key_event(self, key, action, modifiers):
if key == keys.SPACE:
self.timer.toggle_pause()

def mouse_position_event(self, x: int, y: int, dx, dy):
def on_mouse_position_event(self, x: int, y: int, dx, dy):
if self.camera_enabled:
self.camera.rot_state(-dx, -dy)

def resize(self, width: int, height: int):
def on_resize(self, width: int, height: int):
self.camera.projection.update(aspect_ratio=self.wnd.aspect_ratio)
17 changes: 9 additions & 8 deletions examples/advanced/compute_render_to_texture.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,30 @@

class ComputeRenderToTexture(mglw.WindowConfig):
"""Simple example rendering to a texture with a compute shader"""

title = "Render Texture Using Compute Shader"
resource_dir = (Path(__file__) / '../../resources').resolve()
resource_dir = (Path(__file__) / "../../resources").resolve()
gl_version = 4, 3
aspect_ratio = 1.0

def __init__(self, **kwargs):
super().__init__(**kwargs)
self.compute_shader = self.load_compute_shader('programs/compute/render_to_texture.glsl')
self.compute_shader['destTex'] = 0
self.texture_program = self.load_program('programs/texture.glsl')
self.compute_shader = self.load_compute_shader("programs/compute/render_to_texture.glsl")
self.compute_shader["destTex"] = 0
self.texture_program = self.load_program("programs/texture.glsl")
self.quad_fs = geometry.quad_fs()
self.texture = self.ctx.texture((256, 256), 4)
self.texture.filter = mgl.NEAREST, mgl.NEAREST

def render(self, time, frame_time):
def on_render(self, time, frame_time):
self.ctx.clear(0.3, 0.3, 0.3)

w, h = self.texture.size
gw, gh = 16, 16
nx, ny, nz = int(w / gw), int(h / gh), 1

try:
self.compute_shader['time'] = time
self.compute_shader["time"] = time
except Exception:
pass
# Automatically binds as a GL_R32F / r32f (read from the texture)
Expand All @@ -42,5 +43,5 @@ def render(self, time, frame_time):
self.quad_fs.render(self.texture_program)


if __name__ == '__main__':
mglw.run_window_config(ComputeRenderToTexture)
if __name__ == "__main__":
ComputeRenderToTexture.run()
21 changes: 11 additions & 10 deletions examples/advanced/fragment_picking.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def __init__(self, **kwargs):

# Load scene cached to speed up loading!
self.scene = self.load_scene("scenes/fragment_picking/centered.obj", cache=True)
# Grab the raw mesh/vertexarray
# Grab the raw mesh/vertex array
self.mesh = self.scene.root_nodes[0].mesh.vao
self.mesh_texture = self.scene.root_nodes[0].mesh.material.mat_texture.texture

Expand Down Expand Up @@ -117,7 +117,7 @@ def __init__(self, **kwargs):
# Marker geometry
self.marker_buffer = self.ctx.buffer(
reserve=self.marker_byte_size * 1000
) # Resever room for 1000 points
) # Reserve room for 1000 points
self.marker_vao = VAO(name="markers", mode=moderngl.POINTS)
self.marker_vao.buffer(
self.marker_buffer, "3f 3f 1f", ["in_position", "in_normal", "temperature"]
Expand All @@ -129,7 +129,7 @@ def __init__(self, **kwargs):
self.quad_depth = geometry.quad_2d(size=(0.25, 0.25), pos=(0.5, 0.875))
self.quad_positions = geometry.quad_2d(size=(0.25, 0.25), pos=(0.25, 0.875))

def render(self, time, frametime):
def on_render(self, time: float, frametime: float):
self.ctx.enable(moderngl.DEPTH_TEST | moderngl.CULL_FACE)

translation = glm.translate(glm.vec3(0, 0, -45 + self.zoom))
Expand Down Expand Up @@ -179,12 +179,12 @@ def render_debug(self):
self.offscreen_viewpos.use()
self.quad_positions.render(self.texture_program)

def mouse_drag_event(self, x, y, dx, dy):
def on_mouse_drag_event(self, x, y, dx, dy):
"""Pick up mouse drag movements"""
self.x_rot -= dx / 100
self.y_rot -= dy / 100

def mouse_press_event(self, x, y, button):
def on_mouse_press_event(self, x, y, button):
"""Attempts to get the view position from a fragment"""

# only care about right mouse button clicks
Expand All @@ -193,8 +193,9 @@ def mouse_press_event(self, x, y, button):

# mouse coordinates starts in upper left corner
# pixel positions starts and lower left corner
pos = int(x * self.wnd.pixel_ratio), int(
self.wnd.buffer_height - (y * self.wnd.pixel_ratio)
pos = (
int(x * self.wnd.pixel_ratio),
int(self.wnd.buffer_height - (y * self.wnd.pixel_ratio)),
)
print("Picking mouse position", x, y)
print("Viewport position", pos)
Expand All @@ -220,10 +221,10 @@ def mouse_press_event(self, x, y, button):
)
self.num_markers += 1

def mouse_scroll_event(self, x_offset, y_offset):
def on_mouse_scroll_event(self, x_offset, y_offset):
self.zoom += y_offset

def key_event(self, key, action, modifiers):
def on_key_event(self, key, action, modifiers):
keys = self.wnd.keys

# Key presses
Expand Down Expand Up @@ -256,4 +257,4 @@ def save_markers(self, path: Path):


if __name__ == "__main__":
moderngl_window.run_window_config(FragmentPicking)
FragmentPicking.run()
Loading

0 comments on commit 6ef9bff

Please sign in to comment.