gamnit: intro cache for `Camera::mvp_matrix`
[nit.git] / lib / gamnit / cameras_cache.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Cache the `Matrix` produced by `Camera::mvp_matrix`
16 module cameras_cache
17
18 import cameras
19
20 redef class Camera
21 private var mvp_matrix_cache: nullable Matrix = null
22
23 private var position_cache = new Point3d[Float](0.0, 0.0, 0.0)
24
25 # Has `position` changed from `position_cache`? Update the cache at the same time
26 private fun check_position_changed: Bool
27 do
28 if position.x != position_cache.x or
29 position.y != position_cache.y or
30 position.z != position_cache.z then
31 position_cache.x = position.x
32 position_cache.y = position.y
33 position_cache.z = position.z
34 return true
35 end
36 return false
37 end
38 end
39
40 redef class EulerCamera
41 # The returned matrix must not be modified as it is cached.
42 redef fun mvp_matrix
43 do
44 var m = mvp_matrix_cache
45 if m == null or check_position_changed then
46 m = super
47 mvp_matrix_cache = m
48 end
49 return m
50 end
51
52 redef fun pitch=(value)
53 do
54 super
55 mvp_matrix_cache = null
56 end
57
58 redef fun yaw=(value)
59 do
60 super
61 mvp_matrix_cache = null
62 end
63
64 redef fun roll=(value)
65 do
66 super
67 mvp_matrix_cache = null
68 end
69
70 redef fun field_of_view_y=(value)
71 do
72 super
73 mvp_matrix_cache = null
74 end
75
76 redef fun near=(value)
77 do
78 super
79 mvp_matrix_cache = null
80 end
81
82 redef fun far=(value)
83 do
84 super
85 mvp_matrix_cache = null
86 end
87 end
88
89 redef class UICamera
90 # The returned matrix must not be modified as it is cached.
91 redef fun mvp_matrix
92 do
93 var m = mvp_matrix_cache
94 if m == null or check_position_changed then
95 m = super
96 mvp_matrix_cache = m
97 end
98 return m
99 end
100
101 redef fun near=(value)
102 do
103 super
104 mvp_matrix_cache = null
105 end
106
107 redef fun far=(value)
108 do
109 super
110 mvp_matrix_cache = null
111 end
112
113 redef fun width=(value)
114 do
115 super
116 mvp_matrix_cache = null
117 end
118
119 redef fun height=(value)
120 do
121 super
122 mvp_matrix_cache = null
123 end
124 end