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