BGE API cleanup: apply patch from Moguri: Near, Radar, Touch sensor updated.
[blender.git] / source / gameengine / Ketsji / KX_TouchSensor.cpp
1 /**
2  * Senses touch and collision events
3  *
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include "KX_TouchSensor.h"
33 #include "SCA_EventManager.h"
34 #include "SCA_LogicManager.h"
35 #include "KX_GameObject.h"
36 #include "KX_TouchEventManager.h"
37
38 #include "PHY_IPhysicsController.h"
39
40 #include <iostream>
41 #include "PHY_IPhysicsEnvironment.h"
42
43 #ifdef HAVE_CONFIG_H
44 #include <config.h>
45 #endif
46
47 /* ------------------------------------------------------------------------- */
48 /* Native functions                                                          */
49 /* ------------------------------------------------------------------------- */
50
51 void KX_TouchSensor::SynchronizeTransform()
52 {
53         // the touch sensor does not require any synchronization: it uses
54         // the same physical object which is already synchronized by Blender
55 }
56
57
58 void KX_TouchSensor::EndFrame() {
59         m_colliders->ReleaseAndRemoveAll();
60         m_hitObject = NULL;
61         m_bTriggered = false;
62         m_bColliderHash = 0;
63 }
64
65 void KX_TouchSensor::UnregisterToManager()
66 {
67         // before unregistering the sensor, make sure we release all references
68         EndFrame();
69         m_eventmgr->RemoveSensor(this);
70 }
71
72 bool KX_TouchSensor::Evaluate(CValue* event)
73 {
74         bool result = false;
75         bool reset = m_reset && m_level;
76         m_reset = false;
77         if (m_bTriggered != m_bLastTriggered)
78         {
79                 m_bLastTriggered = m_bTriggered;
80                 if (!m_bTriggered)
81                         m_hitObject = NULL;
82                 result = true;
83         }
84         if (reset)
85                 // force an event
86                 result = true;
87         
88         if (m_bTouchPulse) { /* pulse on changes to the colliders */
89                 int count = m_colliders->GetCount();
90                 
91                 if (m_bLastCount!=count || m_bColliderHash!=m_bLastColliderHash) {
92                         m_bLastCount = count;
93                         m_bLastColliderHash= m_bColliderHash;
94                         result = true;
95                 }
96         }
97         return result;
98 }
99
100 KX_TouchSensor::KX_TouchSensor(SCA_EventManager* eventmgr,KX_GameObject* gameobj,bool bFindMaterial,bool bTouchPulse,const STR_String& touchedpropname,PyTypeObject* T)
101 :SCA_ISensor(gameobj,eventmgr,T),
102 m_touchedpropname(touchedpropname),
103 m_bFindMaterial(bFindMaterial),
104 m_bTouchPulse(bTouchPulse),
105 m_eventmgr(eventmgr)
106 /*m_sumoObj(sumoObj),*/
107 {
108 //      KX_TouchEventManager* touchmgr = (KX_TouchEventManager*) eventmgr;
109 //      m_resptable = touchmgr->GetResponseTable();
110         
111 //      m_solidHandle = m_sumoObj->getObjectHandle();
112
113         m_colliders = new CListValue();
114         
115         KX_ClientObjectInfo *client_info = gameobj->getClientInfo();
116         //client_info->m_gameobject = gameobj;
117         //client_info->m_auxilary_info = NULL;
118         client_info->m_sensors.push_back(this);
119         
120         m_physCtrl = dynamic_cast<PHY_IPhysicsController*>(gameobj->GetPhysicsController());
121         MT_assert( !gameobj->GetPhysicsController() || m_physCtrl );
122         Init();
123 }
124
125 void KX_TouchSensor::Init()
126 {
127         m_bCollision = false;
128         m_bTriggered = false;
129         m_bLastTriggered = (m_invert)?true:false;
130         m_bLastCount = 0;
131         m_bColliderHash = m_bLastColliderHash = 0;
132         m_hitObject =  NULL;
133         m_reset = true;
134 }
135
136 KX_TouchSensor::~KX_TouchSensor()
137 {
138         //DT_ClearObjectResponse(m_resptable,m_solidHandle);
139         m_colliders->Release();
140 }
141
142 CValue* KX_TouchSensor::GetReplica() 
143 {
144         KX_TouchSensor* replica = new KX_TouchSensor(*this);
145         replica->m_colliders = new CListValue();
146         replica->Init();
147         // this will copy properties and so on...
148         CValue::AddDataToReplica(replica);
149         return replica;
150 }
151
152 void    KX_TouchSensor::ReParent(SCA_IObject* parent)
153 {
154         KX_GameObject *gameobj = static_cast<KX_GameObject *>(parent);
155         PHY_IPhysicsController *sphy = dynamic_cast<PHY_IPhysicsController*>(((KX_GameObject*)parent)->GetPhysicsController());
156         if (sphy)
157                 m_physCtrl = sphy;
158         
159 //      m_solidHandle = m_sumoObj->getObjectHandle();
160         KX_ClientObjectInfo *client_info = gameobj->getClientInfo();
161         //client_info->m_gameobject = gameobj;
162         //client_info->m_auxilary_info = NULL;
163         
164         client_info->m_sensors.push_back(this);
165         SCA_ISensor::ReParent(parent);
166 }
167
168 void KX_TouchSensor::RegisterSumo(KX_TouchEventManager *touchman)
169 {
170         if (m_physCtrl)
171         {
172                 touchman->GetPhysicsEnvironment()->requestCollisionCallback(m_physCtrl);
173                 // collision
174                 // Deprecated   
175
176         }
177 }
178
179 void KX_TouchSensor::UnregisterSumo(KX_TouchEventManager* touchman)
180 {
181         if (m_physCtrl)
182         {
183                 touchman->GetPhysicsEnvironment()->removeCollisionCallback(m_physCtrl);
184         }
185 }
186
187 bool    KX_TouchSensor::NewHandleCollision(void*object1,void*object2,const PHY_CollData* colldata)
188 {
189 //      KX_TouchEventManager* toucheventmgr = (KX_TouchEventManager*)m_eventmgr;
190         KX_GameObject* parent = (KX_GameObject*)GetParent();
191
192         // need the mapping from PHY_IPhysicsController to gameobjects now
193         
194         KX_ClientObjectInfo* client_info = static_cast<KX_ClientObjectInfo*> (object1 == m_physCtrl? 
195                                         ((PHY_IPhysicsController*)object2)->getNewClientInfo(): 
196                                         ((PHY_IPhysicsController*)object1)->getNewClientInfo());
197
198         KX_GameObject* gameobj = ( client_info ? 
199                         client_info->m_gameobject : 
200                         NULL);
201         
202         // add the same check as in SCA_ISensor::Activate(), 
203         // we don't want to record collision when the sensor is not active.
204         if (m_links && !m_suspended &&
205                 gameobj && (gameobj != parent) && client_info->isActor())
206         {
207                 
208                 bool found = m_touchedpropname.IsEmpty();
209                 if (!found)
210                 {
211                         if (m_bFindMaterial)
212                         {
213                                 if (client_info->m_auxilary_info)
214                                 {
215                                         found = (!strcmp(m_touchedpropname.Ptr(), (char*)client_info->m_auxilary_info));
216                                 }
217                         } else
218                         {
219                                 found = (gameobj->GetProperty(m_touchedpropname) != NULL);
220                         }
221                 }
222                 if (found)
223                 {
224                         if (!m_colliders->SearchValue(gameobj)) {
225                                 m_colliders->Add(gameobj->AddRef());
226                                 
227                                 if (m_bTouchPulse)
228                                         m_bColliderHash += (uint_ptr)(static_cast<void *>(&gameobj));
229                         }
230                         m_bTriggered = true;
231                         m_hitObject = gameobj;
232                         //printf("KX_TouchSensor::HandleCollision\n");
233                 }
234                 
235         } 
236         return false; // was DT_CONTINUE but this was defined in sumo as false.
237 }
238
239
240 /* ------------------------------------------------------------------------- */
241 /* Python functions                                                          */
242 /* ------------------------------------------------------------------------- */
243 /* Integration hooks ------------------------------------------------------- */
244 PyTypeObject KX_TouchSensor::Type = {
245         PyObject_HEAD_INIT(&PyType_Type)
246         0,
247         "KX_TouchSensor",
248         sizeof(KX_TouchSensor),
249         0,
250         PyDestructor,
251         0,
252         __getattr,
253         __setattr,
254         0, //&MyPyCompare,
255         __repr,
256         0, //&cvalue_as_number,
257         0,
258         0,
259         0,
260         0
261 };
262
263 PyParentObject KX_TouchSensor::Parents[] = {
264         &KX_TouchSensor::Type,
265         &SCA_ISensor::Type,
266         &SCA_ILogicBrick::Type,
267         &CValue::Type,
268         NULL
269 };
270
271 PyMethodDef KX_TouchSensor::Methods[] = {
272         //Deprecated ----->
273         {"setProperty", 
274          (PyCFunction) KX_TouchSensor::sPySetProperty,      METH_O, (PY_METHODCHAR)SetProperty_doc},
275         {"getProperty", 
276          (PyCFunction) KX_TouchSensor::sPyGetProperty,      METH_NOARGS, (PY_METHODCHAR)GetProperty_doc},
277         {"getHitObject", 
278          (PyCFunction) KX_TouchSensor::sPyGetHitObject,     METH_NOARGS, (PY_METHODCHAR)GetHitObject_doc},
279         {"getHitObjectList", 
280          (PyCFunction) KX_TouchSensor::sPyGetHitObjectList, METH_NOARGS, (PY_METHODCHAR)GetHitObjectList_doc},
281          //<-----
282         {NULL,NULL} //Sentinel
283 };
284
285 PyAttributeDef KX_TouchSensor::Attributes[] = {
286         KX_PYATTRIBUTE_STRING_RW("property",0,100,false,KX_TouchSensor,m_touchedpropname),
287         KX_PYATTRIBUTE_BOOL_RW("useMaterial",KX_TouchSensor,m_bFindMaterial),
288         KX_PYATTRIBUTE_BOOL_RW("pulseCollisions",KX_TouchSensor,m_bTouchPulse),
289         KX_PYATTRIBUTE_DUMMY("objectHit"),
290         KX_PYATTRIBUTE_DUMMY("objectHitList"),
291         { NULL }        //Sentinel
292 };
293
294 PyObject* KX_TouchSensor::_getattr(const char *attr)
295 {       
296         if (!strcmp(attr, "objectHit")) {
297                 if (m_hitObject)        return m_hitObject->AddRef();
298                 else                            Py_RETURN_NONE;
299         }
300         if (!strcmp(attr, "objectHitList")) {
301                 return m_colliders->AddRef();
302         }
303
304         PyObject* object= _getattr_self(Attributes, this, attr);
305         if (object != NULL)
306                 return object;
307         _getattr_up(SCA_ISensor);
308 }
309
310 int KX_TouchSensor::_setattr(const char *attr, PyObject *value)
311 {
312         int ret = _setattr_self(Attributes, this, attr, value);
313         if (ret >= 0)
314                 return ret;
315         
316         return SCA_ISensor::_setattr(attr, value);
317 }
318
319 /* Python API */
320
321 /* 1. setProperty */
322 const char KX_TouchSensor::SetProperty_doc[] = 
323 "setProperty(name)\n"
324 "\t- name: string\n"
325 "\tSet the property or material to collide with. Use\n"
326 "\tsetTouchMaterial() to switch between properties and\n"
327 "\tmaterials.";
328 PyObject* KX_TouchSensor::PySetProperty(PyObject* self, PyObject* value)
329 {
330         ShowDeprecationWarning("setProperty()", "the propertyName property");
331         char *nameArg= PyString_AsString(value);
332         if (nameArg==NULL) {
333                 PyErr_SetString(PyExc_ValueError, "expected a ");
334                 return NULL;
335         }
336         
337         m_touchedpropname = nameArg;
338         Py_RETURN_NONE;
339 }
340 /* 2. getProperty */
341 const char KX_TouchSensor::GetProperty_doc[] = 
342 "getProperty(name)\n"
343 "\tReturns the property or material to collide with. Use\n"
344 "\tgetTouchMaterial() to find out whether this sensor\n"
345 "\tlooks for properties or materials.";
346 PyObject*  KX_TouchSensor::PyGetProperty(PyObject* self) {
347         return PyString_FromString(m_touchedpropname);
348 }
349
350 const char KX_TouchSensor::GetHitObject_doc[] = 
351 "getHitObject()\n"
352 ;
353 PyObject* KX_TouchSensor::PyGetHitObject(PyObject* self)
354 {
355         ShowDeprecationWarning("getHitObject()", "the objectHit property");
356         /* to do: do Py_IncRef if the object is already known in Python */
357         /* otherwise, this leaks memory */
358         if (m_hitObject)
359         {
360                 return m_hitObject->AddRef();
361         }
362         Py_RETURN_NONE;
363 }
364
365 const char KX_TouchSensor::GetHitObjectList_doc[] = 
366 "getHitObjectList()\n"
367 "\tReturn a list of the objects this object collided with,\n"
368 "\tbut only those matching the property/material condition.\n";
369 PyObject* KX_TouchSensor::PyGetHitObjectList(PyObject* self)
370 {
371         ShowDeprecationWarning("getHitObjectList()", "the objectHitList property");
372         /* to do: do Py_IncRef if the object is already known in Python */
373         /* otherwise, this leaks memory */ /* Edit, this seems ok and not to leak memory - Campbell */
374         return m_colliders->AddRef();
375 }
376
377 /*getTouchMaterial and setTouchMaterial were never added to the api,
378 they can probably be removed with out anyone noticing*/
379
380 /* 5. getTouchMaterial */
381 const char KX_TouchSensor::GetTouchMaterial_doc[] = 
382 "getTouchMaterial()\n"
383 "\tReturns KX_TRUE if this sensor looks for a specific material,\n"
384 "\tKX_FALSE if it looks for a specific property.\n" ;
385 PyObject* KX_TouchSensor::PyGetTouchMaterial(PyObject* self)
386 {
387         ShowDeprecationWarning("getTouchMaterial()", "the materialCheck property");
388         return PyInt_FromLong(m_bFindMaterial);
389 }
390
391 /* 6. setTouchMaterial */
392 #if 0
393 const char KX_TouchSensor::SetTouchMaterial_doc[] = 
394 "setTouchMaterial(flag)\n"
395 "\t- flag: KX_TRUE or KX_FALSE.\n"
396 "\tSet flag to KX_TRUE to switch on positive pulse mode,\n"
397 "\tKX_FALSE to switch off positive pulse mode.\n" ;
398 PyObject* KX_TouchSensor::PySetTouchMaterial(PyObject* self, PyObject *value)
399 {
400         int pulseArg = PyInt_AsLong(value);
401
402         if(pulseArg ==-1 && PyErr_Occurred()) {
403                 PyErr_SetString(PyExc_ValueError, "expected a bool");
404                 return NULL;
405         }
406         
407         m_bFindMaterial = pulseArg != 0;
408
409         Py_RETURN_NONE;
410 }
411 #endif
412
413 /* eof */