svn merge -r 14236:14505 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[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
46 #include "KX_RayCast.h"
47 #include "KX_IPhysicsController.h"
48 #include "PHY_IPhysicsController.h"
49 #include "PHY_IPhysicsEnvironment.h"
50
51
52 #include "KX_ClientObjectInfo.h"
53
54 /* ------------------------------------------------------------------------- */
55 /* Native functions                                                          */
56 /* ------------------------------------------------------------------------- */
57
58 KX_MouseFocusSensor::KX_MouseFocusSensor(SCA_MouseManager* eventmgr, 
59                                                                                  int startx,
60                                                                                  int starty,
61                                                                                  short int mousemode,
62                                                                                  int focusmode,
63                                                                                  RAS_ICanvas* canvas,
64                                                                                  KX_Scene* kxscene,
65                                                                                  SCA_IObject* gameobj, 
66                                                                                  PyTypeObject* T)
67     : SCA_MouseSensor(eventmgr, startx, starty, mousemode, gameobj, T),
68           m_focusmode(focusmode),
69           m_gp_canvas(canvas),
70           m_kxscene(kxscene)
71 {
72
73         m_mouse_over_in_previous_frame = false;
74         m_positive_event = false;
75         m_hitObject = 0;
76
77 }
78
79 bool KX_MouseFocusSensor::Evaluate(CValue* event)
80 {
81         bool result = false;
82         bool obHasFocus = false;
83
84 //      cout << "evaluate focus mouse sensor "<<endl;
85
86         if (m_focusmode) {
87                 /* Focus behaviour required. Test mouse-on. The rest is
88                  * equivalent to handling a key. */
89                 obHasFocus = ParentObjectHasFocus();
90                 
91                 if (!obHasFocus) {
92                         if (m_mouse_over_in_previous_frame) {
93                                         m_positive_event = false;
94                                         result = true;
95                         } 
96                 } else {
97                         if (!m_mouse_over_in_previous_frame) {
98                                 m_positive_event = true;
99                                 result = true;
100                         } 
101                 } 
102         } else {
103                 /* No focus behaviour required: revert to the basic mode. This
104          * mode is never used, because the converter never makes this
105          * sensor for a mouse-key event. It is here for
106          * completeness. */
107                 result = SCA_MouseSensor::Evaluate(event);
108                 m_positive_event = (m_val!=0);
109         }
110
111         m_mouse_over_in_previous_frame = obHasFocus;
112
113         return result;
114 }
115
116 bool KX_MouseFocusSensor::RayHit(KX_ClientObjectInfo* client_info, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data)
117 {
118         KX_GameObject* hitKXObj = client_info->m_gameobject;
119         
120         if (client_info->m_type > KX_ClientObjectInfo::ACTOR)
121         {
122                 // false hit
123                 return false;
124         }
125         
126         /* Is this me? In the ray test, there are a lot of extra checks
127         * for aliasing artefacts from self-hits. That doesn't happen
128         * here, so a simple test suffices. Or does the camera also get
129         * self-hits? (No, and the raysensor shouldn't do it either, since
130         * self-hits are excluded by setting the correct ignore-object.)
131         * Hitspots now become valid. */
132         KX_GameObject* thisObj = (KX_GameObject*) GetParent();
133         if ((m_focusmode == 2) || hitKXObj == thisObj)
134         {
135                 m_hitObject = hitKXObj;
136                 m_hitPosition = hit_point;
137                 m_hitNormal = hit_normal;
138                 return true;
139         }
140         
141         return true;     // object must be visible to trigger
142         //return false;  // occluded objects can trigger
143 }
144
145
146
147 bool KX_MouseFocusSensor::ParentObjectHasFocus(void)
148 {
149         m_hitObject = 0;
150         m_hitPosition = MT_Vector3(0,0,0);
151         m_hitNormal =   MT_Vector3(1,0,0);
152         MT_Point3 resultpoint;
153         MT_Vector3 resultnormal;
154
155         /* All screen handling in the gameengine is done by GL,
156          * specifically the model/view and projection parts. The viewport
157          * part is in the creator. 
158          *
159          * The theory is this:
160          * WCS - world coordinates
161          * -> wcs_camcs_trafo ->
162          * camCS - camera coordinates
163          * -> camcs_clip_trafo ->
164          * clipCS - normalized device coordinates?
165          * -> normview_win_trafo
166          * winCS - window coordinates
167          *
168          * The first two transforms are respectively the model/view and
169          * the projection matrix. These are passed to the rasterizer, and
170          * we store them in the camera for easy access.
171          *
172          * For normalized device coords (xn = x/w, yn = y/w/zw) the
173          * windows coords become (lb = left bottom)
174          *
175          * xwin = [(xn + 1.0) * width]/2 + x_lb
176          * ywin = [(yn + 1.0) * height]/2 + y_lb
177          *
178          * Inverting (blender y is flipped!):
179          *
180          * xn = 2(xwin - x_lb)/width - 1.0
181          * yn = 2(ywin - y_lb)/height - 1.0 
182          *    = 2(height - y_blender - y_lb)/height - 1.0
183          *    = 1.0 - 2(y_blender - y_lb)/height
184          *
185          * */
186         
187         /* Because we don't want to worry about resize events, camera
188          * changes and all that crap, we just determine this over and
189          * over. Stop whining. We have lots of other calculations to do
190          * here as well. These reads are not the main cost. If there is no
191          * canvas, the test is irrelevant. The 1.0 makes sure the
192          * calculations don't bomb. Maybe we should explicitly guard for
193          * division by 0.0...*/
194
195         /**
196          * Get the scenes current viewport.
197          */
198
199         const RAS_Rect & viewport = m_kxscene->GetSceneViewport();
200
201         float height = float(viewport.m_y2 - viewport.m_y1 + 1);
202         float width  = float(viewport.m_x2 - viewport.m_x1 + 1);
203         
204         float x_lb = float(viewport.m_x1);
205         float y_lb = float(viewport.m_y1);
206
207         KX_Camera* cam = m_kxscene->GetActiveCamera();
208         /* There's some strangeness I don't fully get here... These values
209          * _should_ be wrong! */
210
211         /* old: */
212         float nearclip = 0.0;
213         float farclip = 1.0;
214
215         /*      build the from and to point in normalized device coordinates 
216          *      Looks like normailized device coordinates are [-1,1] in x [-1,1] in y
217          *      [0,-1] in z 
218          *      
219          *      The actual z coordinates used don't have to be exact just infront and 
220          *      behind of the near and far clip planes.
221          */ 
222         MT_Vector4 frompoint = MT_Vector4( 
223                 (2 * (m_x-x_lb) / width) - 1.0,
224                 1.0 - (2 * (m_y - y_lb) / height),
225                 nearclip,
226                 1.0
227         );
228         MT_Vector4 topoint = MT_Vector4( 
229                 (2 * (m_x-x_lb) / width) - 1.0,
230                 1.0 - (2 * (m_y-y_lb) / height),
231                 farclip,
232                 1.0
233         );
234
235         /* camera to world  */
236         MT_Transform wcs_camcs_tranform = cam->GetWorldToCamera();
237         if (!cam->GetCameraData()->m_perspective)
238                 wcs_camcs_tranform.getOrigin()[2] *= 100.0;
239         MT_Transform cams_wcs_transform;
240         cams_wcs_transform.invert(wcs_camcs_tranform);
241         
242         MT_Matrix4x4 camcs_wcs_matrix = MT_Matrix4x4(cams_wcs_transform);
243
244         /* badly defined, the first time round.... I wonder why... I might
245          * want to guard against floating point errors here.*/
246         MT_Matrix4x4 clip_camcs_matrix = MT_Matrix4x4(cam->GetProjectionMatrix());
247         clip_camcs_matrix.invert();
248
249         /* shoot-points: clip to cam to wcs . win to clip was already done.*/
250         frompoint = clip_camcs_matrix * frompoint;
251         topoint   = clip_camcs_matrix * topoint;
252         frompoint = camcs_wcs_matrix * frompoint;
253         topoint   = camcs_wcs_matrix * topoint;
254         
255         /* from hom wcs to 3d wcs: */
256         MT_Point3 frompoint3 = MT_Point3(frompoint[0]/frompoint[3], 
257                                                                          frompoint[1]/frompoint[3], 
258                                                                          frompoint[2]/frompoint[3]); 
259         MT_Point3 topoint3 = MT_Point3(topoint[0]/topoint[3], 
260                                                                    topoint[1]/topoint[3], 
261                                                                    topoint[2]/topoint[3]); 
262         m_prevTargetPoint = topoint3;
263         m_prevSourcePoint = frompoint3;
264         
265         /* 2. Get the object from PhysicsEnvironment */
266         /* Shoot! Beware that the first argument here is an
267          * ignore-object. We don't ignore anything... */
268         
269         KX_IPhysicsController* physics_controller = cam->GetPhysicsController();
270         PHY_IPhysicsEnvironment* physics_environment = m_kxscene->GetPhysicsEnvironment();
271
272         bool result = false;
273
274         result = KX_RayCast::RayTest(physics_controller, physics_environment, frompoint3, topoint3, resultpoint, resultnormal, KX_RayCast::Callback<KX_MouseFocusSensor>(this));
275         
276         result = (m_hitObject!=0);
277
278         return result;
279
280 }
281
282 /* ------------------------------------------------------------------------- */
283 /* Python functions                                                          */
284 /* ------------------------------------------------------------------------- */
285
286 /* Integration hooks ------------------------------------------------------- */
287 PyTypeObject KX_MouseFocusSensor::Type = {
288         PyObject_HEAD_INIT(&PyType_Type)
289         0,
290         "KX_MouseFocusSensor",
291         sizeof(KX_MouseFocusSensor),
292         0,
293         PyDestructor,
294         0,
295         __getattr,
296         __setattr,
297         0, //&MyPyCompare,
298         __repr,
299         0, //&cvalue_as_number,
300         0,
301         0,
302         0,
303         0
304 };
305
306 PyParentObject KX_MouseFocusSensor::Parents[] = {
307         &KX_MouseFocusSensor::Type,
308         &SCA_MouseSensor::Type,
309         &SCA_ISensor::Type,
310         &SCA_ILogicBrick::Type,
311         &CValue::Type,
312         NULL
313 };
314
315 PyMethodDef KX_MouseFocusSensor::Methods[] = {
316         {"getRayTarget", (PyCFunction) KX_MouseFocusSensor::sPyGetRayTarget, 
317          METH_VARARGS, GetRayTarget_doc},
318         {"getRaySource", (PyCFunction) KX_MouseFocusSensor::sPyGetRaySource, 
319          METH_VARARGS, GetRaySource_doc},
320         {"getHitObject",(PyCFunction) KX_MouseFocusSensor::sPyGetHitObject,METH_VARARGS, GetHitObject_doc},
321         {"getHitPosition",(PyCFunction) KX_MouseFocusSensor::sPyGetHitPosition,METH_VARARGS, GetHitPosition_doc},
322         {"getHitNormal",(PyCFunction) KX_MouseFocusSensor::sPyGetHitNormal,METH_VARARGS, GetHitNormal_doc},
323         {"getRayDirection",(PyCFunction) KX_MouseFocusSensor::sPyGetRayDirection,METH_VARARGS, GetRayDirection_doc},
324
325
326         {NULL,NULL} //Sentinel
327 };
328
329 PyObject* KX_MouseFocusSensor::_getattr(const STR_String& attr) {
330         _getattr_up(SCA_MouseSensor);
331 }
332
333
334 char KX_MouseFocusSensor::GetHitObject_doc[] = 
335 "getHitObject()\n"
336 "\tReturns the name of the object that was hit by this ray.\n";
337 PyObject* KX_MouseFocusSensor::PyGetHitObject(PyObject* self, 
338                                                                                    PyObject* args, 
339                                                                                    PyObject* kwds)
340 {
341         if (m_hitObject)
342         {
343                 return m_hitObject->AddRef();
344         }
345         Py_Return;
346 }
347
348
349 char KX_MouseFocusSensor::GetHitPosition_doc[] = 
350 "getHitPosition()\n"
351 "\tReturns the position (in worldcoordinates) where the object was hit by this ray.\n";
352 PyObject* KX_MouseFocusSensor::PyGetHitPosition(PyObject* self, 
353                                PyObject* args, 
354                                PyObject* kwds)
355 {
356
357         MT_Point3 pos = m_hitPosition;
358
359         PyObject* resultlist = PyList_New(3);
360         int index;
361         for (index=0;index<3;index++)
362         {
363                 PyList_SetItem(resultlist,index,PyFloat_FromDouble(pos[index]));
364         }
365         return resultlist;
366
367 }
368
369 char KX_MouseFocusSensor::GetRayDirection_doc[] = 
370 "getRayDirection()\n"
371 "\tReturns the direction from the ray (in worldcoordinates) .\n";
372 PyObject* KX_MouseFocusSensor::PyGetRayDirection(PyObject* self, 
373                                PyObject* args, 
374                                PyObject* kwds)
375 {
376
377         MT_Vector3 dir = m_prevTargetPoint - m_prevSourcePoint;
378         dir.normalize();
379
380         PyObject* resultlist = PyList_New(3);
381         int index;
382         for (index=0;index<3;index++)
383         {
384                 PyList_SetItem(resultlist,index,PyFloat_FromDouble(dir[index]));
385         }
386         return resultlist;
387
388 }
389
390 char KX_MouseFocusSensor::GetHitNormal_doc[] = 
391 "getHitNormal()\n"
392 "\tReturns the normal (in worldcoordinates) of the object at the location where the object was hit by this ray.\n";
393 PyObject* KX_MouseFocusSensor::PyGetHitNormal(PyObject* self, 
394                                PyObject* args, 
395                                PyObject* kwds)
396 {
397         MT_Vector3 pos = m_hitNormal;
398
399         PyObject* resultlist = PyList_New(3);
400         int index;
401         for (index=0;index<3;index++)
402         {
403                 PyList_SetItem(resultlist,index,PyFloat_FromDouble(pos[index]));
404         }
405         return resultlist;
406
407 }
408
409
410 /*  getRayTarget                                                */
411 char KX_MouseFocusSensor::GetRayTarget_doc[] = 
412 "getRayTarget()\n"
413 "\tReturns the target of the ray that seeks the focus object,\n"
414 "\tin worldcoordinates.";
415 PyObject* KX_MouseFocusSensor::PyGetRayTarget(PyObject* self, 
416                                                                                           PyObject* args, 
417                                                                                           PyObject* kwds) {
418         PyObject *retVal = PyList_New(3);
419
420         PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_prevTargetPoint[0]));
421         PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_prevTargetPoint[1]));
422         PyList_SetItem(retVal, 2, PyFloat_FromDouble(m_prevTargetPoint[2]));
423         
424         return retVal;
425 }
426
427 /*  getRayTarget                                                */
428 char KX_MouseFocusSensor::GetRaySource_doc[] = 
429 "getRaySource()\n"
430 "\tReturns the source of the ray that seeks the focus object,\n"
431 "\tin worldcoordinates.";
432 PyObject* KX_MouseFocusSensor::PyGetRaySource(PyObject* self, 
433                                                                                           PyObject* args, 
434                                                                                           PyObject* kwds) {
435         PyObject *retVal = PyList_New(3);
436
437         PyList_SetItem(retVal, 0, PyFloat_FromDouble(m_prevSourcePoint[0]));
438         PyList_SetItem(retVal, 1, PyFloat_FromDouble(m_prevSourcePoint[1]));
439         PyList_SetItem(retVal, 2, PyFloat_FromDouble(m_prevSourcePoint[2]));
440         
441         return retVal;
442 }
443
444 /* eof */
445