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