Skip to content

Commit

Permalink
Pyglet2.1dev$VERSION updates (pythonarcade#2226)
Browse files Browse the repository at this point in the history
* Bump to pyglet == 2.1dev3

* Remove del trick for getting future vec behavior

* Update to options object

* Switch arcade/__init__.py to use OOP options object

* Convert applications.py to OOP pyglet options

* Convert doc on headless to use options object

* Fix a comment in arcade/__init__.py

* Update tests/__init__.py

* Fix formatting

* Type compatibility fix in controller db loading

* Use pyglet.media.Source instead of a Union type

* Fix color typing in arcade.Text

* Ignore over-strict pyright Literal opinion

* Attempt to patch up the font loader

* Use new-style | None in application.Window.__init__

* Update some typing for  set_fullscreen

* Use new-style | None

* Add casting and TODO on resolving screen coord issues upstream

* Mention rounding issue in set_fullscreen

* Add temporary type ignore for font_size

* Update type + doc for arcade.text bold support

* Update top-level docstring

* Update bold setter & getter

* Update bold return types

* Temporarily use pyglet development branch directly

* Use development pyglet in rolling release mode + comment it

* Add commented-out future pyglet == 2.1dev4 release we can swap to it later

* Formatting

* Use newly released pyglet==2.1dev4

* Projection funcs: remove inner tuple for Mat4 init

* add dot to pyproject.toml (no idea why pip resolves that)

* Use Vec3 for now in perspective example

* Centralize headless + add some type: ignore

* Centralize headless

* Add some type: ignore since pyglet did vague .pyi

* type: ignore in sound.py

* Whoops, forgot what file I'm in

* Replace todo with # type: ignore # pending syntax

* Awful temp fix for Text.font_name

* Formatting for sound

* Abomination of a test fix

* Import sorting for arcade/__init__.py

* Revert "Abomination of a test fix" (Test not actually fixed)

This reverts commit c59d674.

* Maybe fix the import test?

* Temp fix for pyglet typing all things as float for some reason

* Fix another instance of pyglet making everything a float

* Out of patience for pyglet import / metaclass / method resolution

* Fix rebase issue in casting

* Type ignore window issues

* Tweak pyproject.toml

* Ignore pyglet Window type

The class is dynamically assigned at runtime
so pyright can't handle it.

* Wrong typing for screen

* format issue

* Bump pyright

* Temp ignore EventDispatcher issue

---------

Co-authored-by: Einar Forselv <[email protected]>
  • Loading branch information
pushfoo and einarf authored Jul 18, 2024
1 parent e15946b commit 6e8259d
Show file tree
Hide file tree
Showing 18 changed files with 140 additions and 98 deletions.
29 changes: 11 additions & 18 deletions arcade/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
# Error out if we import Arcade with an incompatible version of Python.
import sys
import os
from typing import Optional
from typing import Final, Optional

from pathlib import Path

Expand Down Expand Up @@ -58,29 +58,21 @@ def configure_logging(level: Optional[int] = None):
# noinspection PyPep8
import pyglet

# TODO: Remove ASAP after pyglet >= 2.1dev2 is out
if pyglet.version == "2.1.dev2":
# Temporary monkeypatch via deletion since dev2 still includes
# overly-specific __eq__ behavior. Later pyglet commits restore
# equality with same-valued tuples by deleting the __eq__ methods.
from pyglet import math as _pyglet_math

del _pyglet_math.Vec2.__eq__
del _pyglet_math.Vec3.__eq__
del _pyglet_math.Vec4.__eq__

# Env variable shortcut for headless mode
if os.environ.get("ARCADE_HEADLESS"):
pyglet.options["headless"] = True
headless: Final[bool] = bool(os.environ.get("ARCADE_HEADLESS"))
if headless:
pyglet.options.headless = headless # type: ignore # pending https://github.com/pyglet/pyglet/issues/1164


from arcade import utils

# Disable shadow window on macs and in headless mode.
if sys.platform == "darwin" or os.environ.get("ARCADE_HEADLESS") or utils.is_raspberry_pi():
pyglet.options["shadow_window"] = False
pyglet.options.shadow_window = False # type: ignore # pending https://github.com/pyglet/pyglet/issues/1164

# Use the old gdi fonts on windows until directwrite is fast/stable
# pyglet.options['win32_gdi_font'] = True
# pyglet.options.win32_gdi_font = True

# Imports from modules that don't do anything circular

Expand Down Expand Up @@ -152,7 +144,7 @@ def configure_logging(level: Optional[int] = None):
from .screenshot import get_pixel

# We don't have joysticks game controllers in headless mode
if not pyglet.options["headless"]:
if not headless: # type: ignore
from .joysticks import get_game_controllers
from .joysticks import get_joysticks
from .controller import ControllerManager
Expand Down Expand Up @@ -407,11 +399,12 @@ def configure_logging(level: Optional[int] = None):
# Piggyback on pyglet's doc run detection
if not getattr(sys, "is_pyglet_doc_run", False):
# Load additional game controller mappings to Pyglet
if not pyglet.options["headless"]:
if not headless:
try:
import pyglet.input.controller

mappings_file = resources.resolve(":system:gamecontrollerdb.txt")
pyglet.input.controller.add_mappings_from_file(mappings_file)
# TODO: remove string conversion once fixed upstream
pyglet.input.controller.add_mappings_from_file(str(mappings_file))
except AssertionError:
pass
49 changes: 29 additions & 20 deletions arcade/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,14 +132,14 @@ def __init__(
self,
width: int = 1280,
height: int = 720,
title: Optional[str] = "Arcade Window",
title: str | None = "Arcade Window",
fullscreen: bool = False,
resizable: bool = False,
update_rate: float = 1 / 60,
antialiasing: bool = True,
gl_version: tuple[int, int] = (3, 3),
screen: Optional[pyglet.display.Screen] = None,
style: Optional[str] = pyglet.window.Window.WINDOW_STYLE_DEFAULT,
screen: pyglet.display.Screen | None = None,
style: str | None = pyglet.window.Window.WINDOW_STYLE_DEFAULT,
visible: bool = True,
vsync: bool = False,
gc_mode: str = "context_gc",
Expand All @@ -149,7 +149,7 @@ def __init__(
gl_api: str = "gl",
draw_rate: float = 1 / 60,
fixed_rate: float = 1.0 / 60.0,
fixed_frame_cap: Optional[int] = None,
fixed_frame_cap: int | None = None,
) -> None:
# In certain environments we can't have antialiasing/MSAA enabled.
# Detect replit environment
Expand All @@ -161,7 +161,7 @@ def __init__(
gl_version = 3, 1
gl_api = "gles"

self.headless: bool = pyglet.options.get("headless") is True
self.headless: bool = arcade.headless
"""If True, the window is running in headless mode."""

config = None
Expand All @@ -171,7 +171,7 @@ def __init__(
config = pyglet.gl.Config(
major_version=gl_version[0],
minor_version=gl_version[1],
opengl_api=gl_api,
opengl_api=gl_api, # type: ignore # pending: upstream fix
double_buffer=True,
sample_buffers=1,
samples=samples,
Expand All @@ -183,7 +183,7 @@ def __init__(
alpha_size=8,
)
display = pyglet.display.get_display()
screen = display.get_default_screen()
screen = display.get_default_screen() # type: ignore # pending: resolve upstream type tricks
if screen:
config = screen.get_best_config(config)
except pyglet.window.NoSuchConfigException:
Expand All @@ -195,7 +195,7 @@ def __init__(
config = pyglet.gl.Config(
major_version=gl_version[0],
minor_version=gl_version[1],
opengl_api=gl_api,
opengl_api=gl_api, # type: ignore # pending: upstream fix
double_buffer=True,
depth_size=24,
stencil_size=8,
Expand All @@ -215,9 +215,10 @@ def __init__(
visible=visible,
style=style,
)
self.register_event_type("on_update")
self.register_event_type("on_action")
self.register_event_type("on_fixed_update")
# pending: weird import tricks resolved
self.register_event_type("on_update") # type: ignore
self.register_event_type("on_action") # type: ignore
self.register_event_type("on_fixed_update") # type: ignore
except pyglet.window.NoSuchConfigException:
raise NoOpenGLException(
"Unable to create an OpenGL 3.3+ context. "
Expand Down Expand Up @@ -291,7 +292,7 @@ def __init__(
if enable_polling:
self.keyboard = pyglet.window.key.KeyStateHandler()

if pyglet.options["headless"]:
if arcade.headless:
self.push_handlers(self.keyboard)

else:
Expand Down Expand Up @@ -412,10 +413,10 @@ def close(self) -> None:
def set_fullscreen(
self,
fullscreen: bool = True,
screen: Optional["Window"] = None,
mode: Optional[ScreenMode] = None,
width: Optional[int] = None,
height: Optional[int] = None,
screen=None,
mode: ScreenMode | None = None,
width: float | None = None,
height: float | None = None,
) -> None:
"""
Change the fullscreen status of the window.
Expand All @@ -438,10 +439,18 @@ def set_fullscreen(
have been obtained by enumerating `Screen.get_modes`. If
None, an appropriate mode will be selected from the given
`width` and `height`.
width (int, optional): Override the width of the window
height (int, optional): Override the height of the window
"""
super().set_fullscreen(fullscreen, screen, mode, width, height)
width: Override the width of the window. Will be rounded to
:py:attr:`int`.
height: Override the height of the window. Will be rounded to
:py:attr:`int`.
"""
# fmt: off
super().set_fullscreen(
fullscreen, screen, mode,
# TODO: resolve the upstream int / float screen coord issue
None if width is None else int(width),
None if height is None else int(height))
# fmt: on

def center_window(self) -> None:
"""Center the window on your desktop."""
Expand Down
12 changes: 6 additions & 6 deletions arcade/camera/projection_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@ def generate_view_matrix(camera_data: CameraData) -> Mat4:
po = Vec3(*camera_data.position)

# fmt: off
return Mat4((
return Mat4(
ri.x, up.x, -fo.x, 0.0,
ri.y, up.y, -fo.y, 0.0,
ri.z, up.z, -fo.z, 0.0,
-ri.dot(po), -up.dot(po), fo.dot(po), 1.0
))
)
# fmt: on


Expand Down Expand Up @@ -69,12 +69,12 @@ def generate_orthographic_matrix(
tz = -(z_far + z_near) / depth

# fmt: off
return Mat4((
return Mat4(
sx, 0.0, 0.0, 0.0,
0.0, sy, 0.0, 0.0,
0.0, 0.0, sz, 0.0,
tx, ty, tz, 1.0
))
)
# fmt: on


Expand Down Expand Up @@ -110,12 +110,12 @@ def generate_perspective_matrix(
h = 2 * z_near / height

# fmt: off
return Mat4((
return Mat4(
w, 0, 0, 0,
0, h, 0, 0,
0, 0, q, -1,
0, 0, qn, 0
))
)
# fmt: on


Expand Down
5 changes: 4 additions & 1 deletion arcade/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,10 @@ class ArcadeContext(Context):
atlas_size: tuple[int, int] = 512, 512

def __init__(
self, window: pyglet.window.Window, gc_mode: str = "context_gc", gl_api: str = "gl"
self,
window: pyglet.window.Window, # type: ignore
gc_mode: str = "context_gc",
gl_api: str = "gl",
) -> None:
super().__init__(window, gc_mode=gc_mode, gl_api=gl_api)

Expand Down
6 changes: 3 additions & 3 deletions arcade/examples/perspective.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from array import array

import arcade
from pyglet.math import Mat4
from pyglet.math import Mat4, Vec3
from arcade.gl import BufferDescription


Expand Down Expand Up @@ -121,8 +121,8 @@ def on_draw(self):
self.fbo.color_attachments[0].use(unit=0)

# Move the plane into camera view and rotate it
translate = Mat4.from_translation((0, 0, -2))
rotate = Mat4.from_rotation(self.time / 2, (1, 0, 0))
translate = Mat4.from_translation(Vec3(0, 0, -2))
rotate = Mat4.from_rotation(self.time / 2, Vec3(1, 0, 0))
self.program["model"] = translate @ rotate

# Scroll the texture coordinates
Expand Down
5 changes: 4 additions & 1 deletion arcade/gl/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,10 @@ class Context:
_valid_apis = ("gl", "gles")

def __init__(
self, window: pyglet.window.Window, gc_mode: str = "context_gc", gl_api: str = "gl"
self,
window: pyglet.window.Window, # type: ignore
gc_mode: str = "context_gc",
gl_api: str = "gl",
):
self._window_ref = weakref.ref(window)
if gl_api not in self._valid_apis:
Expand Down
4 changes: 2 additions & 2 deletions arcade/gui/constructs.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __init__(
raise ValueError("At least a single value has to be available for `buttons`")

super().__init__(size_hint=(1, 1))
self.register_event_type("on_action")
self.register_event_type("on_action") # type: ignore # https://github.com/pyglet/pyglet/pull/1173 # noqa

space = 20

Expand Down Expand Up @@ -136,7 +136,7 @@ def __init__(
space_between=space_between,
style=style,
)
self.register_event_type("on_action")
self.register_event_type("on_action") # type: ignore # https://github.com/pyglet/pyglet/pull/1173 # noqa

self.button_factory = button_factory

Expand Down
2 changes: 1 addition & 1 deletion arcade/gui/ui_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def __init__(self, window: Optional[arcade.Window] = None):
self._render_to_surface_camera = arcade.Camera2D()
# this camera is used for rendering the UI and should not be changed by the user

self.register_event_type("on_event")
self.register_event_type("on_event") # type: ignore # https://github.com/pyglet/pyglet/pull/1173 # noqa

def add(self, widget: W, *, index=None, layer=0) -> W:
"""
Expand Down
6 changes: 3 additions & 3 deletions arcade/gui/widgets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,8 @@ def __init__(
self.size_hint_min = size_hint_min
self.size_hint_max = size_hint_max

self.register_event_type("on_event")
self.register_event_type("on_update")
self.register_event_type("on_event") # type: ignore # https://github.com/pyglet/pyglet/pull/1173 # noqa
self.register_event_type("on_update") # type: ignore # https://github.com/pyglet/pyglet/pull/1173 # noqa

for child in children:
self.add(child)
Expand Down Expand Up @@ -516,7 +516,7 @@ def __init__(
size_hint_max=size_hint_max,
**kwargs,
)
self.register_event_type("on_click")
self.register_event_type("on_click") # type: ignore

self.interaction_buttons = interaction_buttons

Expand Down
2 changes: 1 addition & 1 deletion arcade/gui/widgets/dropdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def __init__(
# add children after super class setup
self.add(self._default_button)

self.register_event_type("on_change")
self.register_event_type("on_change") # type: ignore # https://github.com/pyglet/pyglet/pull/1173 # noqa

self.with_border(color=arcade.color.RED)

Expand Down
2 changes: 1 addition & 1 deletion arcade/gui/widgets/slider.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def __init__(
bind(self, "pressed", self.trigger_render)
bind(self, "disabled", self.trigger_render)

self.register_event_type("on_change")
self.register_event_type("on_change") # type: ignore # https://github.com/pyglet/pyglet/pull/1173 # noqa

def _x_for_value(self, value: float):
"""Provides the x coordinate for the given value."""
Expand Down
2 changes: 1 addition & 1 deletion arcade/gui/widgets/toggle.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def __init__(
)

self.value = value
self.register_event_type("on_change")
self.register_event_type("on_change") # type: ignore # https://github.com/pyglet/pyglet/pull/1173 # noqa

bind(self, "value", self.trigger_render)
bind(self, "value", self._dispatch_on_change_event)
Expand Down
9 changes: 4 additions & 5 deletions arcade/sound.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@
from typing import Optional, Union

import pyglet
from pyglet.media import Source

from arcade.resources import resolve

if os.environ.get("ARCADE_SOUND_BACKENDS"):
pyglet.options["audio"] = tuple(
pyglet.options.audio = tuple( # type: ignore
v.strip() for v in os.environ["ARCADE_SOUND_BACKENDS"].split(",")
)
else:
pyglet.options["audio"] = ("openal", "xaudio2", "directsound", "pulse", "silent")
pyglet.options.audio = ("openal", "xaudio2", "directsound", "pulse", "silent") # type: ignore

import pyglet.media as media

Expand All @@ -39,9 +40,7 @@ def __init__(self, file_name: Union[str, Path], streaming: bool = False):
raise FileNotFoundError(f"The sound file '{file_name}' is not a file or can't be read.")
self.file_name = str(file_name)

self.source: Union[media.StaticSource, media.StreamingSource] = media.load(
self.file_name, streaming=streaming
)
self.source: Source = media.load(self.file_name, streaming=streaming)

if self.source.duration is None:
raise ValueError(
Expand Down
Loading

0 comments on commit 6e8259d

Please sign in to comment.