矩阵与向量数学

现代OpenGL依赖于矩阵来进行投影、平移和其他操作。为了提供开箱即用的功能,pyglet的 math 模块包括必要的矩阵和向量类型,以涵盖大多数使用情形:

  • pyglet.math.Vec2

  • pyglet.math.Vec3

  • pyglet.math.Vec4

  • pyglet.math.Mat3

  • pyglet.math.Mat4

这些类型支持最常见的矩阵和向量运算,包括旋转、缩放和变换。请参阅 math 完整API文档的模块。

备注

就性能而言,矩阵类型是 tuple 打字。因此它们是不可变的--所有操作都返回一个 new 对象;它们不会就地更新。

创建矩阵

可以创建不带参数的矩阵,也可以通过传递 float **

my_matrix = Mat4()
# or
my_matrix = Mat4([1.0, 0.0, 0.0, 0.0,
                  0.0, 1.0, 0.0, 0.0,
                  0.0, 0.0, 1.0, 0.0,
                  0.0, 0.0, 0.0, 1.0])

如果没有给出参数,默认情况下会创建一个“Identity”矩阵。(主对角线上为1.0)。

矩阵乘法

Matrix classes in pyglet use the modern Python matmul (@) operator for matrix multiplication. The star operator (*) is not allowed. For example:

new_matrix = rotation_matrix @ translation_matrix

帮助器方法

OpenGL中的一个常见操作是创建2D或3D投影矩阵。这个 Mat4 模块包括此任务的帮助器方法。参数应类似于您将在流行的OpenGL数学库中找到的参数:

# Orthographic (2D) projection matrix:
projection = Mat4.orthogonal_projection(0, width, 0, height, z_near=-255, z_far=255)

# Perspective (3D) projection matrix:
projection = Mat4.perspective_projection(aspect_ratio, z_near=0.1, z_far=255)

为了在当前OpenGL上下文上设置3D投影,pyglet窗口具有 projection 财产。例如::

my_matrix = Mat4.perspective_projection(aspect_ratio, z_near=0.1, z_far=255)
window.projection = my_matrix

默认情况下,只要调整窗口大小,Piglet就会自动设置2D投影。如果您计划设置自己的3D或2D投影矩阵,一个有用的模式是覆盖默认的ON_RESIZE事件处理程序::

@window.event
def on_resize(width, height):
    # window.viewport = (0, 0, *window.get_framebuffer_size())
    window.projection = Mat4.perspective_projection(window.aspect_ratio, z_near=0.1, z_far=255)
    return pyglet.event.EVENT_HANDLED   # Don't call the default handler