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