doxygen: prevent GPL license block from being parsed as doxygen comment.
[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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 #if defined(WIN32) && !defined(FREE_WINDOWS)
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                 m_hitUV = result->m_hitUV;
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         // get UV mapping
289         KX_RayCast::Callback<KX_MouseFocusSensor> callback(this,physics_controller,NULL,false,true);
290          
291         KX_RayCast::RayTest(physics_environment, m_prevSourcePoint, m_prevTargetPoint, callback);
292         
293         if (m_hitObject)
294                 return true;
295         
296         return false;
297 }
298
299 bool KX_MouseFocusSensor::ParentObjectHasFocus()
300 {
301         m_hitObject = 0;
302         m_hitPosition.setValue(0,0,0);
303         m_hitNormal.setValue(1,0,0);
304         
305         KX_Camera *cam= m_kxscene->GetActiveCamera();
306         
307         if(ParentObjectHasFocusCamera(cam))
308                 return true;
309
310         list<class KX_Camera*>* cameras = m_kxscene->GetCameras();
311         list<KX_Camera*>::iterator it = cameras->begin();
312         
313         while(it != cameras->end())
314         {
315                 if(((*it) != cam) && (*it)->GetViewport())
316                         if (ParentObjectHasFocusCamera(*it))
317                                 return true;
318                 
319                 it++;
320         }
321         
322         return false;
323 }
324
325 const MT_Point3& KX_MouseFocusSensor::RaySource() const
326 {
327         return m_prevSourcePoint;
328 }
329
330 const MT_Point3& KX_MouseFocusSensor::RayTarget() const
331 {
332         return m_prevTargetPoint;
333 }
334
335 const MT_Point3& KX_MouseFocusSensor::HitPosition() const
336 {
337         return m_hitPosition;
338 }
339
340 const MT_Vector3& KX_MouseFocusSensor::HitNormal() const
341 {
342         return m_hitNormal;
343 }
344
345 const MT_Vector2& KX_MouseFocusSensor::HitUV() const
346 {
347         return m_hitUV;
348 }
349
350 #ifdef WITH_PYTHON
351
352 /* ------------------------------------------------------------------------- */
353 /* Python functions                                                          */
354 /* ------------------------------------------------------------------------- */
355
356 /* Integration hooks ------------------------------------------------------- */
357 PyTypeObject KX_MouseFocusSensor::Type = {
358         PyVarObject_HEAD_INIT(NULL, 0)
359         "KX_MouseFocusSensor",
360         sizeof(PyObjectPlus_Proxy),
361         0,
362         py_base_dealloc,
363         0,
364         0,
365         0,
366         0,
367         py_base_repr,
368         0,0,0,0,0,0,0,0,0,
369         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
370         0,0,0,0,0,0,0,
371         Methods,
372         0,
373         0,
374         &SCA_MouseSensor::Type,
375         0,0,0,0,0,0,
376         py_base_new
377 };
378
379 PyMethodDef KX_MouseFocusSensor::Methods[] = {
380         {NULL,NULL} //Sentinel
381 };
382
383 PyAttributeDef KX_MouseFocusSensor::Attributes[] = {
384         KX_PYATTRIBUTE_RO_FUNCTION("raySource",         KX_MouseFocusSensor, pyattr_get_ray_source),
385         KX_PYATTRIBUTE_RO_FUNCTION("rayTarget",         KX_MouseFocusSensor, pyattr_get_ray_target),
386         KX_PYATTRIBUTE_RO_FUNCTION("rayDirection",      KX_MouseFocusSensor, pyattr_get_ray_direction),
387         KX_PYATTRIBUTE_RO_FUNCTION("hitObject",         KX_MouseFocusSensor, pyattr_get_hit_object),
388         KX_PYATTRIBUTE_RO_FUNCTION("hitPosition",       KX_MouseFocusSensor, pyattr_get_hit_position),
389         KX_PYATTRIBUTE_RO_FUNCTION("hitNormal",         KX_MouseFocusSensor, pyattr_get_hit_normal),
390         KX_PYATTRIBUTE_RO_FUNCTION("hitUV",             KX_MouseFocusSensor, pyattr_get_hit_uv),
391         KX_PYATTRIBUTE_BOOL_RW("usePulseFocus", KX_MouseFocusSensor,m_bTouchPulse),
392         { NULL }        //Sentinel
393 };
394
395 /* Attributes */
396 PyObject* KX_MouseFocusSensor::pyattr_get_ray_source(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
397 {
398         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
399         return PyObjectFrom(self->RaySource());
400 }
401
402 PyObject* KX_MouseFocusSensor::pyattr_get_ray_target(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
403 {
404         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
405         return PyObjectFrom(self->RayTarget());
406 }
407
408 PyObject* KX_MouseFocusSensor::pyattr_get_ray_direction(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
409 {
410         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
411         MT_Vector3 dir = self->RayTarget() - self->RaySource();
412         if(MT_fuzzyZero(dir))   dir.setValue(0,0,0);
413         else                                    dir.normalize();
414         return PyObjectFrom(dir);
415 }
416
417 PyObject* KX_MouseFocusSensor::pyattr_get_hit_object(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
418 {
419         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
420         
421         if(self->m_hitObject)
422                 return self->m_hitObject->GetProxy();
423         
424         Py_RETURN_NONE;
425 }
426
427 PyObject* KX_MouseFocusSensor::pyattr_get_hit_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
428 {
429         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
430         return PyObjectFrom(self->HitPosition());
431 }
432
433 PyObject* KX_MouseFocusSensor::pyattr_get_hit_normal(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
434 {
435         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
436         return PyObjectFrom(self->HitNormal());
437 }
438
439 PyObject* KX_MouseFocusSensor::pyattr_get_hit_uv(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
440 {
441         KX_MouseFocusSensor* self= static_cast<KX_MouseFocusSensor*>(self_v);
442         return PyObjectFrom(self->HitUV());
443 }
444
445 #endif // WITH_PYTHON
446
447 /* eof */
448