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