Last of the config.h mods...
[blender.git] / source / gameengine / Ketsji / KX_MouseFocusSensor.cpp
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  * KX_MouseFocusSensor determines mouse in/out/over events.
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #include <config.h>
36 #endif
37
38 #ifdef WIN32
39 // This warning tells us about truncation of __long__ stl-generated names.
40 // It can occasionally cause DevStudio to have internal compiler warnings.
41 #pragma warning( disable : 4786 )     
42 #endif
43
44 #include "MT_Point3.h"
45 #include "KX_ClientObjectInfo.h"
46 #include "RAS_FramingManager.h"
47 #include "RAS_ICanvas.h"
48 #include "RAS_IRasterizer.h"
49 #include "SCA_IScene.h"
50 #include "KX_Scene.h"
51 #include "KX_Camera.h"
52 #include "KX_MouseFocusSensor.h"
53
54 /* ------------------------------------------------------------------------- */
55 /* Native functions                                                          */
56 /* ------------------------------------------------------------------------- */
57
58 KX_MouseFocusSensor::KX_MouseFocusSensor(SCA_MouseManager* eventmgr, 
59                                                                                  int startx,
60                                                                                  int starty,
61                                                                                  short int mousemode,
62                                                                                  bool focusmode,
63                                                                                  RAS_ICanvas* canvas,
64                                                                                  KX_Scene* kxscene,
65                                                                                  SCA_IObject* gameobj, 
66                                                                                  PyTypeObject* T)
67     : SCA_MouseSensor(eventmgr, startx, starty, mousemode, gameobj, T),
68           m_focusmode(focusmode),
69           m_gp_canvas(canvas),
70           m_kxscene(kxscene)
71 {
72         /* Or postpone? I think a sumo scene and kx scene go pretty much
73          * together, so it should be safe to do it here. */
74         m_mouse_over_in_previous_frame = false;
75         m_positive_event = false;
76 }
77
78 bool KX_MouseFocusSensor::Evaluate(CValue* event)
79 {
80         bool result = false;
81         bool obHasFocus = false;
82
83 //      cout << "evaluate focus mouse sensor "<<endl;
84
85         if (m_focusmode) {
86                 /* Focus behaviour required. Test mouse-on. The rest is
87                  * equivalent to handling a key. */
88                 obHasFocus = ParentObjectHasFocus();
89                 
90                 if (!obHasFocus) {
91                         if (m_mouse_over_in_previous_frame) {
92                                         m_positive_event = false;
93                                         result = true;
94                         } 
95                 } else {
96                         if (!m_mouse_over_in_previous_frame) {
97                                 m_positive_event = true;
98                                 result = true;
99                         } 
100                 } 
101         } else {
102                 /* No focus behaviour required: revert to the basic mode. This
103          * mode is never used, because the converter never makes this
104          * sensor for a mouse-key event. It is here for
105          * completeness. */
106                 result = SCA_MouseSensor::Evaluate(event);
107                 m_positive_event = (m_val!=0);
108         }
109
110         m_mouse_over_in_previous_frame = obHasFocus;
111
112         return result;
113 }
114
115 bool KX_MouseFocusSensor::ParentObjectHasFocus(void)
116 {
117         
118         bool res = false;
119         m_hitPosition = MT_Vector3(0,0,0);
120         m_hitNormal =   MT_Vector3(1,0,0);
121         MT_Point3 resultpoint;
122         MT_Vector3 resultnormal;
123
124         /* All screen handling in the gameengine is done by GL,
125          * specifically the model/view and projection parts. The viewport
126          * part is in the creator. 
127          *
128          * The theory is this:
129          * WCS - world coordinates
130          * -> wcs_camcs_trafo ->
131          * camCS - camera coordinates
132          * -> camcs_clip_trafo ->
133          * clipCS - normalised device coordinates?
134          * -> normview_win_trafo
135          * winCS - window coordinates
136          *
137          * The first two transforms are respectively the model/view and
138          * the projection matrix. These are passed to the rasterizer, and
139          * we store them in the camera for easy access.
140          *
141          * For normalised device coords (xn = x/w, yn = y/w/zw) the
142          * windows coords become (lb = left bottom)
143          *
144          * xwin = [(xn + 1.0) * width]/2 + x_lb
145          * ywin = [(yn + 1.0) * height]/2 + y_lb
146          *
147          * Inverting (blender y is flipped!):
148          *
149          * xn = 2(xwin - x_lb)/width - 1.0
150          * yn = 2(ywin - y_lb)/height - 1.0 
151          *    = 2(height - y_blender - y_lb)/height - 1.0
152          *    = 1.0 - 2(y_blender - y_lb)/height
153          *
154          * */
155         
156         /* Because we don't want to worry about resize events, camera
157          * changes and all that crap, we just determine this over and
158          * over. Stop whining. We have lots of other calculations to do
159          * here as well. These reads are not the main cost. If there is no
160          * canvas, the test is irrelevant. The 1.0 makes sure the
161          * calculations don't bomb. Maybe we should explicitly guard for
162          * division by 0.0...*/
163
164         /**
165          * Get the scenes current viewport.
166          */
167
168         const RAS_Rect & viewport = m_kxscene->GetSceneViewport();
169
170         float height = float(viewport.m_y2 - viewport.m_y1 + 1);
171         float width  = float(viewport.m_x2 - viewport.m_x1 + 1);
172         
173         float x_lb = float(viewport.m_x1);
174         float y_lb = float(viewport.m_y1);
175
176         KX_Camera* cam = m_kxscene->GetActiveCamera();
177         /* There's some strangeness I don't fully get here... These values
178          * _should_ be wrong! */
179
180         /* old: */
181     float nearclip = 0.0;
182     float farclip = -1.0;
183
184         /*      build the from and to point in normalised device coordinates 
185          *      Looks like normailized device coordinates are [-1,1] in x [-1,1] in y
186          *      [0,-1] in z 
187          *      
188          *      The actual z coordinates used don't have to be exact just infront and 
189          *      behind of the near and far clip planes.
190          */ 
191         
192         MT_Vector4 frompoint = MT_Vector4( 
193                 (2 * (m_x-x_lb) / width) - 1.0,
194                 1.0 - (2 * (m_y - y_lb) / height),
195                 (nearclip + 3 * farclip) / (farclip - nearclip),
196                 1.0
197         );
198         MT_Vector4 topoint = MT_Vector4( 
199                 (2 * (m_x-x_lb) / width) - 1.0,
200                 1.0 - (2 * (m_y-y_lb) / height),
201                 (3 * nearclip + farclip) / (farclip - nearclip),
202                 1.0
203         );
204
205         /* camera to world  */
206         MT_Matrix4x4 camcs_wcs_matrix;
207         cam->GetModelviewMatrix(camcs_wcs_matrix);
208         camcs_wcs_matrix.invert();
209
210         MT_Matrix4x4 clip_camcs_matrix;
211         /* badly defined, the first time round.... I wonder why... I might
212          * want to guard against floating point errors here.*/
213         cam->GetProjectionMatrix(clip_camcs_matrix);
214         clip_camcs_matrix.invert();
215
216         /* shoot-points: clip to cam to wcs . win to clip was already done.*/
217         frompoint = clip_camcs_matrix * frompoint;
218         topoint   = clip_camcs_matrix * topoint;
219         frompoint = camcs_wcs_matrix * frompoint;
220         topoint   = camcs_wcs_matrix * topoint;
221
222         /* from hom wcs to 3d wcs: */
223         MT_Point3 frompoint3 = MT_Point3(frompoint[0]/frompoint[3], 
224                                                                          frompoint[1]/frompoint[3], 
225                                                                          frompoint[2]/frompoint[3]); 
226         MT_Point3 topoint3 = MT_Point3(topoint[0]/topoint[3], 
227                                                                    topoint[1]/topoint[3], 
228                                                                    topoint[2]/topoint[3]); 
229         m_prevTargetPoint = topoint3;
230         
231         /* 2. Get the object from SuMO*/
232         /* Shoot! Beware that the first argument here is an
233          * ignore-object. We don't ignore anything... */
234         KX_GameObject* thisObj = (KX_GameObject*) GetParent();
235         
236
237         //SM_Object* hitSMObj = m_sumoScene->rayTest(NULL, 
238         //                                                                                 frompoint3,
239         //                                                                                 topoint3,
240         //                                                                                 resultpoint, 
241         //                                                                                 resultnormal);
242         
243         KX_GameObject* hitKXObj = 0;
244         
245         /* all this casting makes me nervous... */
246         //SM_ClientObjectInfo* client_info 
247         //      = ( hitSMObj ?
248         //              (SM_ClientObjectInfo*) ((SM_Object*)hitSMObj)->getClientObject() :
249         //              NULL);
250         //KX_GameObject* hitKXObj = ( client_info ? 
251         //                                                      (KX_GameObject*)client_info->m_clientobject : 
252         //                                                      NULL);
253                 
254         
255         /* Is this me? In the ray test, there are a lot of extra checks
256          * for aliasing artefacts from self-hits. That doesn't happen
257          * here, so a simple test suffices. Or does the camera also get
258          * self-hits? (No, and the raysensor shouldn't do it either, since
259          * self-hits are excluded by setting the correct ignore-object.)
260          * Hitspots now become valid. */
261         if (hitKXObj == thisObj)
262         {
263                 m_hitPosition = resultpoint;
264                 m_hitNormal = resultnormal;
265                 res = true;
266         }
267
268         return res;
269 }
270
271 /* ------------------------------------------------------------------------- */
272 /* Python functions                                                          */
273 /* ------------------------------------------------------------------------- */
274
275 /* Integration hooks ------------------------------------------------------- */
276 PyTypeObject KX_MouseFocusSensor::Type = {
277         PyObject_HEAD_INIT(&PyType_Type)
278         0,
279         "KX_MouseFocusSensor",
280         sizeof(KX_MouseFocusSensor),
281         0,
282         PyDestructor,
283         0,
284         __getattr,
285         __setattr,
286         0, //&MyPyCompare,
287         __repr,
288         0, //&cvalue_as_number,
289         0,
290         0,
291         0,
292         0
293 };
294
295 PyParentObject KX_MouseFocusSensor::Parents[] = {
296         &KX_MouseFocusSensor::Type,
297         &SCA_MouseSensor::Type,
298         &SCA_ISensor::Type,
299         &SCA_ILogicBrick::Type,
300         &CValue::Type,
301         NULL
302 };
303
304 PyMethodDef KX_MouseFocusSensor::Methods[] = {
305         {"getRayTarget", (PyCFunction) KX_MouseFocusSensor::sPyGetRayTarget, 
306          METH_VARARGS, GetRayTarget_doc},
307         {"getRaySource", (PyCFunction) KX_MouseFocusSensor::sPyGetRaySource, 
308          METH_VARARGS, GetRaySource_doc},
309         {NULL,NULL} //Sentinel
310 };
311
312 PyObject* KX_MouseFocusSensor::_getattr(char* attr) {
313         _getattr_up(SCA_MouseSensor);
314 }
315
316 /*  getRayTarget                                                */
317 char KX_MouseFocusSensor::GetRayTarget_doc[] = 
318 "getRayTarget()\n"
319 "\tReturns the target of the ray that seeks the focus object,\n"
320 "\tin worldcoordinates.";
321 PyObject* KX_MouseFocusSensor::PyGetRayTarget(PyObject* self, 
322                                                                                           PyObject* args, 
323                                                                                           PyObject* kwds) {
324         PyObject *retVal = PyList_New(3);
325
326         PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_prevTargetPoint[0]));
327         PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_prevTargetPoint[1]));
328         PyList_SetItem(retVal, 2, PyFloat_FromDouble(m_prevTargetPoint[2]));
329         
330         return retVal;
331 }
332
333 /*  getRayTarget                                                */
334 char KX_MouseFocusSensor::GetRaySource_doc[] = 
335 "getRaySource()\n"
336 "\tReturns the source of the ray that seeks the focus object,\n"
337 "\tin worldcoordinates.";
338 PyObject* KX_MouseFocusSensor::PyGetRaySource(PyObject* self, 
339                                                                                           PyObject* args, 
340                                                                                           PyObject* kwds) {
341         PyObject *retVal = PyList_New(3);
342
343         PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_prevSourcePoint[0]));
344         PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_prevSourcePoint[1]));
345         PyList_SetItem(retVal, 2, PyFloat_FromDouble(m_prevSourcePoint[2]));
346         
347         return retVal;
348 }
349
350 /* eof */
351