| 1 |
""" |
| 2 |
A basic first-person camera example. |
| 3 |
|
| 4 |
This is ideal for inspecting 3D models/scenes and can be adapted |
| 5 |
to your needs for first person games. |
| 6 |
|
| 7 |
* Supports mouse and keyboard input with WASD + QE for up/down. |
| 8 |
* Supports controller input for movement and rotation including left and right triggers |
| 9 |
to move up and down, |
| 10 |
""" |
| 11 |
|
| 12 |
from __future__ import annotations |
| 13 |
|
| 14 |
import weakref |
| 15 |
|
| 16 |
from math import radians, degrees |
| 17 |
|
| 18 |
import pyglet |
| 19 |
|
| 20 |
from pyglet.gl import glEnable, GL_DEPTH_TEST, GL_CULL_FACE |
| 21 |
from pyglet.math import Vec2, Vec3, Mat4, clamp |
| 22 |
from pyglet.window import key as _key |
| 23 |
|
| 24 |
|
| 25 |
class FPSCamera: |
| 26 |
"""A 3D projection "first person" camera example. |
| 27 |
|
| 28 |
Windows in pyglet contain `view` and `projection` matrices, |
| 29 |
which are shared with all default shaders in a `WindowBlock` UBO. |
| 30 |
This Camera class handles events from the mouse & keyboard and |
| 31 |
Controller, and updates these Window matrices. |
| 32 |
|
| 33 |
Note: mouse input will be captured once you click on the Window, |
| 34 |
which sets the mouse as exclusive. Pressing ESC once will set |
| 35 |
the mouse as non-exclusive. |
| 36 |
|
| 37 |
Args: |
| 38 |
window (pyglet.window.Window): The window to attach the camera to. |
| 39 |
|
| 40 |
Keyword Args: |
| 41 |
position (Vec3, optional): |
| 42 |
The position of the camera. Defaults to Vec3(0, 0, 0). |
| 43 |
target (Vec3, optional): |
| 44 |
The target of the camera. Defaults to Vec3(0, 0, -1). |
| 45 |
near (float, optional): |
| 46 |
The near plane of the camera. Defaults to 0.1. |
| 47 |
far (float, optional): |
| 48 |
The far plane of the camera. Defaults to 1000. |
| 49 |
field_of_view (float, optional): |
| 50 |
The field of view of the camera in degrees. Defaults to 45.0 degrees. |
| 51 |
""" |
| 52 |
UP = Vec3(0.0, 1.0, 0.0) |
| 53 |
ZERO = Vec3(0.0, 0.0, 0.0) |
| 54 |
|
| 55 |
def __init__( |
| 56 |
self, |
| 57 |
window: pyglet.window.Window, |
| 58 |
position: Vec3 | None = None, |
| 59 |
target: Vec3 | None = None, |
| 60 |
near: float = 0.1, |
| 61 |
far: float = 1000, |
| 62 |
field_of_view: float = 60.0, |
| 63 |
) -> None: |
| 64 |
"""Initialize the camera.""" |
| 65 |
self._window = weakref.proxy(window) |
| 66 |
self.position = position or Vec3(0.0, 0.0, 0.0) |
| 67 |
self._exclusive_mouse = False |
| 68 |
|
| 69 |
|
| 70 |
self._near = near |
| 71 |
self._far = far |
| 72 |
self._field_of_view = field_of_view |
| 73 |
|
| 74 |
|
| 75 |
self.walk_speed = 10.0 |
| 76 |
self.look_speed = 10.0 |
| 77 |
|
| 78 |
|
| 79 |
self._pitch = 0.0 |
| 80 |
self._yaw = -90.0 |
| 81 |
self._roll = 0.0 |
| 82 |
self._elevation = 0.0 |
| 83 |
|
| 84 |
|
| 85 |
self.keyboard_move = Vec2() |
| 86 |
self.mouse_look = Vec2() |
| 87 |
|
| 88 |
self.controller_move = Vec2() |
| 89 |
self.controller_look = Vec2() |
| 90 |
self.dead_zone = 0.1 |
| 91 |
|
| 92 |
|
| 93 |
self.input_map = { |
| 94 |
_key.W: "forward", |
| 95 |
_key.S: "backward", |
| 96 |
_key.A: "left", |
| 97 |
_key.D: "right", |
| 98 |
_key.E: "up", |
| 99 |
_key.Q: "down", |
| 100 |
} |
| 101 |
|
| 102 |
self.inputs = {direction: False for direction in self.input_map.values()} |
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
if target is None: |
| 107 |
target = position + Vec3(0.0, 0.0, -1.0) |
| 108 |
|
| 109 |
self.teleport(position, target) |
| 110 |
|
| 111 |
self._window.push_handlers(self) |
| 112 |
self.on_refresh(0.0) |
| 113 |
|
| 114 |
@property |
| 115 |
def pitch(self) -> float: |
| 116 |
"""Get or set the pitch of the camera in degrees. |
| 117 |
|
| 118 |
Pitch is the rotation around the local x-axis meaning |
| 119 |
that a positive pitch will look up and a negative pitch |
| 120 |
will look down. |
| 121 |
|
| 122 |
These values are clamped between -85 and 85 degrees to |
| 123 |
mimic the behavior of most first-person cameras. |
| 124 |
""" |
| 125 |
return self._pitch |
| 126 |
|
| 127 |
@pitch.setter |
| 128 |
def pitch(self, value: float) -> None: |
| 129 |
self._pitch = clamp(value, -85.0, 85.0) |
| 130 |
|
| 131 |
@property |
| 132 |
def yaw(self) -> float: |
| 133 |
"""The yaw of the camera in degrees. |
| 134 |
|
| 135 |
This is the local rotation around the global y-axis |
| 136 |
meaning that a positive yaw will look to the right |
| 137 |
and a negative yaw will look to the left. |
| 138 |
""" |
| 139 |
return self._yaw |
| 140 |
|
| 141 |
@yaw.setter |
| 142 |
def yaw(self, value: float) -> None: |
| 143 |
self._yaw = value |
| 144 |
|
| 145 |
@property |
| 146 |
def field_of_view(self) -> float: |
| 147 |
"""Get or set the field of view of the camera in degrees. |
| 148 |
|
| 149 |
Setting the value will update the projection matrix. |
| 150 |
""" |
| 151 |
return self._field_of_view |
| 152 |
|
| 153 |
@field_of_view.setter |
| 154 |
def field_of_view(self, value: float) -> None: |
| 155 |
self._field_of_view = value |
| 156 |
self._update_projection() |
| 157 |
|
| 158 |
@property |
| 159 |
def near(self) -> float: |
| 160 |
"""Get or set the near plane of the camera. |
| 161 |
|
| 162 |
Setting the value will update the projection matrix. |
| 163 |
""" |
| 164 |
return self._near |
| 165 |
|
| 166 |
@near.setter |
| 167 |
def near(self, value: float) -> None: |
| 168 |
self._near = value |
| 169 |
self._update_projection() |
| 170 |
|
| 171 |
@property |
| 172 |
def far(self) -> float: |
| 173 |
"""Get or set the far plane of the camera. |
| 174 |
|
| 175 |
Setting the value will update the projection matrix. |
| 176 |
""" |
| 177 |
return self._far |
| 178 |
|
| 179 |
@far.setter |
| 180 |
def far(self, value: float) -> None: |
| 181 |
self._far = value |
| 182 |
self._update_projection() |
| 183 |
|
| 184 |
def on_resize(self, width: int, height: int) -> bool: |
| 185 |
"""Update the viewport and projection matrix on window resize.""" |
| 186 |
self._window.viewport = (0, 0, *self._window.get_framebuffer_size()) |
| 187 |
self._update_projection() |
| 188 |
return pyglet.event.EVENT_HANDLED |
| 189 |
|
| 190 |
def on_refresh(self, delta_time: float) -> None: |
| 191 |
"""Called before the window content is drawn. |
| 192 |
|
| 193 |
Runs every frame applying the camera movement. |
| 194 |
""" |
| 195 |
walk_speed = self.walk_speed * delta_time |
| 196 |
look_speed = self.look_speed * delta_time |
| 197 |
|
| 198 |
|
| 199 |
if self.mouse_look: |
| 200 |
self.yaw += self.mouse_look.x * look_speed |
| 201 |
self.pitch += self.mouse_look.y * look_speed |
| 202 |
|
| 203 |
self.mouse_look = Vec2() |
| 204 |
|
| 205 |
|
| 206 |
if self.controller_look: |
| 207 |
self.yaw += self.controller_look.x * look_speed * 20 |
| 208 |
self.pitch += self.controller_look.y * look_speed * 20 |
| 209 |
|
| 210 |
|
| 211 |
forward = Vec3.from_pitch_yaw(radians(self.pitch), radians(self.yaw)) |
| 212 |
right = forward.cross(self.UP).normalize() |
| 213 |
up = right.cross(forward).normalize() |
| 214 |
translation = Vec3() |
| 215 |
|
| 216 |
|
| 217 |
if self.keyboard_move: |
| 218 |
translation += forward * self.keyboard_move.y + right * self.keyboard_move.x |
| 219 |
|
| 220 |
|
| 221 |
if self.controller_move: |
| 222 |
translation += forward * self.controller_move.y + right * self.controller_move.x |
| 223 |
|
| 224 |
self.position += (translation + up * self._elevation) * walk_speed |
| 225 |
|
| 226 |
|
| 227 |
self._window.view = Mat4.look_at(self.position, self.position + forward, self.UP) |
| 228 |
|
| 229 |
def on_deactivate(self) -> None: |
| 230 |
"""Reset the movement states when the window loses focus.""" |
| 231 |
self.controller_look = Vec2() |
| 232 |
self.controller_move = Vec2() |
| 233 |
|
| 234 |
def teleport(self, position: Vec3, target: Vec3 | None = None) -> None: |
| 235 |
"""Teleport the camera to a new position. |
| 236 |
|
| 237 |
An optional new view target can be provided. If no target is |
| 238 |
provided, the camera will look in the same direction as before. |
| 239 |
""" |
| 240 |
if target is not None: |
| 241 |
direction = (target - self.position).normalize() |
| 242 |
pitch, yaw = direction.get_pitch_yaw() |
| 243 |
self.yaw = degrees(yaw) |
| 244 |
self.pitch = degrees(pitch) |
| 245 |
|
| 246 |
self.position = position |
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
def on_mouse_motion(self, x: int, y: int, dx: int, dy: int) -> None: |
| 251 |
"""Read the mouse input and update the camera's yaw and pitch.""" |
| 252 |
if not self._exclusive_mouse: |
| 253 |
return |
| 254 |
|
| 255 |
self.mouse_look = Vec2(dx, dy) |
| 256 |
|
| 257 |
def on_mouse_press(self, x: int, y: int, button, modifiers) -> None: |
| 258 |
"""Capture the mouse input when the window is clicked.""" |
| 259 |
if not self._exclusive_mouse: |
| 260 |
self._exclusive_mouse = True |
| 261 |
self._window.set_exclusive_mouse(True) |
| 262 |
|
| 263 |
|
| 264 |
|
| 265 |
def on_key_press(self, symbol: int, mod: int) -> bool: |
| 266 |
"""Handle keyboard input.""" |
| 267 |
if direction := self.input_map.get(symbol): |
| 268 |
self.inputs[direction] = True |
| 269 |
forward, backward, left, right, up, down = self.inputs.values() |
| 270 |
self.keyboard_move = Vec2(-float(left) + float(right), float(forward) + -float(backward)).normalize() |
| 271 |
self._elevation = float(up) + -float(down) |
| 272 |
return pyglet.event.EVENT_HANDLED |
| 273 |
|
| 274 |
if symbol == pyglet.window.key.ESCAPE: |
| 275 |
if not self._exclusive_mouse: |
| 276 |
pyglet.app.exit() |
| 277 |
self._exclusive_mouse = False |
| 278 |
self._window.set_exclusive_mouse(False) |
| 279 |
return pyglet.event.EVENT_HANDLED |
| 280 |
|
| 281 |
return False |
| 282 |
|
| 283 |
def on_key_release(self, symbol: int, mod: int) -> bool: |
| 284 |
"""Handle keyboard input release.""" |
| 285 |
if direction := self.input_map.get(symbol): |
| 286 |
self.inputs[direction] = False |
| 287 |
forward, backward, left, right, up, down = self.inputs.values() |
| 288 |
self.keyboard_move = Vec2(-float(left) + float(right), float(forward) + -float(backward)).normalize() |
| 289 |
self._elevation = float(up) + -float(down) |
| 290 |
return pyglet.event.EVENT_HANDLED |
| 291 |
|
| 292 |
return False |
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
def on_stick_motion(self, _controller, stick: str, vector: Vec2): |
| 297 |
"""Handle controller input. |
| 298 |
|
| 299 |
The left stick controls the camera position, and the right stick |
| 300 |
controls the camera rotation. |
| 301 |
""" |
| 302 |
|
| 303 |
if stick == "leftstick": |
| 304 |
if vector.length() < self.dead_zone: |
| 305 |
self.controller_move = Vec2() |
| 306 |
else: |
| 307 |
self.controller_move = vector |
| 308 |
|
| 309 |
|
| 310 |
if stick == "rightstick": |
| 311 |
if vector.length() >= self.dead_zone: |
| 312 |
self.controller_look = vector |
| 313 |
else: |
| 314 |
self.controller_look = Vec2() |
| 315 |
|
| 316 |
def on_trigger_motion(self, controller, trigger: str, value: float): |
| 317 |
"""Handle the controller trigger input.""" |
| 318 |
if trigger == "lefttrigger": |
| 319 |
self._elevation = -value |
| 320 |
if trigger == "righttrigger": |
| 321 |
self._elevation = value |
| 322 |
|
| 323 |
|
| 324 |
|
| 325 |
def _update_projection(self): |
| 326 |
"""Update the projection matrix""" |
| 327 |
self._window.projection = Mat4.perspective_projection( |
| 328 |
self._window.aspect_ratio, |
| 329 |
z_near=self.near, |
| 330 |
z_far=self.far, |
| 331 |
fov=self.field_of_view, |
| 332 |
) |
| 333 |
|
| 334 |
|
| 335 |
if __name__ == "__main__": |
| 336 |
window = pyglet.window.Window(resizable=True) |
| 337 |
batch = pyglet.graphics.Batch() |
| 338 |
|
| 339 |
@window.event |
| 340 |
def on_draw(): |
| 341 |
window.clear() |
| 342 |
batch.draw() |
| 343 |
|
| 344 |
glEnable(GL_DEPTH_TEST) |
| 345 |
glEnable(GL_CULL_FACE) |
| 346 |
|
| 347 |
|
| 348 |
model_logo = pyglet.resource.scene("logo3d.obj").create_models(batch=batch)[0] |
| 349 |
model_box = pyglet.resource.scene("box.obj").create_models(batch=batch)[0] |
| 350 |
|
| 351 |
|
| 352 |
camera = FPSCamera(window, position=Vec3(0.0, 0.0, 5.0)) |
| 353 |
|
| 354 |
|
| 355 |
if controllers := pyglet.input.get_controllers(): |
| 356 |
controller = controllers[0] |
| 357 |
controller.open() |
| 358 |
controller.push_handlers(camera) |
| 359 |
|
| 360 |
model_logo.matrix = Mat4.from_translation(Vec3(1.75, 0, 0)) |
| 361 |
model_box.matrix = Mat4.from_translation(Vec3(-1.75, 0, 0)) |
| 362 |
|
| 363 |
pyglet.app.run() |