BGE Python API
[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                                                                                  RAS_ICanvas* canvas,
65                                                                                  KX_Scene* kxscene,
66                                                                                  KX_KetsjiEngine *kxengine,
67                                                                                  SCA_IObject* gameobj, 
68                                                                                  PyTypeObject* T)
69     : SCA_MouseSensor(eventmgr, startx, starty, mousemode, gameobj, T),
70           m_focusmode(focusmode),
71           m_gp_canvas(canvas),
72           m_kxscene(kxscene),
73           m_kxengine(kxengine)
74 {
75         Init();
76 }
77
78 void KX_MouseFocusSensor::Init()
79 {
80         m_mouse_over_in_previous_frame = (m_invert)?true:false;
81         m_positive_event = false;
82         m_hitObject = 0;
83         m_reset = true;
84 }
85
86 bool KX_MouseFocusSensor::Evaluate(CValue* event)
87 {
88         bool result = false;
89         bool obHasFocus = false;
90         bool reset = m_reset && m_level;
91
92 //      cout << "evaluate focus mouse sensor "<<endl;
93         m_reset = false;
94         if (m_focusmode) {
95                 /* Focus behaviour required. Test mouse-on. The rest is
96                  * equivalent to handling a key. */
97                 obHasFocus = ParentObjectHasFocus();
98                 
99                 if (!obHasFocus) {
100                         m_positive_event = false;
101                         if (m_mouse_over_in_previous_frame) {
102                                 result = true;
103                         } 
104                 } else {
105                         m_positive_event = true;
106                         if (!m_mouse_over_in_previous_frame) {
107                                 result = true;
108                         } 
109                 } 
110                 if (reset) {
111                         // force an event 
112                         result = true;
113                 }
114         } else {
115                 /* No focus behaviour required: revert to the basic mode. This
116          * mode is never used, because the converter never makes this
117          * sensor for a mouse-key event. It is here for
118          * completeness. */
119                 result = SCA_MouseSensor::Evaluate(event);
120                 m_positive_event = (m_val!=0);
121         }
122
123         m_mouse_over_in_previous_frame = obHasFocus;
124
125         return result;
126 }
127
128 bool KX_MouseFocusSensor::RayHit(KX_ClientObjectInfo* client_info, KX_RayCast* result, void * const data)
129 {
130         KX_GameObject* hitKXObj = client_info->m_gameobject;
131         
132         /* Is this me? In the ray test, there are a lot of extra checks
133         * for aliasing artefacts from self-hits. That doesn't happen
134         * here, so a simple test suffices. Or does the camera also get
135         * self-hits? (No, and the raysensor shouldn't do it either, since
136         * self-hits are excluded by setting the correct ignore-object.)
137         * Hitspots now become valid. */
138         KX_GameObject* thisObj = (KX_GameObject*) GetParent();
139         if ((m_focusmode == 2) || hitKXObj == thisObj)
140         {
141                 m_hitObject = hitKXObj;
142                 m_hitPosition = result->m_hitPoint;
143                 m_hitNormal = result->m_hitNormal;
144                 return true;
145         }
146         
147         return true;     // object must be visible to trigger
148         //return false;  // occluded objects can trigger
149 }
150
151
152
153 bool KX_MouseFocusSensor::ParentObjectHasFocus(void)
154 {
155         m_hitObject = 0;
156         m_hitPosition = MT_Vector3(0,0,0);
157         m_hitNormal =   MT_Vector3(1,0,0);
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 - normalized 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 normalized 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         KX_Camera* cam = m_kxscene->GetActiveCamera();
200
201         /* get the scenes current viewport. we recompute it because there
202          * may be multiple cameras and m_kxscene->GetSceneViewport() only
203          * has the one that was last drawn */
204
205         RAS_Rect area, viewport;
206         m_kxengine->GetSceneViewport(m_kxscene, cam, area, viewport);
207
208         float height = float(viewport.m_y2 - viewport.m_y1 + 1);
209         float width  = float(viewport.m_x2 - viewport.m_x1 + 1);
210         
211         float x_lb = float(viewport.m_x1);
212         float y_lb = float(viewport.m_y1);
213
214         /* There's some strangeness I don't fully get here... These values
215          * _should_ be wrong! */
216         
217
218         /* old: */
219         float nearclip = 0.0;
220         float farclip = 1.0;
221
222         /*      build the from and to point in normalized device coordinates 
223          *      Looks like normailized device coordinates are [-1,1] in x [-1,1] in y
224          *      [0,-1] in z 
225          *      
226          *      The actual z coordinates used don't have to be exact just infront and 
227          *      behind of the near and far clip planes.
228          */ 
229         MT_Vector4 frompoint = MT_Vector4( 
230                 (2 * (m_x-x_lb) / width) - 1.0,
231                 1.0 - (2 * (m_y - y_lb) / height),
232                 nearclip,
233                 1.0
234         );
235         MT_Vector4 topoint = MT_Vector4( 
236                 (2 * (m_x-x_lb) / width) - 1.0,
237                 1.0 - (2 * (m_y-y_lb) / height),
238                 farclip,
239                 1.0
240         );
241
242         /* camera to world  */
243         MT_Transform wcs_camcs_tranform = cam->GetWorldToCamera();
244         if (!cam->GetCameraData()->m_perspective)
245                 wcs_camcs_tranform.getOrigin()[2] *= 100.0;
246         MT_Transform cams_wcs_transform;
247         cams_wcs_transform.invert(wcs_camcs_tranform);
248         
249         MT_Matrix4x4 camcs_wcs_matrix = MT_Matrix4x4(cams_wcs_transform);
250
251         /* badly defined, the first time round.... I wonder why... I might
252          * want to guard against floating point errors here.*/
253         MT_Matrix4x4 clip_camcs_matrix = MT_Matrix4x4(cam->GetProjectionMatrix());
254         clip_camcs_matrix.invert();
255
256         /* shoot-points: clip to cam to wcs . win to clip was already done.*/
257         frompoint = clip_camcs_matrix * frompoint;
258         topoint   = clip_camcs_matrix * topoint;
259         frompoint = camcs_wcs_matrix * frompoint;
260         topoint   = camcs_wcs_matrix * topoint;
261         
262         /* from hom wcs to 3d wcs: */
263         MT_Point3 frompoint3 = MT_Point3(frompoint[0]/frompoint[3], 
264                                                                          frompoint[1]/frompoint[3], 
265                                                                          frompoint[2]/frompoint[3]); 
266         MT_Point3 topoint3 = MT_Point3(topoint[0]/topoint[3], 
267                                                                    topoint[1]/topoint[3], 
268                                                                    topoint[2]/topoint[3]); 
269         m_prevTargetPoint = topoint3;
270         m_prevSourcePoint = frompoint3;
271         
272         /* 2. Get the object from PhysicsEnvironment */
273         /* Shoot! Beware that the first argument here is an
274          * ignore-object. We don't ignore anything... */
275         
276         KX_IPhysicsController* physics_controller = cam->GetPhysicsController();
277         PHY_IPhysicsEnvironment* physics_environment = m_kxscene->GetPhysicsEnvironment();
278
279         bool result = false;
280
281         KX_RayCast::Callback<KX_MouseFocusSensor> callback(this,physics_controller);
282         KX_RayCast::RayTest(physics_environment, frompoint3, topoint3, callback);
283         
284         result = (m_hitObject!=0);
285
286         return result;
287
288 }
289
290 /* ------------------------------------------------------------------------- */
291 /* Python functions                                                          */
292 /* ------------------------------------------------------------------------- */
293
294 /* Integration hooks ------------------------------------------------------- */
295 PyTypeObject KX_MouseFocusSensor::Type = {
296         PyObject_HEAD_INIT(NULL)
297         0,
298         "KX_MouseFocusSensor",
299         sizeof(KX_MouseFocusSensor),
300         0,
301         PyDestructor,
302         0,
303         0,
304         0,
305         0,
306         py_base_repr,
307         0,0,0,0,0,0,
308         py_base_getattro,
309         py_base_setattro,
310         0,0,0,0,0,0,0,0,0,
311         Methods
312 };
313
314 PyParentObject KX_MouseFocusSensor::Parents[] = {
315         &KX_MouseFocusSensor::Type,
316         &SCA_MouseSensor::Type,
317         &SCA_ISensor::Type,
318         &SCA_ILogicBrick::Type,
319         &CValue::Type,
320         NULL
321 };
322
323 PyMethodDef KX_MouseFocusSensor::Methods[] = {
324         {"getRayTarget", (PyCFunction) KX_MouseFocusSensor::sPyGetRayTarget, METH_NOARGS, (PY_METHODCHAR)GetRayTarget_doc},
325         {"getRaySource", (PyCFunction) KX_MouseFocusSensor::sPyGetRaySource, METH_NOARGS, (PY_METHODCHAR)GetRaySource_doc},
326         {"getHitObject",(PyCFunction) KX_MouseFocusSensor::sPyGetHitObject,METH_NOARGS, (PY_METHODCHAR)GetHitObject_doc},
327         {"getHitPosition",(PyCFunction) KX_MouseFocusSensor::sPyGetHitPosition,METH_NOARGS, (PY_METHODCHAR)GetHitPosition_doc},
328         {"getHitNormal",(PyCFunction) KX_MouseFocusSensor::sPyGetHitNormal,METH_NOARGS, (PY_METHODCHAR)GetHitNormal_doc},
329         {"getRayDirection",(PyCFunction) KX_MouseFocusSensor::sPyGetRayDirection,METH_NOARGS, (PY_METHODCHAR)GetRayDirection_doc},
330
331
332         {NULL,NULL} //Sentinel
333 };
334
335 PyAttributeDef KX_MouseFocusSensor::Attributes[] = {
336         { NULL }        //Sentinel
337 };
338
339 PyObject* KX_MouseFocusSensor::py_getattro(PyObject *attr) {
340         py_getattro_up(SCA_MouseSensor);
341 }
342
343
344 const char KX_MouseFocusSensor::GetHitObject_doc[] = 
345 "getHitObject()\n"
346 "\tReturns the object that was hit by this ray.\n";
347 PyObject* KX_MouseFocusSensor::PyGetHitObject(PyObject* self)
348 {
349         if (m_hitObject)
350                 return m_hitObject->AddRef();
351         
352         Py_RETURN_NONE;
353 }
354
355
356 const char KX_MouseFocusSensor::GetHitPosition_doc[] = 
357 "getHitPosition()\n"
358 "\tReturns the position (in worldcoordinates) where the object was hit by this ray.\n";
359 PyObject* KX_MouseFocusSensor::PyGetHitPosition(PyObject* self)
360 {
361         return PyObjectFrom(m_hitPosition);
362 }
363
364 const char KX_MouseFocusSensor::GetRayDirection_doc[] = 
365 "getRayDirection()\n"
366 "\tReturns the direction from the ray (in worldcoordinates) .\n";
367 PyObject* KX_MouseFocusSensor::PyGetRayDirection(PyObject* self)
368 {
369
370         MT_Vector3 dir = m_prevTargetPoint - m_prevSourcePoint;
371         dir.normalize();
372         return PyObjectFrom(dir);
373 }
374
375 const char KX_MouseFocusSensor::GetHitNormal_doc[] = 
376 "getHitNormal()\n"
377 "\tReturns the normal (in worldcoordinates) at the point of collision where the object was hit by this ray.\n";
378 PyObject* KX_MouseFocusSensor::PyGetHitNormal(PyObject* self)
379 {
380         return PyObjectFrom(m_hitNormal);
381 }
382
383
384 /*  getRayTarget                                                */
385 const char KX_MouseFocusSensor::GetRayTarget_doc[] = 
386 "getRayTarget()\n"
387 "\tReturns the target of the ray that seeks the focus object,\n"
388 "\tin worldcoordinates.";
389 PyObject* KX_MouseFocusSensor::PyGetRayTarget(PyObject* self) {
390         return PyObjectFrom(m_prevTargetPoint);
391 }
392
393 /*  getRayTarget                                                */
394 const char KX_MouseFocusSensor::GetRaySource_doc[] = 
395 "getRaySource()\n"
396 "\tReturns the source of the ray that seeks the focus object,\n"
397 "\tin worldcoordinates.";
398 PyObject* KX_MouseFocusSensor::PyGetRaySource(PyObject* self) {
399         return PyObjectFrom(m_prevSourcePoint);
400 }
401
402 /* eof */
403