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