File: symbolic_matrix.py

package info (click to toggle)
renpy 8.0.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 81,768 kB
  • sloc: python: 44,587; ansic: 13,708; javascript: 308; makefile: 41; sh: 13
file content (346 lines) | stat: -rw-r--r-- 7,874 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
from __future__ import print_function, unicode_literals
from sympy import symbols, Matrix, pi, cos, sin, simplify
import io

matrix_names = [
    "xdx",
    "xdy",
    "xdz",
    "xdw",

    "ydx",
    "ydy",
    "ydz",
    "ydw",

    "zdx",
    "zdy",
    "zdz",
    "zdw",

    "wdx",
    "wdy",
    "wdz",
    "wdw",
    ]


def prefixed_matrix(prefix):
    """
    Returns a matrix where each entry is of the for prefix___name.
    """

    return Matrix(4, 4, [ symbols(prefix + "___" + i) for i in matrix_names ])

###############################################################################


generators = [ ]


class Generator(object):

    def __init__(self, name, docs):

        self.pyd_f = io.StringIO()
        self.pyx_f = io.StringIO()

        self.f = io.StringIO()

        self.name = name
        self.docs = docs

        generators.append(self)

        self.first_let = True

    def parameters(self, params):

        # PYD.
        print("    @staticmethod", file=self.pyd_f)
        print("    cdef Matrix c{}({})".format(
            self.name,
            ", ".join("float " + i for i in params.split())), file=self.pyd_f)

        # PYX.

        print("    @staticmethod", file=self.pyx_f)
        print("    cdef Matrix c{}({}):".format(
            self.name,
            ", ".join("float " + i for i in params.split())), file=self.pyx_f)
        print("        return {}_matrix({})".format(
            self.name, ", ".join(params.split())), file=self.pyx_f)

        print(file=self.pyx_f)

        print("    @staticmethod", file=self.pyx_f)
        print("    def {}({}):".format(
            self.name,
            ", ".join(params.split())), file=self.pyx_f)

        if self.docs:
            print('        """' + self.docs.replace("\n", "\n    ") + '"""', file=self.pyx_f)

        print("        return {}_matrix({})".format(
            self.name, ", ".join(params.split())), file=self.pyx_f)

        # PXI.

        print(file=self.f)
        print(file=self.f)

        print("cpdef Matrix {}_matrix({}):".format(
            self.name,
            ", ".join("float " + i for i in params.split())), file=self.f)

        if params.split():
            return symbols(params)

    def let(self, name, value):

        if self.first_let:
            print(file=self.f)
            self.first_let = False

        value = simplify(value, rational=True)

        print("    cdef float {} = {}".format(name, str(value)), file=self.f)

        return symbols(name)

    def matrix(self, m):

        print(file=self.f)

        print("    cdef Matrix rv = Matrix(None)", file=self.f)
        print(file=self.f)

        for name, value in zip(matrix_names, m):
            if value == 0.0:
                continue

            print("    rv.{} =".format(name), simplify(value, rational=True), file=self.f)

        print(file=self.f)
        print("    return rv", file=self.f)


def generate(func):
    g = Generator(func.__name__, func.__doc__)
    func(g)
    return func


def write(fn):

    with open(fn, "w") as f:
        for i in generators:
            f.write(i.f.getvalue())

    print("pxd ---------------------------------")

    for i in generators:
        print(i.pyd_f.getvalue())

    print("pyx ---------------------------------")

    for i in generators:
        print(i.pyx_f.getvalue())


@generate
def identity(g):
    """
    Returns an identity matrix.
    """

    g.parameters("")

    g.matrix(Matrix(4, 4, [
        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,
        ]))


@generate
def offset(g):
    """
    Returns a matrix that offsets the vertex by a fixed amount.
    """

    x, y, z = g.parameters("x y z")

    g.matrix(Matrix(4, 4, [
        1.0, 0.0, 0.0, x,
        0.0, 1.0, 0.0, y,
        0.0, 0.0, 1.0, z,
        0.0, 0.0, 0.0, 1.0,
        ]))


@generate
def rotate(g):
    """
    Returns a matrix that rotates the displayable around the
    origin.

    `x`, `y`, `x`
        The amount to rotate around the origin, in degrees.

    The rotations are applied in order:

    * A clockwise rotation by `x` degrees in the Y/Z plane.
    * A clockwise rotation by `y` degrees in the Z/X plane.
    * A clockwise rotation by `z` degrees in the X/Y plane.
    """

    x, y, z = g.parameters("x y z")

    sinx = g.let("sinx", sin(x * pi / 180.0))
    cosx = g.let("cosx", cos(x * pi / 180.0))

    siny = g.let("siny", sin(y * pi / 180.0))
    cosy = g.let("cosy", cos(y * pi / 180.0))

    sinz = g.let("sinz", sin(z * pi / 180.0))
    cosz = g.let("cosz", cos(z * pi / 180.0))

    rx = Matrix(4, 4, [
        1, 0, 0, 0,
        0, cosx, -sinx, 0,
        0, sinx, cosx, 0,
        0, 0, 0, 1 ])

    ry = Matrix(4, 4, [
        cosy, 0, siny, 0,
        0, 1, 0, 0,
        -siny, 0, cosy, 0,
        0, 0, 0, 1])

    rz = Matrix(4, 4, [
        cosz, -sinz, 0, 0,
        sinz, cosz, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1, ])

    g.matrix(rz * ry * rx)


@generate
def scale(g):
    """
    Returns a matrix that scales the displayable.

    `x`, `y`, `z`
        The factor to scale each axis by.
    """

    x, y, z = g.parameters("x y z")

    m = Matrix(4, 4, [
        x, 0, 0, 0,
        0, y, 0, 0,
        0, 0, z, 0,
        0, 0, 0, 1 ])

    g.matrix(m)


@generate
def perspective(g):
    """
    Returns the Ren'Py projection matrix. This is a view into a 3d space
    where (0, 0) is the top left corner (`w`/2, `h`/2) is the center, and
    (`w`,`h`) is the bottom right, when the z coordinate is 0.

    `w`, `h`
        The width and height of the input plane, in pixels.

    `n`
        The distance of the near plane from the camera.

    `p`
        The distance of the 1:1 plane from the camera. This is where 1 pixel
        is one coordinate unit.

    `f`
        The distance of the far plane from the camera.
    """

    w, h, n, p, f = g.parameters('w h n p f')

    offset = Matrix(4, 4, [
        1.0, 0.0, 0.0, -w / 2.0,
        0.0, 1.0, 0.0, -h / 2.0,
        0.0, 0.0, 1.0, -p,
        0.0, 0.0, 0.0, 1.0,
    ])

    projection = Matrix(4, 4, [
        2.0 * p / w, 0.0, 0.0, 0.0,
        0.0, 2.0 * p / h, 0.0, 0.0,
        0.0, 0.0, -(f + n) / (f - n), -2 * f * n / (f - n),
        0.0, 0.0, -1.0, 0.0,
    ])

    reverse_offset = Matrix(4, 4, [
        w / 2.0, 0.0, 0.0, w / 2.0,
        0.0, h / 2.0, 0.0, h / 2.0,
        0.0, 0.0, 1.0, 0.0,
        0.0, 0.0, 0.0, 1.0,
    ])

    g.matrix(reverse_offset * projection * offset)


@generate
def screen_projection(g):
    """
    This generates a matrix that projects the Ren'Py space, where (0, 0) is the
    top left and (`w`, `h`) is the bottom right, into the OpenGL viewport, where
    (-1.0, 1.0) is the top left and (1.0, -1.0) is the bottom.

    Generates the matrix that projects the Ren'Py screen to the OpenGL screen.
    """

    w, h = g.parameters("w h")

    m = Matrix(4, 4, [
        2.0 / w, 0.0, 0.0, -1.0,
        0.0, -2.0 / h, 0.0, 1.0,
        0.0, 0.0, 1.0, 0.0,
        0.0, 0.0, 0.0, 1.0
        ])

    g.matrix(m)


@generate
def texture_projection(g):
    """
    This generates a matrix that project the Ren'Py space, where (0, 0) is the
    top left and (`w`, `h`) is the bottom right, into the OpenGL render-to-texture
    space, where (-1.0, -1.0) is the top left and (1.0, 1.0) is the bottom.

    Generates the matrix that projects the Ren'Py screen to the OpenGL screen.
    """

    w, h = g.parameters("w h")

    m = Matrix(4, 4, [
        2.0 / w, 0.0, 0.0, -1.0,
        0.0, 2.0 / h, 0.0, -1.0,
        0.0, 0.0, 1.0, 0.0,
        0.0, 0.0, 0.0, 1.0
        ])

    g.matrix(m)


if __name__ == "__main__":
    import os

    RENPY = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    write(os.path.join(RENPY, "renpy", "display", "matrix_functions.pxi"))