BGE Bugfix
[blender.git] / source / gameengine / Ketsji / KX_MouseFocusSensor.cpp
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL 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.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * KX_MouseFocusSensor determines mouse in/out/over events.
29  */
30
31 #ifdef WIN32
32 // This warning tells us about truncation of __long__ stl-generated names.
33 // It can occasionally cause DevStudio to have internal compiler warnings.
34 #pragma warning( disable : 4786 )     
35 #endif
36
37 #include "MT_Point3.h"
38 #include "RAS_FramingManager.h"
39 #include "RAS_ICanvas.h"
40 #include "RAS_IRasterizer.h"
41 #include "SCA_IScene.h"
42 #include "KX_Scene.h"
43 #include "KX_Camera.h"
44 #include "KX_MouseFocusSensor.h"
45 #include "KX_PyMath.h"
46
47 #include "KX_RayCast.h"
48 #include "KX_IPhysicsController.h"
49 #include "PHY_IPhysicsController.h"
50 #include "PHY_IPhysicsEnvironment.h"
51
52
53 #include "KX_ClientObjectInfo.h"
54
55 /* ------------------------------------------------------------------------- */
56 /* Native functions                                                          */
57 /* ------------------------------------------------------------------------- */
58
59 KX_MouseFocusSensor::KX_MouseFocusSensor(SCA_MouseManager* eventmgr, 
60                                                                                  int startx,
61                                                                                  int starty,
62                                                                                  short int mousemode,
63                                                                                  int focusmode,
64                                                                                  RAS_ICanvas* canvas,
65                                                                                  KX_Scene* kxscene,
66                                                                                  KX_KetsjiEngine *kxengine,
67                                                                                  SCA_IObject* gameobj, 
68                                                                                  PyTypeObject* T)
69     : SCA_MouseSensor(eventmgr, startx, starty, mousemode, gameobj, T),
70           m_focusmode(focusmode),
71           m_gp_canvas(canvas),
72           m_kxscene(kxscene),
73           m_kxengine(kxengine)
74 {
75         Init();
76 }
77
78 void KX_MouseFocusSensor::Init()
79 {
80         m_mouse_over_in_previous_frame = (m_invert)?true:false;
81         m_positive_event = false;
82         m_hitObject = 0;
83         m_reset = true;
84 }
85
86 bool KX_MouseFocusSensor::Evaluate(CValue* event)
87 {
88         bool result = false;
89         bool obHasFocus = false;
90         bool reset = m_reset && m_level;
91
92 //      cout << "evaluate focus mouse sensor "<<endl;
93         m_reset = false;
94         if (m_focusmode) {
95                 /* Focus behaviour required. Test mouse-on. The rest is
96                  * equivalent to handling a key. */
97                 obHasFocus = ParentObjectHasFocus();
98                 
99                 if (!obHasFocus) {
100                         m_positive_event = false;
101                         if (m_mouse_over_in_previous_frame) {
102                                 result = true;
103                         } 
104                 } else {
105                         m_positive_event = true;
106                         if (!m_mouse_over_in_previous_frame) {
107                                 result = true;
108                         } 
109                 } 
110                 if (reset) {
111                         // force an event 
112                         result = true;
113                 }
114         } else {
115                 /* No focus behaviour required: revert to the basic mode. This
116          * mode is never used, because the converter never makes this
117          * sensor for a mouse-key event. It is here for
118          * completeness. */
119                 result = SCA_MouseSensor::Evaluate(event);
120                 m_positive_event = (m_val!=0);
121         }
122
123         m_mouse_over_in_previous_frame = obHasFocus;
124
125         return result;
126 }
127
128 bool KX_MouseFocusSensor::RayHit(KX_ClientObjectInfo* client_info, KX_RayCast* result, void * const data)
129 {
130         KX_GameObject* hitKXObj = client_info->m_gameobject;
131         
132         /* Is this me? In the ray test, there are a lot of extra checks
133         * for aliasing artefacts from self-hits. That doesn't happen
134         * here, so a simple test suffices. Or does the camera also get
135         * self-hits? (No, and the raysensor shouldn't do it either, since
136         * self-hits are excluded by setting the correct ignore-object.)
137         * Hitspots now become valid. */
138         KX_GameObject* thisObj = (KX_GameObject*) GetParent();
139         if ((m_focusmode == 2) || hitKXObj == thisObj)
140         {
141                 m_hitObject = hitKXObj;
142                 m_hitPosition = result->m_hitPoint;
143                 m_hitNormal = result->m_hitNormal;
144                 return true;
145         }
146         
147         return true;     // object must be visible to trigger
148         //return false;  // occluded objects can trigger
149 }
150
151
152
153 bool KX_MouseFocusSensor::ParentObjectHasFocus()
154 {
155         m_hitObject = 0;
156         m_hitPosition.setValue(0,0,0);
157         m_hitNormal.setValue(1,0,0);
158
159         /* All screen handling in the gameengine is done by GL,
160          * specifically the model/view and projection parts. The viewport
161          * part is in the creator. 
162          *
163          * The theory is this:
164          * WCS - world coordinates
165          * -> wcs_camcs_trafo ->
166          * camCS - camera coordinates
167          * -> camcs_clip_trafo ->
168          * clipCS - normalized device coordinates?
169          * -> normview_win_trafo
170          * winCS - window coordinates
171          *
172          * The first two transforms are respectively the model/view and
173          * the projection matrix. These are passed to the rasterizer, and
174          * we store them in the camera for easy access.
175          *
176          * For normalized device coords (xn = x/w, yn = y/w/zw) the
177          * windows coords become (lb = left bottom)
178          *
179          * xwin = [(xn + 1.0) * width]/2 + x_lb
180          * ywin = [(yn + 1.0) * height]/2 + y_lb
181          *
182          * Inverting (blender y is flipped!):
183          *
184          * xn = 2(xwin - x_lb)/width - 1.0
185          * yn = 2(ywin - y_lb)/height - 1.0 
186          *    = 2(height - y_blender - y_lb)/height - 1.0
187          *    = 1.0 - 2(y_blender - y_lb)/height
188          *
189          * */
190         
191         MT_Vector4 frompoint;
192         MT_Vector4 topoint;
193         
194         bool result = false;
195         
196         /* Because we don't want to worry about resize events, camera
197          * changes and all that crap, we just determine this over and
198          * over. Stop whining. We have lots of other calculations to do
199          * here as well. These reads are not the main cost. If there is no
200          * canvas, the test is irrelevant. The 1.0 makes sure the
201          * calculations don't bomb. Maybe we should explicitly guard for
202          * division by 0.0...*/
203         list<class KX_Camera*>* cameras = m_kxscene->GetCameras();
204         
205         // Draw the scene once for each camera with an enabled viewport
206         list<KX_Camera*>::iterator it = cameras->begin();
207         while(it != cameras->end())
208         {
209                 if((*it)->GetViewport())
210                 {
211                         KX_Camera* cam= (*it);
212                 
213                         /* get the scenes current viewport. we recompute it because there
214                          * may be multiple cameras and m_kxscene->GetSceneViewport() only
215                          * has the one that was last drawn */
216
217                         RAS_Rect area, viewport;
218                         m_kxengine->GetSceneViewport(m_kxscene, cam, area, viewport);
219                         
220                         /* Check if the mouse is in the viewport */
221                         if (    m_x < viewport.m_x2 &&  // less then right
222                                         m_x > viewport.m_x1 &&  // more then then left
223                                         m_y < viewport.m_y2 &&  // below top
224                                         m_y > viewport.m_y1)    // above bottom
225                         {
226                                 float height = float(viewport.m_y2 - viewport.m_y1 + 1);
227                                 float width  = float(viewport.m_x2 - viewport.m_x1 + 1);
228                                 
229                                 float x_lb = float(viewport.m_x1);
230                                 float y_lb = float(viewport.m_y1);
231
232                                 /* There's some strangeness I don't fully get here... These values
233                                  * _should_ be wrong! - see from point Z values */
234                                 
235                                 
236                                 /*      build the from and to point in normalized device coordinates 
237                                  *      Looks like normailized device coordinates are [-1,1] in x [-1,1] in y
238                                  *      [0,-1] in z 
239                                  *      
240                                  *      The actual z coordinates used don't have to be exact just infront and 
241                                  *      behind of the near and far clip planes.
242                                  */ 
243                                 frompoint.setValue(     (2 * (m_x-x_lb) / width) - 1.0,
244                                                                         1.0 - (2 * (m_y - y_lb) / height),
245                                                                         0.0, /* nearclip, see above comments */
246                                                                         1.0 );
247                                 
248                                 topoint.setValue(       (2 * (m_x-x_lb) / width) - 1.0,
249                                                                         1.0 - (2 * (m_y-y_lb) / height),
250                                                                         1.0, /* farclip, see above comments */
251                                                                         1.0 );
252
253                                 /* camera to world  */
254                                 MT_Transform wcs_camcs_tranform = cam->GetWorldToCamera();
255                                 if (!cam->GetCameraData()->m_perspective)
256                                         wcs_camcs_tranform.getOrigin()[2] *= 100.0;
257                                 MT_Transform cams_wcs_transform;
258                                 cams_wcs_transform.invert(wcs_camcs_tranform);
259                                 
260                                 MT_Matrix4x4 camcs_wcs_matrix = MT_Matrix4x4(cams_wcs_transform);
261
262                                 /* badly defined, the first time round.... I wonder why... I might
263                                  * want to guard against floating point errors here.*/
264                                 MT_Matrix4x4 clip_camcs_matrix = MT_Matrix4x4(cam->GetProjectionMatrix());
265                                 clip_camcs_matrix.invert();
266
267                                 /* shoot-points: clip to cam to wcs . win to clip was already done.*/
268                                 frompoint = clip_camcs_matrix * frompoint;
269                                 topoint   = clip_camcs_matrix * topoint;
270                                 frompoint = camcs_wcs_matrix * frompoint;
271                                 topoint   = camcs_wcs_matrix * topoint;
272                                 
273                                 /* from hom wcs to 3d wcs: */
274                                 m_prevSourcePoint.setValue(     frompoint[0]/frompoint[3],
275                                                                                         frompoint[1]/frompoint[3],
276                                                                                         frompoint[2]/frompoint[3]); 
277                                 
278                                 m_prevTargetPoint.setValue(     topoint[0]/topoint[3],
279                                                                                         topoint[1]/topoint[3],
280                                                                                         topoint[2]/topoint[3]); 
281                                 
282                                 /* 2. Get the object from PhysicsEnvironment */
283                                 /* Shoot! Beware that the first argument here is an
284                                  * ignore-object. We don't ignore anything... */
285                                 KX_IPhysicsController* physics_controller = cam->GetPhysicsController();
286                                 PHY_IPhysicsEnvironment* physics_environment = m_kxscene->GetPhysicsEnvironment();
287
288                                 KX_RayCast::Callback<KX_MouseFocusSensor> callback(this,physics_controller);
289                                  
290                                 KX_RayCast::RayTest(physics_environment, m_prevSourcePoint, m_prevTargetPoint, callback);
291                                 
292                                 if (m_hitObject) {
293                                         result= true;
294                                         break;
295                                 }
296                         }
297                 }
298                 it++;
299         }
300         
301         return result;
302 }
303
304 /* ------------------------------------------------------------------------- */
305 /* Python functions                                                          */
306 /* ------------------------------------------------------------------------- */
307
308 /* Integration hooks ------------------------------------------------------- */
309 PyTypeObject KX_MouseFocusSensor::Type = {
310         PyObject_HEAD_INIT(NULL)
311         0,
312         "KX_MouseFocusSensor",
313         sizeof(KX_MouseFocusSensor),
314         0,
315         PyDestructor,
316         0,
317         0,
318         0,
319         0,
320         py_base_repr,
321         0,0,0,0,0,0,
322         py_base_getattro,
323         py_base_setattro,
324         0,0,0,0,0,0,0,0,0,
325         Methods
326 };
327
328 PyParentObject KX_MouseFocusSensor::Parents[] = {
329         &KX_MouseFocusSensor::Type,
330         &SCA_MouseSensor::Type,
331         &SCA_ISensor::Type,
332         &SCA_ILogicBrick::Type,
333         &CValue::Type,
334         NULL
335 };
336
337 PyMethodDef KX_MouseFocusSensor::Methods[] = {
338         {"getRayTarget", (PyCFunction) KX_MouseFocusSensor::sPyGetRayTarget, METH_NOARGS, (PY_METHODCHAR)GetRayTarget_doc},
339         {"getRaySource", (PyCFunction) KX_MouseFocusSensor::sPyGetRaySource, METH_NOARGS, (PY_METHODCHAR)GetRaySource_doc},
340         {"getHitObject",(PyCFunction) KX_MouseFocusSensor::sPyGetHitObject,METH_NOARGS, (PY_METHODCHAR)GetHitObject_doc},
341         {"getHitPosition",(PyCFunction) KX_MouseFocusSensor::sPyGetHitPosition,METH_NOARGS, (PY_METHODCHAR)GetHitPosition_doc},
342         {"getHitNormal",(PyCFunction) KX_MouseFocusSensor::sPyGetHitNormal,METH_NOARGS, (PY_METHODCHAR)GetHitNormal_doc},
343         {"getRayDirection",(PyCFunction) KX_MouseFocusSensor::sPyGetRayDirection,METH_NOARGS, (PY_METHODCHAR)GetRayDirection_doc},
344
345
346         {NULL,NULL} //Sentinel
347 };
348
349 PyAttributeDef KX_MouseFocusSensor::Attributes[] = {
350         { NULL }        //Sentinel
351 };
352
353 PyObject* KX_MouseFocusSensor::py_getattro(PyObject *attr) {
354         py_getattro_up(SCA_MouseSensor);
355 }
356
357
358 const char KX_MouseFocusSensor::GetHitObject_doc[] = 
359 "getHitObject()\n"
360 "\tReturns the object that was hit by this ray.\n";
361 PyObject* KX_MouseFocusSensor::PyGetHitObject(PyObject* self)
362 {
363         if (m_hitObject)
364                 return m_hitObject->AddRef();
365         
366         Py_RETURN_NONE;
367 }
368
369
370 const char KX_MouseFocusSensor::GetHitPosition_doc[] = 
371 "getHitPosition()\n"
372 "\tReturns the position (in worldcoordinates) where the object was hit by this ray.\n";
373 PyObject* KX_MouseFocusSensor::PyGetHitPosition(PyObject* self)
374 {
375         return PyObjectFrom(m_hitPosition);
376 }
377
378 const char KX_MouseFocusSensor::GetRayDirection_doc[] = 
379 "getRayDirection()\n"
380 "\tReturns the direction from the ray (in worldcoordinates) .\n";
381 PyObject* KX_MouseFocusSensor::PyGetRayDirection(PyObject* self)
382 {
383
384         MT_Vector3 dir = m_prevTargetPoint - m_prevSourcePoint;
385         dir.normalize();
386         return PyObjectFrom(dir);
387 }
388
389 const char KX_MouseFocusSensor::GetHitNormal_doc[] = 
390 "getHitNormal()\n"
391 "\tReturns the normal (in worldcoordinates) at the point of collision where the object was hit by this ray.\n";
392 PyObject* KX_MouseFocusSensor::PyGetHitNormal(PyObject* self)
393 {
394         return PyObjectFrom(m_hitNormal);
395 }
396
397
398 /*  getRayTarget                                                */
399 const char KX_MouseFocusSensor::GetRayTarget_doc[] = 
400 "getRayTarget()\n"
401 "\tReturns the target of the ray that seeks the focus object,\n"
402 "\tin worldcoordinates.";
403 PyObject* KX_MouseFocusSensor::PyGetRayTarget(PyObject* self) {
404         return PyObjectFrom(m_prevTargetPoint);
405 }
406
407 /*  getRayTarget                                                */
408 const char KX_MouseFocusSensor::GetRaySource_doc[] = 
409 "getRaySource()\n"
410 "\tReturns the source of the ray that seeks the focus object,\n"
411 "\tin worldcoordinates.";
412 PyObject* KX_MouseFocusSensor::PyGetRaySource(PyObject* self) {
413         return PyObjectFrom(m_prevSourcePoint);
414 }
415
416 /* eof */
417