BGE logic update: new servo control motion actuator, new distance constraint actuator...
[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 #include "KX_SumoPhysicsController.h"
38 #include <iostream>
39 #include "PHY_IPhysicsEnvironment.h"
40
41 #ifdef HAVE_CONFIG_H
42 #include <config.h>
43 #endif
44
45 /* ------------------------------------------------------------------------- */
46 /* Native functions                                                          */
47 /* ------------------------------------------------------------------------- */
48
49 void KX_TouchSensor::SynchronizeTransform()
50 {
51         // the touch sensor does not require any synchronization: it uses
52         // the same physical object which is already synchronized by Blender
53 }
54
55
56 void KX_TouchSensor::EndFrame() {
57         m_colliders->ReleaseAndRemoveAll();
58         m_bTriggered = false;
59 }
60
61 bool KX_TouchSensor::Evaluate(CValue* event)
62 {
63         bool result = false;
64         bool reset = m_reset && m_level;
65
66         m_reset = false;
67         if (m_bTriggered != m_bLastTriggered)
68         {
69                 m_bLastTriggered = m_bTriggered;
70                 if (!m_bTriggered)
71                         m_hitObject = NULL;
72                 result = true;
73         }
74         if (reset)
75                 // force an event
76                 result = true;
77         return result;
78 }
79
80 KX_TouchSensor::KX_TouchSensor(SCA_EventManager* eventmgr,KX_GameObject* gameobj,bool bFindMaterial,const STR_String& touchedpropname,PyTypeObject* T)
81 :SCA_ISensor(gameobj,eventmgr,T),
82 m_touchedpropname(touchedpropname),
83 m_bFindMaterial(bFindMaterial),
84 m_eventmgr(eventmgr)
85 /*m_sumoObj(sumoObj),*/
86 {
87 //      KX_TouchEventManager* touchmgr = (KX_TouchEventManager*) eventmgr;
88 //      m_resptable = touchmgr->GetResponseTable();
89         
90 //      m_solidHandle = m_sumoObj->getObjectHandle();
91
92         m_colliders = new CListValue();
93         
94         KX_ClientObjectInfo *client_info = gameobj->getClientInfo();
95         client_info->m_gameobject = gameobj;
96         client_info->m_auxilary_info = NULL;
97         client_info->m_sensors.push_back(this);
98         
99         m_physCtrl = dynamic_cast<PHY_IPhysicsController*>(gameobj->GetPhysicsController());
100         MT_assert( !gameobj->GetPhysicsController() || m_physCtrl );
101         Init();
102 }
103
104 void KX_TouchSensor::Init()
105 {
106         m_bCollision = false;
107         m_bTriggered = false;
108         m_bLastTriggered = (m_invert)?true:false;
109         m_hitObject =  NULL;
110         m_reset = true;
111 }
112
113 KX_TouchSensor::~KX_TouchSensor()
114 {
115         //DT_ClearObjectResponse(m_resptable,m_solidHandle);
116         m_colliders->Release();
117 }
118
119 CValue* KX_TouchSensor::GetReplica() 
120 {
121         KX_TouchSensor* replica = new KX_TouchSensor(*this);
122         replica->m_colliders = new CListValue();
123         replica->Init();
124         // this will copy properties and so on...
125         CValue::AddDataToReplica(replica);
126         return replica;
127 }
128
129 void    KX_TouchSensor::ReParent(SCA_IObject* parent)
130 {
131         KX_GameObject *gameobj = static_cast<KX_GameObject *>(parent);
132         PHY_IPhysicsController *sphy = dynamic_cast<PHY_IPhysicsController*>(((KX_GameObject*)parent)->GetPhysicsController());
133         if (sphy)
134                 m_physCtrl = sphy;
135         
136 //      m_solidHandle = m_sumoObj->getObjectHandle();
137         KX_ClientObjectInfo *client_info = gameobj->getClientInfo();
138         client_info->m_gameobject = gameobj;
139         client_info->m_auxilary_info = NULL;
140         
141         client_info->m_sensors.push_back(this);
142         SCA_ISensor::ReParent(parent);
143 }
144
145 void KX_TouchSensor::RegisterSumo(KX_TouchEventManager *touchman)
146 {
147         if (m_physCtrl)
148         {
149                 touchman->GetPhysicsEnvironment()->requestCollisionCallback(m_physCtrl);
150                 // collision
151                 // Deprecated   
152
153         }
154 }
155
156 bool    KX_TouchSensor::NewHandleCollision(void*object1,void*object2,const PHY_CollData* colldata)
157 {
158 //      KX_TouchEventManager* toucheventmgr = (KX_TouchEventManager*)m_eventmgr;
159         KX_GameObject* parent = (KX_GameObject*)GetParent();
160
161         // need the mapping from PHY_IPhysicsController to gameobjects now
162         
163         KX_ClientObjectInfo* client_info = static_cast<KX_ClientObjectInfo*> (object1 == m_physCtrl? 
164                                         ((PHY_IPhysicsController*)object2)->getNewClientInfo(): 
165                                         ((PHY_IPhysicsController*)object1)->getNewClientInfo());
166
167         KX_GameObject* gameobj = ( client_info ? 
168                         client_info->m_gameobject : 
169                         NULL);
170         
171         if (gameobj && (gameobj != parent) && client_info->isActor())
172         {
173                 if (!m_colliders->SearchValue(gameobj))
174                         m_colliders->Add(gameobj->AddRef());
175                 
176                 bool found = m_touchedpropname.IsEmpty();
177                 if (!found)
178                 {
179                         if (m_bFindMaterial)
180                         {
181                                 if (client_info->m_auxilary_info)
182                                 {
183                                         found = (m_touchedpropname == STR_String((char*)client_info->m_auxilary_info));
184                                 }
185                         } else
186                         {
187                                 found = (gameobj->GetProperty(m_touchedpropname) != NULL);
188                         }
189                 }
190                 if (found)
191                 {
192                         m_bTriggered = true;
193                         m_hitObject = gameobj;
194                         //printf("KX_TouchSensor::HandleCollision\n");
195                 }
196                 
197         } 
198         return DT_CONTINUE;
199 }
200
201
202 /* ------------------------------------------------------------------------- */
203 /* Python functions                                                          */
204 /* ------------------------------------------------------------------------- */
205 /* Integration hooks ------------------------------------------------------- */
206 PyTypeObject KX_TouchSensor::Type = {
207         PyObject_HEAD_INIT(&PyType_Type)
208         0,
209         "KX_TouchSensor",
210         sizeof(KX_TouchSensor),
211         0,
212         PyDestructor,
213         0,
214         __getattr,
215         __setattr,
216         0, //&MyPyCompare,
217         __repr,
218         0, //&cvalue_as_number,
219         0,
220         0,
221         0,
222         0
223 };
224
225 PyParentObject KX_TouchSensor::Parents[] = {
226         &KX_TouchSensor::Type,
227         &SCA_ISensor::Type,
228         &SCA_ILogicBrick::Type,
229         &CValue::Type,
230         NULL
231 };
232
233 PyMethodDef KX_TouchSensor::Methods[] = {
234         {"setProperty", 
235          (PyCFunction) KX_TouchSensor::sPySetProperty,      METH_VARARGS, SetProperty_doc},
236         {"getProperty", 
237          (PyCFunction) KX_TouchSensor::sPyGetProperty,      METH_VARARGS, GetProperty_doc},
238         {"getHitObject", 
239          (PyCFunction) KX_TouchSensor::sPyGetHitObject,     METH_VARARGS, GetHitObject_doc},
240         {"getHitObjectList", 
241          (PyCFunction) KX_TouchSensor::sPyGetHitObjectList, METH_VARARGS, GetHitObjectList_doc},
242         {NULL,NULL} //Sentinel
243 };
244
245 PyObject* KX_TouchSensor::_getattr(const STR_String& attr) {
246         _getattr_up(SCA_ISensor);
247 }
248
249 /* Python API */
250
251 /* 1. setProperty */
252 char KX_TouchSensor::SetProperty_doc[] = 
253 "setProperty(name)\n"
254 "\t- name: string\n"
255 "\tSet the property or material to collide with. Use\n"
256 "\tsetTouchMaterial() to switch between properties and\n"
257 "\tmaterials.";
258 PyObject* KX_TouchSensor::PySetProperty(PyObject* self, 
259                                                                                 PyObject* args, 
260                                                                                 PyObject* kwds) {
261         char *nameArg;
262         if (!PyArg_ParseTuple(args, "s", &nameArg)) {
263                 return NULL;
264         }
265
266         CValue* prop = GetParent()->FindIdentifier(nameArg);
267
268         if (!prop->IsError()) {
269                 m_touchedpropname = nameArg;
270         } else {
271                 ; /* not found ... */
272         }
273         prop->Release();
274         
275         Py_Return;
276 }
277 /* 2. getProperty */
278 char KX_TouchSensor::GetProperty_doc[] = 
279 "getProperty(name)\n"
280 "\tReturns the property or material to collide with. Use\n"
281 "\tgetTouchMaterial() to find out whether this sensor\n"
282 "\tlooks for properties or materials.";
283 PyObject*  KX_TouchSensor::PyGetProperty(PyObject* self, 
284                                                                                  PyObject* args, 
285                                                                                  PyObject* kwds) {
286         return PyString_FromString(m_touchedpropname);
287 }
288
289 char KX_TouchSensor::GetHitObject_doc[] = 
290 "getHitObject()\n"
291 ;
292 PyObject* KX_TouchSensor::PyGetHitObject(PyObject* self, 
293                                                                                  PyObject* args, 
294                                                                                  PyObject* kwds)
295 {
296         /* to do: do Py_IncRef if the object is already known in Python */
297         /* otherwise, this leaks memory */
298         if (m_hitObject)
299         {
300                 return m_hitObject->AddRef();
301         }
302         Py_Return;
303 }
304
305 char KX_TouchSensor::GetHitObjectList_doc[] = 
306 "getHitObjectList()\n"
307 "\tReturn a list of the objects this object collided with,\n"
308 "\tbut only those matching the property/material condition.\n";
309 PyObject* KX_TouchSensor::PyGetHitObjectList(PyObject* self, 
310                                                                                  PyObject* args, 
311                                                                                  PyObject* kwds)
312 {
313
314         /* to do: do Py_IncRef if the object is already known in Python */
315         /* otherwise, this leaks memory */
316
317         if ( m_touchedpropname.IsEmpty() ) {
318                 return m_colliders->AddRef();
319         } else {
320                 CListValue* newList = new CListValue();
321                 int i = 0;
322                 while (i < m_colliders->GetCount()) {
323                         if (m_bFindMaterial) {
324                                 /* need to associate the CValues from the list to material
325                                  * names. The collider list _should_ contains only
326                                  * KX_GameObjects. I am loathe to cast them, though... The
327                                  * material name must be retrieved from Sumo. To a Sumo
328                                  * object, a client-info block is attached. This block
329                                  * contains the material name. 
330                                  * - this also doesn't work (obviously) for multi-materials... 
331                                  */
332                                 KX_GameObject* gameob = (KX_GameObject*) m_colliders->GetValue(i);
333                                 PHY_IPhysicsController* spc = dynamic_cast<PHY_IPhysicsController*>(gameob->GetPhysicsController());
334                                 
335                                 if (spc) {
336                                         KX_ClientObjectInfo* cl_inf = static_cast<KX_ClientObjectInfo*>(spc->getNewClientInfo());
337                                         
338                                         if (m_touchedpropname == ((char*)cl_inf->m_auxilary_info)) {
339                                                 newList->Add(m_colliders->GetValue(i)->AddRef());
340                                         } 
341                                 }
342                                 
343                         } else {
344                                 CValue* val = m_colliders->GetValue(i)->FindIdentifier(m_touchedpropname);
345                                 if (!val->IsError()) {
346                                         newList->Add(m_colliders->GetValue(i)->AddRef());
347                                 }
348                                 val->Release();
349                         }
350                         
351                         i++;
352                 }
353                 return newList->AddRef();
354         }
355
356 }
357
358 /* 5. getTouchMaterial */
359 char KX_TouchSensor::GetTouchMaterial_doc[] = 
360 "getTouchMaterial()\n"
361 "\tReturns KX_TRUE if this sensor looks for a specific material,\n"
362 "\tKX_FALSE if it looks for a specific property.\n" ;
363 PyObject* KX_TouchSensor::PyGetTouchMaterial(PyObject* self, 
364                                                                                          PyObject* args, 
365                                                                                          PyObject* kwds)
366 {
367         return PyInt_FromLong(m_bFindMaterial);
368 }
369
370 /* 6. setTouchMaterial */
371 char KX_TouchSensor::SetTouchMaterial_doc[] = 
372 "setTouchMaterial(flag)\n"
373 "\t- flag: KX_TRUE or KX_FALSE.\n"
374 "\tSet flag to KX_TRUE to switch on positive pulse mode,\n"
375 "\tKX_FALSE to switch off positive pulse mode.\n" ;
376 PyObject* KX_TouchSensor::PySetTouchMaterial(PyObject* self, PyObject* args, PyObject* kwds)
377 {
378         int pulseArg = 0;
379
380         if(!PyArg_ParseTuple(args, "i", &pulseArg)) {
381                 return NULL;
382         }
383         
384         m_bFindMaterial = pulseArg != 0;
385
386         Py_Return;
387 }
388
389
390 /* eof */