BGE MouseFocusSensor
[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                                                                                  KX_Scene* kxscene,
65                                                                                  KX_KetsjiEngine *kxengine,
66                                                                                  SCA_IObject* gameobj, 
67                                                                                  PyTypeObject* T)
68     : SCA_MouseSensor(eventmgr, startx, starty, mousemode, gameobj, T),
69           m_focusmode(focusmode),
70           m_kxscene(kxscene),
71           m_kxengine(kxengine)
72 {
73         Init();
74 }
75
76 void KX_MouseFocusSensor::Init()
77 {
78         m_mouse_over_in_previous_frame = (m_invert)?true:false;
79         m_positive_event = false;
80         m_hitObject = 0;
81         m_reset = true;
82         
83         m_hitPosition.setValue(0,0,0);
84         m_prevTargetPoint.setValue(0,0,0);
85         m_prevSourcePoint.setValue(0,0,0);
86         m_hitNormal.setValue(0,0,1);
87 }
88
89 bool KX_MouseFocusSensor::Evaluate(CValue* event)
90 {
91         bool result = false;
92         bool obHasFocus = false;
93         bool reset = m_reset && m_level;
94
95 //      cout << "evaluate focus mouse sensor "<<endl;
96         m_reset = false;
97         if (m_focusmode) {
98                 /* Focus behaviour required. Test mouse-on. The rest is
99                  * equivalent to handling a key. */
100                 obHasFocus = ParentObjectHasFocus();
101                 
102                 if (!obHasFocus) {
103                         m_positive_event = false;
104                         if (m_mouse_over_in_previous_frame) {
105                                 result = true;
106                         } 
107                 } else {
108                         m_positive_event = true;
109                         if (!m_mouse_over_in_previous_frame) {
110                                 result = true;
111                         } 
112                 } 
113                 if (reset) {
114                         // force an event 
115                         result = true;
116                 }
117         } else {
118                 /* No focus behaviour required: revert to the basic mode. This
119          * mode is never used, because the converter never makes this
120          * sensor for a mouse-key event. It is here for
121          * completeness. */
122                 result = SCA_MouseSensor::Evaluate(event);
123                 m_positive_event = (m_val!=0);
124         }
125
126         m_mouse_over_in_previous_frame = obHasFocus;
127
128         return result;
129 }
130
131 bool KX_MouseFocusSensor::RayHit(KX_ClientObjectInfo* client_info, KX_RayCast* result, void * const data)
132 {
133         KX_GameObject* hitKXObj = client_info->m_gameobject;
134         
135         /* Is this me? In the ray test, there are a lot of extra checks
136         * for aliasing artefacts from self-hits. That doesn't happen
137         * here, so a simple test suffices. Or does the camera also get
138         * self-hits? (No, and the raysensor shouldn't do it either, since
139         * self-hits are excluded by setting the correct ignore-object.)
140         * Hitspots now become valid. */
141         KX_GameObject* thisObj = (KX_GameObject*) GetParent();
142         if ((m_focusmode == 2) || hitKXObj == thisObj)
143         {
144                 m_hitObject = hitKXObj;
145                 m_hitPosition = result->m_hitPoint;
146                 m_hitNormal = result->m_hitNormal;
147                 return true;
148         }
149         
150         return true;     // object must be visible to trigger
151         //return false;  // occluded objects can trigger
152 }
153
154
155
156 bool KX_MouseFocusSensor::ParentObjectHasFocusCamera(KX_Camera *cam)
157 {
158         /* All screen handling in the gameengine is done by GL,
159          * specifically the model/view and projection parts. The viewport
160          * part is in the creator. 
161          *
162          * The theory is this:
163          * WCS - world coordinates
164          * -> wcs_camcs_trafo ->
165          * camCS - camera coordinates
166          * -> camcs_clip_trafo ->
167          * clipCS - normalized device coordinates?
168          * -> normview_win_trafo
169          * winCS - window coordinates
170          *
171          * The first two transforms are respectively the model/view and
172          * the projection matrix. These are passed to the rasterizer, and
173          * we store them in the camera for easy access.
174          *
175          * For normalized device coords (xn = x/w, yn = y/w/zw) the
176          * windows coords become (lb = left bottom)
177          *
178          * xwin = [(xn + 1.0) * width]/2 + x_lb
179          * ywin = [(yn + 1.0) * height]/2 + y_lb
180          *
181          * Inverting (blender y is flipped!):
182          *
183          * xn = 2(xwin - x_lb)/width - 1.0
184          * yn = 2(ywin - y_lb)/height - 1.0 
185          *    = 2(height - y_blender - y_lb)/height - 1.0
186          *    = 1.0 - 2(y_blender - y_lb)/height
187          *
188          * */
189          
190         
191         /* Because we don't want to worry about resize events, camera
192          * changes and all that crap, we just determine this over and
193          * over. Stop whining. We have lots of other calculations to do
194          * here as well. These reads are not the main cost. If there is no
195          * canvas, the test is irrelevant. The 1.0 makes sure the
196          * calculations don't bomb. Maybe we should explicitly guard for
197          * division by 0.0...*/
198         
199         RAS_Rect area, viewport;
200         m_kxengine->GetSceneViewport(m_kxscene, cam, area, viewport);
201         
202         /* Check if the mouse is in the viewport */
203         if ((   m_x < viewport.m_x2 &&  // less then right
204                         m_x > viewport.m_x1 &&  // more then then left
205                         m_y < viewport.m_y2 &&  // below top
206                         m_y > viewport.m_y1) == 0)      // above bottom
207         {
208                 return false;
209         }
210
211         float height = float(viewport.m_y2 - viewport.m_y1 + 1);
212         float width  = float(viewport.m_x2 - viewport.m_x1 + 1);
213         
214         float x_lb = float(viewport.m_x1);
215         float y_lb = float(viewport.m_y1);
216
217         MT_Vector4 frompoint;
218         MT_Vector4 topoint;
219         
220         /* There's some strangeness I don't fully get here... These values
221          * _should_ be wrong! - see from point Z values */
222         
223         
224         /*      build the from and to point in normalized device coordinates 
225          *      Looks like normailized device coordinates are [-1,1] in x [-1,1] in y
226          *      [0,-1] in z 
227          *      
228          *      The actual z coordinates used don't have to be exact just infront and 
229          *      behind of the near and far clip planes.
230          */ 
231         frompoint.setValue(     (2 * (m_x-x_lb) / width) - 1.0,
232                                                 1.0 - (2 * (m_y - y_lb) / height),
233                                                 0.0, /* nearclip, see above comments */
234                                                 1.0 );
235         
236         topoint.setValue(       (2 * (m_x-x_lb) / width) - 1.0,
237                                                 1.0 - (2 * (m_y-y_lb) / height),
238                                                 1.0, /* farclip, see above comments */
239                                                 1.0 );
240
241         /* camera to world  */
242         MT_Transform wcs_camcs_tranform = cam->GetWorldToCamera();
243         if (!cam->GetCameraData()->m_perspective)
244                 wcs_camcs_tranform.getOrigin()[2] *= 100.0;
245         MT_Transform cams_wcs_transform;
246         cams_wcs_transform.invert(wcs_camcs_tranform);
247         
248         MT_Matrix4x4 camcs_wcs_matrix = MT_Matrix4x4(cams_wcs_transform);
249
250         /* badly defined, the first time round.... I wonder why... I might
251          * want to guard against floating point errors here.*/
252         MT_Matrix4x4 clip_camcs_matrix = MT_Matrix4x4(cam->GetProjectionMatrix());
253         clip_camcs_matrix.invert();
254
255         /* shoot-points: clip to cam to wcs . win to clip was already done.*/
256         frompoint = clip_camcs_matrix * frompoint;
257         topoint   = clip_camcs_matrix * topoint;
258         frompoint = camcs_wcs_matrix * frompoint;
259         topoint   = camcs_wcs_matrix * topoint;
260         
261         /* from hom wcs to 3d wcs: */
262         m_prevSourcePoint.setValue(     frompoint[0]/frompoint[3],
263                                                                 frompoint[1]/frompoint[3],
264                                                                 frompoint[2]/frompoint[3]); 
265         
266         m_prevTargetPoint.setValue(     topoint[0]/topoint[3],
267                                                                 topoint[1]/topoint[3],
268                                                                 topoint[2]/topoint[3]); 
269         
270         /* 2. Get the object from PhysicsEnvironment */
271         /* Shoot! Beware that the first argument here is an
272          * ignore-object. We don't ignore anything... */
273         KX_IPhysicsController* physics_controller = cam->GetPhysicsController();
274         PHY_IPhysicsEnvironment* physics_environment = m_kxscene->GetPhysicsEnvironment();
275
276         KX_RayCast::Callback<KX_MouseFocusSensor> callback(this,physics_controller);
277          
278         KX_RayCast::RayTest(physics_environment, m_prevSourcePoint, m_prevTargetPoint, callback);
279         
280         if (m_hitObject)
281                 return true;
282         
283         return false;
284 }
285
286 bool KX_MouseFocusSensor::ParentObjectHasFocus()
287 {
288         m_hitObject = 0;
289         m_hitPosition.setValue(0,0,0);
290         m_hitNormal.setValue(1,0,0);
291         
292         KX_Camera *cam= m_kxscene->GetActiveCamera();
293         
294         if(ParentObjectHasFocusCamera(cam))
295                 return true;
296
297         list<class KX_Camera*>* cameras = m_kxscene->GetCameras();
298         list<KX_Camera*>::iterator it = cameras->begin();
299         
300         while(it != cameras->end())
301         {
302                 if(((*it) != cam) && (*it)->GetViewport())
303                         if (ParentObjectHasFocusCamera(*it))
304                                 return true;
305                 
306                 it++;
307         }
308         
309         return false;
310 }
311
312 const MT_Point3& KX_MouseFocusSensor::RaySource() const
313 {
314         return m_prevSourcePoint;
315 }
316
317 const MT_Point3& KX_MouseFocusSensor::RayTarget() const
318 {
319         return m_prevTargetPoint;
320 }
321
322 const MT_Point3& KX_MouseFocusSensor::HitPosition() const
323 {
324         return m_hitPosition;
325 }
326
327 const MT_Vector3& KX_MouseFocusSensor::HitNormal() const
328 {
329         return m_hitNormal;
330 }
331
332 /* ------------------------------------------------------------------------- */
333 /* Python functions                                                          */
334 /* ------------------------------------------------------------------------- */
335
336 /* Integration hooks ------------------------------------------------------- */
337 PyTypeObject KX_MouseFocusSensor::Type = {
338         PyObject_HEAD_INIT(NULL)
339         0,
340         "KX_MouseFocusSensor",
341         sizeof(KX_MouseFocusSensor),
342         0,
343         PyDestructor,
344         0,
345         0,
346         0,
347         0,
348         py_base_repr,
349         0,0,0,0,0,0,
350         py_base_getattro,
351         py_base_setattro,
352         0,0,0,0,0,0,0,0,0,
353         Methods
354 };
355
356 PyParentObject KX_MouseFocusSensor::Parents[] = {
357         &KX_MouseFocusSensor::Type,
358         &SCA_MouseSensor::Type,
359         &SCA_ISensor::Type,
360         &SCA_ILogicBrick::Type,
361         &CValue::Type,
362         NULL
363 };
364
365 PyMethodDef KX_MouseFocusSensor::Methods[] = {
366         {"getRayTarget", (PyCFunction) KX_MouseFocusSensor::sPyGetRayTarget, METH_NOARGS, (PY_METHODCHAR)GetRayTarget_doc},
367         {"getRaySource", (PyCFunction) KX_MouseFocusSensor::sPyGetRaySource, METH_NOARGS, (PY_METHODCHAR)GetRaySource_doc},
368         {"getHitObject",(PyCFunction) KX_MouseFocusSensor::sPyGetHitObject,METH_NOARGS, (PY_METHODCHAR)GetHitObject_doc},
369         {"getHitPosition",(PyCFunction) KX_MouseFocusSensor::sPyGetHitPosition,METH_NOARGS, (PY_METHODCHAR)GetHitPosition_doc},
370         {"getHitNormal",(PyCFunction) KX_MouseFocusSensor::sPyGetHitNormal,METH_NOARGS, (PY_METHODCHAR)GetHitNormal_doc},
371         {"getRayDirection",(PyCFunction) KX_MouseFocusSensor::sPyGetRayDirection,METH_NOARGS, (PY_METHODCHAR)GetRayDirection_doc},
372
373         {NULL,NULL} //Sentinel
374 };
375
376 PyAttributeDef KX_MouseFocusSensor::Attributes[] = {
377         KX_PYATTRIBUTE_RO_FUNCTION("raySource",         KX_MouseFocusSensor, pyattr_get_ray_source),
378         KX_PYATTRIBUTE_RO_FUNCTION("rayTarget",         KX_MouseFocusSensor, pyattr_get_ray_target),
379         KX_PYATTRIBUTE_RO_FUNCTION("rayDirection",      KX_MouseFocusSensor, pyattr_get_ray_direction),
380         KX_PYATTRIBUTE_RO_FUNCTION("hitObject",         KX_MouseFocusSensor, pyattr_get_hit_object),
381         KX_PYATTRIBUTE_RO_FUNCTION("hitPosition",       KX_MouseFocusSensor, pyattr_get_hit_position),
382         KX_PYATTRIBUTE_RO_FUNCTION("hitNormal",         KX_MouseFocusSensor, pyattr_get_hit_normal),
383         { NULL }        //Sentinel
384 };
385
386 PyObject* KX_MouseFocusSensor::py_getattro(PyObject *attr) {
387         py_getattro_up(SCA_MouseSensor);
388 }
389
390
391 const char KX_MouseFocusSensor::GetHitObject_doc[] = 
392 "getHitObject()\n"
393 "\tReturns the object that was hit by this ray.\n";
394 PyObject* KX_MouseFocusSensor::PyGetHitObject(PyObject* self)
395 {
396         ShowDeprecationWarning("GetHitObject()", "the hitObject property");
397         
398         if (m_hitObject)
399                 return m_hitObject->AddRef();
400         
401         Py_RETURN_NONE;
402 }
403
404
405 const char KX_MouseFocusSensor::GetHitPosition_doc[] = 
406 "getHitPosition()\n"
407 "\tReturns the position (in worldcoordinates) where the object was hit by this ray.\n";
408 PyObject* KX_MouseFocusSensor::PyGetHitPosition(PyObject* self)
409 {
410         ShowDeprecationWarning("getHitPosition()", "the hitPosition property");
411         
412         return PyObjectFrom(m_hitPosition);
413 }
414
415 const char KX_MouseFocusSensor::GetRayDirection_doc[] = 
416 "getRayDirection()\n"
417 "\tReturns the direction from the ray (in worldcoordinates) .\n";
418 PyObject* KX_MouseFocusSensor::PyGetRayDirection(PyObject* self)
419 {
420         ShowDeprecationWarning("getRayDirection()", "the rayDirection property");
421         
422         MT_Vector3 dir = m_prevTargetPoint - m_prevSourcePoint;
423         if(MT_fuzzyZero(dir))   dir.setValue(0,0,0);
424         else                                    dir.normalize();
425         return PyObjectFrom(dir);
426 }
427
428 const char KX_MouseFocusSensor::GetHitNormal_doc[] = 
429 "getHitNormal()\n"
430 "\tReturns the normal (in worldcoordinates) at the point of collision where the object was hit by this ray.\n";
431 PyObject* KX_MouseFocusSensor::PyGetHitNormal(PyObject* self)
432 {
433         ShowDeprecationWarning("getHitNormal()", "the hitNormal property");
434         
435         return PyObjectFrom(m_hitNormal);
436 }
437
438
439 /*  getRayTarget                                                */
440 const char KX_MouseFocusSensor::GetRayTarget_doc[] = 
441 "getRayTarget()\n"
442 "\tReturns the target of the ray that seeks the focus object,\n"
443 "\tin worldcoordinates.";
444 PyObject* KX_MouseFocusSensor::PyGetRayTarget(PyObject* self)
445 {
446         ShowDeprecationWarning("getRayTarget()", "the rayTarget property");
447         
448         return PyObjectFrom(m_prevTargetPoint);
449 }
450
451 /*  getRayTarget                                                */
452 const char KX_MouseFocusSensor::GetRaySource_doc[] = 
453 "getRaySource()\n"
454 "\tReturns the source of the ray that seeks the focus object,\n"
455 "\tin worldcoordinates.";
456 PyObject* KX_MouseFocusSensor::PyGetRaySource(PyObject* self)
457 {
458         ShowDeprecationWarning("getRaySource()", "the raySource property");
459         
460         return PyObjectFrom(m_prevSourcePoint);
461 }
462
463 /* Attributes */
464 PyObject* KX_MouseFocusSensor::pyattr_get_ray_source(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
465 {
466         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
467         return PyObjectFrom(self->RaySource());
468 }
469
470 PyObject* KX_MouseFocusSensor::pyattr_get_ray_target(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
471 {
472         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
473         return PyObjectFrom(self->RayTarget());
474 }
475
476 PyObject* KX_MouseFocusSensor::pyattr_get_ray_direction(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
477 {
478         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
479         MT_Vector3 dir = self->RayTarget() - self->RaySource();
480         if(MT_fuzzyZero(dir))   dir.setValue(0,0,0);
481         else                                    dir.normalize();
482         return PyObjectFrom(dir);
483 }
484
485 PyObject* KX_MouseFocusSensor::pyattr_get_hit_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
486 {
487         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
488         
489         if(self->m_hitObject)
490                 return self->m_hitObject->AddRef();
491         
492         Py_RETURN_NONE;
493 }
494
495 PyObject* KX_MouseFocusSensor::pyattr_get_hit_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
496 {
497         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
498         return PyObjectFrom(self->HitPosition());
499 }
500
501 PyObject* KX_MouseFocusSensor::pyattr_get_hit_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
502 {
503         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
504         return PyObjectFrom(self->HitNormal());
505 }
506
507
508
509 /* eof */
510