Mercurial > touhou
comparison pytouhou/utils/maths.pyx @ 412:5fe6cd6ceb48
Refactor the maths functions out of Renderer.
author | Emmanuel Gil Peyrot <linkmauve@linkmauve.fr> |
---|---|
date | Wed, 12 Jun 2013 18:30:08 +0200 |
parents | |
children | 878273a984c4 |
comparison
equal
deleted
inserted
replaced
411:2428296cccab | 412:5fe6cd6ceb48 |
---|---|
1 # -*- encoding: utf-8 -*- | |
2 ## | |
3 ## Copyright (C) 2013 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr> | |
4 ## | |
5 ## This program is free software; you can redistribute it and/or modify | |
6 ## it under the terms of the GNU General Public License as published | |
7 ## by the Free Software Foundation; version 3 only. | |
8 ## | |
9 ## This program is distributed in the hope that it will be useful, | |
10 ## but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 ## GNU General Public License for more details. | |
13 ## | |
14 | |
15 from math import radians | |
16 from libc.math cimport tan | |
17 | |
18 from .matrix cimport Matrix | |
19 from .vector import Vector, normalize, cross, dot | |
20 | |
21 | |
22 cpdef ortho_2d(left, right, bottom, top): | |
23 mat = Matrix() | |
24 data = mat.data | |
25 data[0][0] = 2 / (right - left) | |
26 data[1][1] = 2 / (top - bottom) | |
27 data[2][2] = -1 | |
28 data[3][0] = -(right + left) / (right - left) | |
29 data[3][1] = -(top + bottom) / (top - bottom) | |
30 return mat | |
31 | |
32 | |
33 cpdef look_at(eye, center, up): | |
34 eye = Vector(eye) | |
35 center = Vector(center) | |
36 up = Vector(up) | |
37 | |
38 f = normalize(center - eye) | |
39 u = normalize(up) | |
40 s = normalize(cross(f, u)) | |
41 u = cross(s, f) | |
42 | |
43 return Matrix([[s[0], u[0], -f[0], 0], | |
44 [s[1], u[1], -f[1], 0], | |
45 [s[2], u[2], -f[2], 0], | |
46 [-dot(s, eye), -dot(u, eye), dot(f, eye), 1]]) | |
47 | |
48 | |
49 cpdef perspective(fovy, aspect, z_near, z_far): | |
50 top = tan(radians(fovy / 2)) * z_near | |
51 bottom = -top | |
52 left = -top * aspect | |
53 right = top * aspect | |
54 | |
55 mat = Matrix() | |
56 data = mat.data | |
57 data[0][0] = (2 * z_near) / (right - left) | |
58 data[1][1] = (2 * z_near) / (top - bottom) | |
59 data[2][2] = -(z_far + z_near) / (z_far - z_near) | |
60 data[2][3] = -1 | |
61 data[3][2] = -(2 * z_far * z_near) / (z_far - z_near) | |
62 data[3][3] = 0 | |
63 return mat | |
64 | |
65 | |
66 cpdef setup_camera(dx, dy, dz): | |
67 # Some explanations on the magic constants: | |
68 # 192. = 384. / 2. = width / 2. | |
69 # 224. = 448. / 2. = height / 2. | |
70 # 835.979370 = 224./math.tan(math.radians(15)) = (height/2.)/math.tan(math.radians(fov/2)) | |
71 # This is so that objects on the (O, x, y) plane use pixel coordinates | |
72 return look_at((192., 224., - 835.979370 * dz), | |
73 (192. + dx, 224. - dy, 0.), (0., -1., 0.)) |