BGE Python api
[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,
255         __repr,
256         0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
257         Methods
258 };
259
260 PyParentObject KX_TouchSensor::Parents[] = {
261         &KX_TouchSensor::Type,
262         &SCA_ISensor::Type,
263         &SCA_ILogicBrick::Type,
264         &CValue::Type,
265         NULL
266 };
267
268 PyMethodDef KX_TouchSensor::Methods[] = {
269         //Deprecated ----->
270         {"setProperty", 
271          (PyCFunction) KX_TouchSensor::sPySetProperty,      METH_O, (PY_METHODCHAR)SetProperty_doc},
272         {"getProperty", 
273          (PyCFunction) KX_TouchSensor::sPyGetProperty,      METH_NOARGS, (PY_METHODCHAR)GetProperty_doc},
274         {"getHitObject", 
275          (PyCFunction) KX_TouchSensor::sPyGetHitObject,     METH_NOARGS, (PY_METHODCHAR)GetHitObject_doc},
276         {"getHitObjectList", 
277          (PyCFunction) KX_TouchSensor::sPyGetHitObjectList, METH_NOARGS, (PY_METHODCHAR)GetHitObjectList_doc},
278          //<-----
279         {NULL,NULL} //Sentinel
280 };
281
282 PyAttributeDef KX_TouchSensor::Attributes[] = {
283         KX_PYATTRIBUTE_STRING_RW("property",0,100,false,KX_TouchSensor,m_touchedpropname),
284         KX_PYATTRIBUTE_BOOL_RW("useMaterial",KX_TouchSensor,m_bFindMaterial),
285         KX_PYATTRIBUTE_BOOL_RW("pulseCollisions",KX_TouchSensor,m_bTouchPulse),
286         KX_PYATTRIBUTE_DUMMY("objectHit"),
287         KX_PYATTRIBUTE_DUMMY("objectHitList"),
288         { NULL }        //Sentinel
289 };
290
291 PyObject* KX_TouchSensor::_getattr(const char *attr)
292 {       
293         if (!strcmp(attr, "objectHit")) {
294                 if (m_hitObject)        return m_hitObject->AddRef();
295                 else                            Py_RETURN_NONE;
296         }
297         if (!strcmp(attr, "objectHitList")) {
298                 return m_colliders->AddRef();
299         }
300
301         PyObject* object= _getattr_self(Attributes, this, attr);
302         if (object != NULL)
303                 return object;
304         _getattr_up(SCA_ISensor);
305 }
306
307 int KX_TouchSensor::_setattr(const char *attr, PyObject *value)
308 {
309         int ret = _setattr_self(Attributes, this, attr, value);
310         if (ret >= 0)
311                 return ret;
312         
313         return SCA_ISensor::_setattr(attr, value);
314 }
315
316 /* Python API */
317
318 /* 1. setProperty */
319 const char KX_TouchSensor::SetProperty_doc[] = 
320 "setProperty(name)\n"
321 "\t- name: string\n"
322 "\tSet the property or material to collide with. Use\n"
323 "\tsetTouchMaterial() to switch between properties and\n"
324 "\tmaterials.";
325 PyObject* KX_TouchSensor::PySetProperty(PyObject* self, PyObject* value)
326 {
327         ShowDeprecationWarning("setProperty()", "the propertyName property");
328         char *nameArg= PyString_AsString(value);
329         if (nameArg==NULL) {
330                 PyErr_SetString(PyExc_ValueError, "expected a ");
331                 return NULL;
332         }
333         
334         m_touchedpropname = nameArg;
335         Py_RETURN_NONE;
336 }
337 /* 2. getProperty */
338 const char KX_TouchSensor::GetProperty_doc[] = 
339 "getProperty(name)\n"
340 "\tReturns the property or material to collide with. Use\n"
341 "\tgetTouchMaterial() to find out whether this sensor\n"
342 "\tlooks for properties or materials.";
343 PyObject*  KX_TouchSensor::PyGetProperty(PyObject* self) {
344         return PyString_FromString(m_touchedpropname);
345 }
346
347 const char KX_TouchSensor::GetHitObject_doc[] = 
348 "getHitObject()\n"
349 ;
350 PyObject* KX_TouchSensor::PyGetHitObject(PyObject* self)
351 {
352         ShowDeprecationWarning("getHitObject()", "the objectHit property");
353         /* to do: do Py_IncRef if the object is already known in Python */
354         /* otherwise, this leaks memory */
355         if (m_hitObject)
356         {
357                 return m_hitObject->AddRef();
358         }
359         Py_RETURN_NONE;
360 }
361
362 const char KX_TouchSensor::GetHitObjectList_doc[] = 
363 "getHitObjectList()\n"
364 "\tReturn a list of the objects this object collided with,\n"
365 "\tbut only those matching the property/material condition.\n";
366 PyObject* KX_TouchSensor::PyGetHitObjectList(PyObject* self)
367 {
368         ShowDeprecationWarning("getHitObjectList()", "the objectHitList property");
369         /* to do: do Py_IncRef if the object is already known in Python */
370         /* otherwise, this leaks memory */ /* Edit, this seems ok and not to leak memory - Campbell */
371         return m_colliders->AddRef();
372 }
373
374 /*getTouchMaterial and setTouchMaterial were never added to the api,
375 they can probably be removed with out anyone noticing*/
376
377 /* 5. getTouchMaterial */
378 const char KX_TouchSensor::GetTouchMaterial_doc[] = 
379 "getTouchMaterial()\n"
380 "\tReturns KX_TRUE if this sensor looks for a specific material,\n"
381 "\tKX_FALSE if it looks for a specific property.\n" ;
382 PyObject* KX_TouchSensor::PyGetTouchMaterial(PyObject* self)
383 {
384         ShowDeprecationWarning("getTouchMaterial()", "the materialCheck property");
385         return PyInt_FromLong(m_bFindMaterial);
386 }
387
388 /* 6. setTouchMaterial */
389 #if 0
390 const char KX_TouchSensor::SetTouchMaterial_doc[] = 
391 "setTouchMaterial(flag)\n"
392 "\t- flag: KX_TRUE or KX_FALSE.\n"
393 "\tSet flag to KX_TRUE to switch on positive pulse mode,\n"
394 "\tKX_FALSE to switch off positive pulse mode.\n" ;
395 PyObject* KX_TouchSensor::PySetTouchMaterial(PyObject* self, PyObject *value)
396 {
397         int pulseArg = PyInt_AsLong(value);
398
399         if(pulseArg ==-1 && PyErr_Occurred()) {
400                 PyErr_SetString(PyExc_ValueError, "expected a bool");
401                 return NULL;
402         }
403         
404         m_bFindMaterial = pulseArg != 0;
405
406         Py_RETURN_NONE;
407 }
408 #endif
409
410 /* eof */