At last... this merge should finally do the trick!
[blender.git] / source / gameengine / Ketsji / KX_GameObject.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  * Game object wrapper
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #include <config.h>
33 #endif
34
35 #if defined(_WIN64)
36 typedef unsigned __int64 uint_ptr;
37 #else
38 typedef unsigned long uint_ptr;
39 #endif
40
41 #ifdef WIN32
42 // This warning tells us about truncation of __long__ stl-generated names.
43 // It can occasionally cause DevStudio to have internal compiler warnings.
44 #pragma warning( disable : 4786 )     
45 #endif
46
47
48 #define KX_INERTIA_INFINITE 10000
49 #include "RAS_IPolygonMaterial.h"
50 #include "KX_BlenderMaterial.h"
51 #include "KX_GameObject.h"
52 #include "KX_Camera.h" // only for their ::Type
53 #include "KX_Light.h"  // only for their ::Type
54 #include "RAS_MeshObject.h"
55 #include "KX_MeshProxy.h"
56 #include "KX_PolyProxy.h"
57 #include <stdio.h> // printf
58 #include "SG_Controller.h"
59 #include "KX_IPhysicsController.h"
60 #include "PHY_IGraphicController.h"
61 #include "SG_Node.h"
62 #include "SG_Controller.h"
63 #include "KX_ClientObjectInfo.h"
64 #include "RAS_BucketManager.h"
65 #include "KX_RayCast.h"
66 #include "KX_PythonInit.h"
67 #include "KX_PyMath.h"
68 #include "KX_PythonSeq.h"
69 #include "SCA_IActuator.h"
70 #include "SCA_ISensor.h"
71 #include "SCA_IController.h"
72 #include "NG_NetworkScene.h" //Needed for sendMessage()
73
74 #include "PyObjectPlus.h" /* python stuff */
75
76 // This file defines relationships between parents and children
77 // in the game engine.
78
79 #include "KX_SG_NodeRelationships.h"
80
81 static MT_Point3 dummy_point= MT_Point3(0.0, 0.0, 0.0);
82 static MT_Vector3 dummy_scaling = MT_Vector3(1.0, 1.0, 1.0);
83 static MT_Matrix3x3 dummy_orientation = MT_Matrix3x3(   1.0, 0.0, 0.0,
84                                                                                                                 0.0, 1.0, 0.0,
85                                                                                                                 0.0, 0.0, 1.0);
86
87 KX_GameObject::KX_GameObject(
88         void* sgReplicationInfo,
89         SG_Callbacks callbacks,
90         PyTypeObject* T
91 ) : 
92         SCA_IObject(T),
93         m_bDyna(false),
94         m_layer(0),
95         m_pBlenderObject(NULL),
96         m_pBlenderGroupObject(NULL),
97         m_bSuspendDynamics(false),
98         m_bUseObjectColor(false),
99         m_bIsNegativeScaling(false),
100         m_bVisible(true),
101         m_bCulled(true),
102         m_bOccluder(false),
103         m_pPhysicsController1(NULL),
104         m_pGraphicController(NULL),
105         m_pPhysicsEnvironment(NULL),
106         m_xray(false),
107         m_pHitObject(NULL),
108         m_isDeformable(false),
109         m_attr_dict(NULL)
110 {
111         m_ignore_activity_culling = false;
112         m_pClient_info = new KX_ClientObjectInfo(this, KX_ClientObjectInfo::ACTOR);
113         m_pSGNode = new SG_Node(this,sgReplicationInfo,callbacks);
114
115         // define the relationship between this node and it's parent.
116         
117         KX_NormalParentRelation * parent_relation = 
118                 KX_NormalParentRelation::New();
119         m_pSGNode->SetParentRelation(parent_relation);
120 };
121
122
123
124 KX_GameObject::~KX_GameObject()
125 {
126         RemoveMeshes();
127
128         // is this delete somewhere ?
129         //if (m_sumoObj)
130         //      delete m_sumoObj;
131         delete m_pClient_info;
132         //if (m_pSGNode)
133         //      delete m_pSGNode;
134         if (m_pSGNode)
135         {
136                 // must go through controllers and make sure they will not use us anymore
137                 // This is important for KX_BulletPhysicsControllers that unregister themselves
138                 // from the object when they are deleted.
139                 SGControllerList::iterator contit;
140                 SGControllerList& controllers = m_pSGNode->GetSGControllerList();
141                 for (contit = controllers.begin();contit!=controllers.end();++contit)
142                 {
143                         (*contit)->ClearObject();
144                 }
145                 m_pSGNode->SetSGClientObject(NULL);
146         }
147         if (m_pGraphicController)
148         {
149                 delete m_pGraphicController;
150         }
151         
152         if (m_attr_dict) {
153                 PyDict_Clear(m_attr_dict); /* incase of circular refs or other weired cases */
154                 Py_DECREF(m_attr_dict);
155         }
156 }
157
158 KX_GameObject* KX_GameObject::GetClientObject(KX_ClientObjectInfo* info)
159 {
160         if (!info)
161                 return NULL;
162         return info->m_gameobject;
163 }
164
165 CValue* KX_GameObject:: Calc(VALUE_OPERATOR op, CValue *val) 
166 {
167         return NULL;
168 }
169
170
171
172 CValue* KX_GameObject::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
173 {
174         return NULL;
175 }
176
177
178
179 const STR_String & KX_GameObject::GetText()
180 {
181         return m_text;
182 }
183
184
185
186 double KX_GameObject::GetNumber()
187 {
188         return 0;
189 }
190
191
192
193 STR_String& KX_GameObject::GetName()
194 {
195         return m_name;
196 }
197
198
199
200 void KX_GameObject::SetName(const char *name)
201 {
202         m_name = name;
203 };                                                              // Set the name of the value
204
205 KX_IPhysicsController* KX_GameObject::GetPhysicsController()
206 {
207         return m_pPhysicsController1;
208 }
209
210 KX_GameObject* KX_GameObject::GetParent()
211 {
212         KX_GameObject* result = NULL;
213         SG_Node* node = m_pSGNode;
214         
215         while (node && !result)
216         {
217                 node = node->GetSGParent();
218                 if (node)
219                         result = (KX_GameObject*)node->GetSGClientObject();
220         }
221         
222         if (result)
223                 result->AddRef();
224
225         return result;
226         
227 }
228
229 void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj, bool addToCompound, bool ghost)
230 {
231         // check on valid node in case a python controller holds a reference to a deleted object
232         if (obj && GetSGNode() && obj->GetSGNode() && GetSGNode()->GetSGParent() != obj->GetSGNode())
233         {
234                 // Make sure the objects have some scale
235                 MT_Vector3 scale1 = NodeGetWorldScaling();
236                 MT_Vector3 scale2 = obj->NodeGetWorldScaling();
237                 if (fabs(scale2[0]) < FLT_EPSILON || 
238                         fabs(scale2[1]) < FLT_EPSILON || 
239                         fabs(scale2[2]) < FLT_EPSILON || 
240                         fabs(scale1[0]) < FLT_EPSILON || 
241                         fabs(scale1[1]) < FLT_EPSILON || 
242                         fabs(scale1[2]) < FLT_EPSILON) { return; }
243
244                 // Remove us from our old parent and set our new parent
245                 RemoveParent(scene);
246                 obj->GetSGNode()->AddChild(GetSGNode());
247
248                 if (m_pPhysicsController1) 
249                 {
250                         m_pPhysicsController1->SuspendDynamics(ghost);
251                 }
252                 // Set us to our new scale, position, and orientation
253                 scale2[0] = 1.0/scale2[0];
254                 scale2[1] = 1.0/scale2[1];
255                 scale2[2] = 1.0/scale2[2];
256                 scale1 = scale1 * scale2;
257                 MT_Matrix3x3 invori = obj->NodeGetWorldOrientation().inverse();
258                 MT_Vector3 newpos = invori*(NodeGetWorldPosition()-obj->NodeGetWorldPosition())*scale2;
259
260                 NodeSetLocalScale(scale1);
261                 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
262                 NodeSetLocalOrientation(invori*NodeGetWorldOrientation());
263                 NodeUpdateGS(0.f);
264                 // object will now be a child, it must be removed from the parent list
265                 CListValue* rootlist = scene->GetRootParentList();
266                 if (rootlist->RemoveValue(this))
267                         // the object was in parent list, decrement ref count as it's now removed
268                         Release();
269                 // if the new parent is a compound object, add this object shape to the compound shape.
270                 // step 0: verify this object has physical controller
271                 if (m_pPhysicsController1 && addToCompound)
272                 {
273                         // step 1: find the top parent (not necessarily obj)
274                         KX_GameObject* rootobj = (KX_GameObject*)obj->GetSGNode()->GetRootSGParent()->GetSGClientObject();
275                         // step 2: verify it has a physical controller and compound shape
276                         if (rootobj != NULL && 
277                                 rootobj->m_pPhysicsController1 != NULL &&
278                                 rootobj->m_pPhysicsController1->IsCompound())
279                         {
280                                 rootobj->m_pPhysicsController1->AddCompoundChild(m_pPhysicsController1);
281                         }
282                 }
283                 // graphically, the object hasn't change place, no need to update m_pGraphicController
284         }
285 }
286
287 void KX_GameObject::RemoveParent(KX_Scene *scene)
288 {
289         // check on valid node in case a python controller holds a reference to a deleted object
290         if (GetSGNode() && GetSGNode()->GetSGParent())
291         {
292                 // get the root object to remove us from compound object if needed
293                 KX_GameObject* rootobj = (KX_GameObject*)GetSGNode()->GetRootSGParent()->GetSGClientObject();
294                 // Set us to the right spot 
295                 GetSGNode()->SetLocalScale(GetSGNode()->GetWorldScaling());
296                 GetSGNode()->SetLocalOrientation(GetSGNode()->GetWorldOrientation());
297                 GetSGNode()->SetLocalPosition(GetSGNode()->GetWorldPosition());
298
299                 // Remove us from our parent
300                 GetSGNode()->DisconnectFromParent();
301                 NodeUpdateGS(0.f);
302                 // the object is now a root object, add it to the parentlist
303                 CListValue* rootlist = scene->GetRootParentList();
304                 if (!rootlist->SearchValue(this))
305                         // object was not in root list, add it now and increment ref count
306                         rootlist->Add(AddRef());
307                 if (m_pPhysicsController1) 
308                 {
309                         // in case this controller was added as a child shape to the parent
310                         if (rootobj != NULL && 
311                                 rootobj->m_pPhysicsController1 != NULL &&
312                                 rootobj->m_pPhysicsController1->IsCompound())
313                         {
314                                 rootobj->m_pPhysicsController1->RemoveCompoundChild(m_pPhysicsController1);
315                         }
316                         m_pPhysicsController1->RestoreDynamics();
317                         if (m_pPhysicsController1->IsDyna() && rootobj->m_pPhysicsController1)
318                         {
319                                 // dynamic object should remember the velocity they had while being parented
320                                 MT_Point3 childPoint = GetSGNode()->GetWorldPosition();
321                                 MT_Point3 rootPoint = rootobj->GetSGNode()->GetWorldPosition();
322                                 MT_Point3 relPoint;
323                                 relPoint = (childPoint-rootPoint);
324                                 MT_Vector3 linVel = rootobj->m_pPhysicsController1->GetVelocity(relPoint);
325                                 MT_Vector3 angVel = rootobj->m_pPhysicsController1->GetAngularVelocity();
326                                 m_pPhysicsController1->SetLinearVelocity(linVel, false);
327                                 m_pPhysicsController1->SetAngularVelocity(angVel, false);
328                         }
329                 }
330                 // graphically, the object hasn't change place, no need to update m_pGraphicController
331         }
332 }
333
334 void KX_GameObject::ProcessReplica()
335 {
336         SCA_IObject::ProcessReplica();
337         
338         m_pPhysicsController1 = NULL;
339         m_pGraphicController = NULL;
340         m_pSGNode = NULL;
341         m_pClient_info = new KX_ClientObjectInfo(*m_pClient_info);
342         m_pClient_info->m_gameobject = this;
343         m_state = 0;
344         if(m_attr_dict)
345                 m_attr_dict= PyDict_Copy(m_attr_dict);
346                 
347 }
348
349 static void setGraphicController_recursive(SG_Node* node)
350 {
351         NodeList& children = node->GetSGChildren();
352
353         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
354         {
355                 SG_Node* childnode = (*childit);
356                 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
357                 if (clientgameobj != NULL) // This is a GameObject
358                         clientgameobj->ActivateGraphicController(false);
359                 
360                 // if the childobj is NULL then this may be an inverse parent link
361                 // so a non recursive search should still look down this node.
362                 setGraphicController_recursive(childnode);
363         }
364 }
365
366
367 void KX_GameObject::ActivateGraphicController(bool recurse)
368 {
369         if (m_pGraphicController)
370         {
371                 m_pGraphicController->Activate(m_bVisible);
372         }
373         if (recurse)
374         {
375                 setGraphicController_recursive(GetSGNode());
376         }
377 }
378
379
380 CValue* KX_GameObject::GetReplica()
381 {
382         KX_GameObject* replica = new KX_GameObject(*this);
383
384         // this will copy properties and so on...
385         replica->ProcessReplica();
386
387         return replica;
388 }
389
390
391
392 void KX_GameObject::ApplyForce(const MT_Vector3& force,bool local)
393 {
394         if (m_pPhysicsController1)
395                 m_pPhysicsController1->ApplyForce(force,local);
396 }
397
398
399
400 void KX_GameObject::ApplyTorque(const MT_Vector3& torque,bool local)
401 {
402         if (m_pPhysicsController1)
403                 m_pPhysicsController1->ApplyTorque(torque,local);
404 }
405
406
407
408 void KX_GameObject::ApplyMovement(const MT_Vector3& dloc,bool local)
409 {
410         if (GetSGNode()) 
411         {
412                 if (m_pPhysicsController1) // (IsDynamic())
413                 {
414                         m_pPhysicsController1->RelativeTranslate(dloc,local);
415                 }
416                 GetSGNode()->RelativeTranslate(dloc,GetSGNode()->GetSGParent(),local);
417         }
418 }
419
420
421
422 void KX_GameObject::ApplyRotation(const MT_Vector3& drot,bool local)
423 {
424         MT_Matrix3x3 rotmat(drot);
425         
426         if (GetSGNode()) {
427                 GetSGNode()->RelativeRotate(rotmat,local);
428
429                 if (m_pPhysicsController1) { // (IsDynamic())
430                         m_pPhysicsController1->RelativeRotate(rotmat,local); 
431                 }
432         }
433 }
434
435
436
437 /**
438 GetOpenGL Matrix, returns an OpenGL 'compatible' matrix
439 */
440 double* KX_GameObject::GetOpenGLMatrix()
441 {
442         // todo: optimize and only update if necessary
443         double* fl = m_OpenGL_4x4Matrix.getPointer();
444         if (GetSGNode()) {
445                 MT_Transform trans;
446         
447                 trans.setOrigin(GetSGNode()->GetWorldPosition());
448                 trans.setBasis(GetSGNode()->GetWorldOrientation());
449         
450                 MT_Vector3 scaling = GetSGNode()->GetWorldScaling();
451                 m_bIsNegativeScaling = ((scaling[0] < 0.0) ^ (scaling[1] < 0.0) ^ (scaling[2] < 0.0)) ? true : false;
452                 trans.scale(scaling[0], scaling[1], scaling[2]);
453                 trans.getValue(fl);
454                 GetSGNode()->ClearDirty();
455         }
456         return fl;
457 }
458
459 void KX_GameObject::AddMeshUser()
460 {
461         for (size_t i=0;i<m_meshes.size();i++)
462         {
463                 m_meshes[i]->AddMeshUser(this, &m_meshSlots, GetDeformer());
464         }
465         // set the part of the mesh slot that never change
466         double* fl = GetOpenGLMatrixPtr()->getPointer();
467
468         SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
469         RAS_MeshSlot* ms;
470         for(mit.begin(); !mit.end(); ++mit)
471         {
472                 (*mit)->m_OpenGLMatrix = fl;
473         }
474         UpdateBuckets(false);
475 }
476
477 static void UpdateBuckets_recursive(SG_Node* node)
478 {
479         NodeList& children = node->GetSGChildren();
480
481         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
482         {
483                 SG_Node* childnode = (*childit);
484                 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
485                 if (clientgameobj != NULL) // This is a GameObject
486                         clientgameobj->UpdateBuckets(0);
487                 
488                 // if the childobj is NULL then this may be an inverse parent link
489                 // so a non recursive search should still look down this node.
490                 UpdateBuckets_recursive(childnode);
491         }
492 }
493
494 void KX_GameObject::UpdateBuckets( bool recursive )
495 {
496         if (GetSGNode()) {
497                 RAS_MeshSlot *ms;
498
499                 if (GetSGNode()->IsDirty())
500                         GetOpenGLMatrix();
501
502                 SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
503                 for(mit.begin(); !mit.end(); ++mit)
504                 {
505                         ms = *mit;
506                         ms->m_bObjectColor = m_bUseObjectColor;
507                         ms->m_RGBAcolor = m_objectColor;
508                         ms->m_bVisible = m_bVisible;
509                         ms->m_bCulled = m_bCulled || !m_bVisible;
510                         if (!ms->m_bCulled) 
511                                 ms->m_bucket->ActivateMesh(ms);
512                         
513                         /* split if necessary */
514 #ifdef USE_SPLIT
515                         ms->Split();
516 #endif
517                 }
518         
519                 if (recursive) {
520                         UpdateBuckets_recursive(GetSGNode());
521                 }
522         }
523 }
524
525 void KX_GameObject::RemoveMeshes()
526 {
527         for (size_t i=0;i<m_meshes.size();i++)
528                 m_meshes[i]->RemoveFromBuckets(this);
529
530         //note: meshes can be shared, and are deleted by KX_BlenderSceneConverter
531
532         m_meshes.clear();
533 }
534
535 void KX_GameObject::UpdateTransform()
536 {
537         // HACK: saves function call for dynamic object, they are handled differently
538         if (m_pPhysicsController1 && !m_pPhysicsController1->IsDyna())
539                 // Note that for Bullet, this does not even update the transform of static object
540                 // but merely sets there collision flag to "kinematic" because the synchronization is 
541                 // done during physics simulation
542                 m_pPhysicsController1->SetSumoTransform(true);
543         if (m_pGraphicController)
544                 // update the culling tree
545                 m_pGraphicController->SetGraphicTransform();
546
547 }
548
549 void KX_GameObject::UpdateTransformFunc(SG_IObject* node, void* gameobj, void* scene)
550 {
551         ((KX_GameObject*)gameobj)->UpdateTransform();
552 }
553
554 void KX_GameObject::SynchronizeTransform()
555 {
556         // only used for sensor object, do full synchronization as bullet doesn't do it
557         if (m_pPhysicsController1)
558                 m_pPhysicsController1->SetTransform();
559         if (m_pGraphicController)
560                 m_pGraphicController->SetGraphicTransform();
561 }
562
563 void KX_GameObject::SynchronizeTransformFunc(SG_IObject* node, void* gameobj, void* scene)
564 {
565         ((KX_GameObject*)gameobj)->SynchronizeTransform();
566 }
567
568
569 void KX_GameObject::SetDebugColor(unsigned int bgra)
570 {
571         for (size_t i=0;i<m_meshes.size();i++)
572                 m_meshes[i]->DebugColor(bgra);  
573 }
574
575
576
577 void KX_GameObject::ResetDebugColor()
578 {
579         SetDebugColor(0xff000000);
580 }
581
582 void KX_GameObject::InitIPO(bool ipo_as_force,
583                                                         bool ipo_add,
584                                                         bool ipo_local)
585 {
586         SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin();
587
588         while (it != GetSGNode()->GetSGControllerList().end()) {
589                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true);
590                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, ipo_as_force);
591                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, ipo_add);
592                 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, ipo_local);
593                 it++;
594         }
595
596
597 void KX_GameObject::UpdateIPO(float curframetime,
598                                                           bool recurse) 
599 {
600         // just the 'normal' update procedure.
601         GetSGNode()->SetSimulatedTime(curframetime,recurse);
602         GetSGNode()->UpdateWorldData(curframetime);
603         UpdateTransform();
604 }
605
606 // IPO update
607 void 
608 KX_GameObject::UpdateMaterialData(
609                 dword matname_hash,
610                 MT_Vector4 rgba,
611                 MT_Vector3 specrgb,
612                 MT_Scalar hard,
613                 MT_Scalar spec,
614                 MT_Scalar ref,
615                 MT_Scalar emit,
616                 MT_Scalar alpha
617
618         )
619 {
620         int mesh = 0;
621         if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) {
622                 list<RAS_MeshMaterial>::iterator mit = m_meshes[mesh]->GetFirstMaterial();
623
624                 for(; mit != m_meshes[mesh]->GetLastMaterial(); ++mit)
625                 {
626                         RAS_IPolyMaterial* poly = mit->m_bucket->GetPolyMaterial();
627
628                         if(poly->GetFlag() & RAS_BLENDERMAT )
629                         {
630                                 KX_BlenderMaterial *m =  static_cast<KX_BlenderMaterial*>(poly);
631                                 
632                                 if (matname_hash == 0)
633                                 {
634                                         m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
635                                         // if mesh has only one material attached to it then use original hack with no need to edit vertices (better performance)
636                                         SetObjectColor(rgba);
637                                 }
638                                 else
639                                 {
640                                         if (matname_hash == poly->GetMaterialNameHash())
641                                         {
642                                                 m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
643                                                 m_meshes[mesh]->SetVertexColor(poly,rgba);
644                                                 
645                                                 // no break here, because one blender material can be split into several game engine materials
646                                                 // (e.g. one uvsphere material is split into one material at poles with ras_mode TRIANGLE and one material for the body
647                                                 // if here was a break then would miss some vertices if material was split
648                                         }
649                                 }
650                         }
651                 }
652         }
653 }
654 bool
655 KX_GameObject::GetVisible(
656         void
657         )
658 {
659         return m_bVisible;
660 }
661
662 static void setVisible_recursive(SG_Node* node, bool v)
663 {
664         NodeList& children = node->GetSGChildren();
665
666         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
667         {
668                 SG_Node* childnode = (*childit);
669                 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
670                 if (clientgameobj != NULL) // This is a GameObject
671                         clientgameobj->SetVisible(v, 0);
672                 
673                 // if the childobj is NULL then this may be an inverse parent link
674                 // so a non recursive search should still look down this node.
675                 setVisible_recursive(childnode, v);
676         }
677 }
678
679
680 void
681 KX_GameObject::SetVisible(
682         bool v,
683         bool recursive
684         )
685 {
686         if (GetSGNode()) {
687                 m_bVisible = v;
688                 if (m_pGraphicController)
689                         m_pGraphicController->Activate(m_bVisible);
690                 if (recursive)
691                         setVisible_recursive(GetSGNode(), v);
692         }
693 }
694
695 static void setOccluder_recursive(SG_Node* node, bool v)
696 {
697         NodeList& children = node->GetSGChildren();
698
699         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
700         {
701                 SG_Node* childnode = (*childit);
702                 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
703                 if (clientgameobj != NULL) // This is a GameObject
704                         clientgameobj->SetOccluder(v, false);
705                 
706                 // if the childobj is NULL then this may be an inverse parent link
707                 // so a non recursive search should still look down this node.
708                 setOccluder_recursive(childnode, v);
709         }
710 }
711
712 void
713 KX_GameObject::SetOccluder(
714         bool v,
715         bool recursive
716         )
717 {
718         if (GetSGNode()) {
719                 m_bOccluder = v;
720                 if (recursive)
721                         setOccluder_recursive(GetSGNode(), v);
722         }
723 }
724
725 void
726 KX_GameObject::SetLayer(
727         int l
728         )
729 {
730         m_layer = l;
731 }
732
733 int
734 KX_GameObject::GetLayer(
735         void
736         )
737 {
738         return m_layer;
739 }
740
741 void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local)
742 {
743         if (m_pPhysicsController1) 
744         {
745                 MT_Vector3 lv = local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
746                 m_pPhysicsController1->SetLinearVelocity(lv + m_pPhysicsController1->GetLinearVelocity(), 0);
747         }
748 }
749
750
751
752 void KX_GameObject::setLinearVelocity(const MT_Vector3& lin_vel,bool local)
753 {
754         if (m_pPhysicsController1)
755                 m_pPhysicsController1->SetLinearVelocity(lin_vel,local);
756 }
757
758
759
760 void KX_GameObject::setAngularVelocity(const MT_Vector3& ang_vel,bool local)
761 {
762         if (m_pPhysicsController1)
763                 m_pPhysicsController1->SetAngularVelocity(ang_vel,local);
764 }
765
766
767 void KX_GameObject::ResolveCombinedVelocities(
768         const MT_Vector3 & lin_vel,
769         const MT_Vector3 & ang_vel,
770         bool lin_vel_local,
771         bool ang_vel_local
772 ){
773         if (m_pPhysicsController1)
774         {
775
776                 MT_Vector3 lv = lin_vel_local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
777                 MT_Vector3 av = ang_vel_local ? NodeGetWorldOrientation() * ang_vel : ang_vel;
778                 m_pPhysicsController1->resolveCombinedVelocities(
779                         lv.x(),lv.y(),lv.z(),av.x(),av.y(),av.z());
780         }
781 }
782
783
784 void KX_GameObject::SetObjectColor(const MT_Vector4& rgbavec)
785 {
786         m_bUseObjectColor = true;
787         m_objectColor = rgbavec;
788 }
789
790 void KX_GameObject::AlignAxisToVect(const MT_Vector3& dir, int axis, float fac)
791 {
792         MT_Matrix3x3 orimat;
793         MT_Vector3 vect,ori,z,x,y;
794         MT_Scalar len;
795
796         // check on valid node in case a python controller holds a reference to a deleted object
797         if (!GetSGNode())
798                 return;
799
800         vect = dir;
801         len = vect.length();
802         if (MT_fuzzyZero(len))
803         {
804                 cout << "alignAxisToVect() Error: Null vector!\n";
805                 return;
806         }
807         
808         if (fac<=0.0) {
809                 return;
810         }
811         
812         // normalize
813         vect /= len;
814         orimat = GetSGNode()->GetWorldOrientation();
815         switch (axis)
816         {       
817                 case 0: //x axis
818                         ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]); //pivot axis
819                         if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON) //is the vector paralell to the pivot?
820                                 ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]); //change the pivot!
821                         if (fac == 1.0) {
822                                 x = vect;
823                         } else {
824                                 x = (vect * fac) + ((orimat * MT_Vector3(1.0, 0.0, 0.0)) * (1-fac));
825                                 len = x.length();
826                                 if (MT_fuzzyZero(len)) x = vect;
827                                 else x /= len;
828                         }
829                         y = ori.cross(x);
830                         z = x.cross(y);
831                         break;
832                 case 1: //y axis
833                         ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
834                         if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
835                                 ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]);
836                         if (fac == 1.0) {
837                                 y = vect;
838                         } else {
839                                 y = (vect * fac) + ((orimat * MT_Vector3(0.0, 1.0, 0.0)) * (1-fac));
840                                 len = y.length();
841                                 if (MT_fuzzyZero(len)) y = vect;
842                                 else y /= len;
843                         }
844                         z = ori.cross(y);
845                         x = y.cross(z);
846                         break;
847                 case 2: //z axis
848                         ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]);
849                         if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
850                                 ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
851                         if (fac == 1.0) {
852                                 z = vect;
853                         } else {
854                                 z = (vect * fac) + ((orimat * MT_Vector3(0.0, 0.0, 1.0)) * (1-fac));
855                                 len = z.length();
856                                 if (MT_fuzzyZero(len)) z = vect;
857                                 else z /= len;
858                         }
859                         x = ori.cross(z);
860                         y = z.cross(x);
861                         break;
862                 default: //wrong input?
863                         cout << "alignAxisToVect(): Wrong axis '" << axis <<"'\n";
864                         return;
865         }
866         x.normalize(); //normalize the vectors
867         y.normalize();
868         z.normalize();
869         orimat.setValue(        x[0],y[0],z[0],
870                                                 x[1],y[1],z[1],
871                                                 x[2],y[2],z[2]);
872         if (GetSGNode()->GetSGParent() != NULL)
873         {
874                 // the object is a child, adapt its local orientation so that 
875                 // the global orientation is aligned as we want.
876                 MT_Matrix3x3 invori = GetSGNode()->GetSGParent()->GetWorldOrientation().inverse();
877                 NodeSetLocalOrientation(invori*orimat);
878         }
879         else
880                 NodeSetLocalOrientation(orimat);
881 }
882
883 MT_Scalar KX_GameObject::GetMass()
884 {
885         if (m_pPhysicsController1)
886         {
887                 return m_pPhysicsController1->GetMass();
888         }
889         return 0.0;
890 }
891
892 MT_Vector3 KX_GameObject::GetLocalInertia()
893 {
894         MT_Vector3 local_inertia(0.0,0.0,0.0);
895         if (m_pPhysicsController1)
896         {
897                 local_inertia = m_pPhysicsController1->GetLocalInertia();
898         }
899         return local_inertia;
900 }
901
902 MT_Vector3 KX_GameObject::GetLinearVelocity(bool local)
903 {
904         MT_Vector3 velocity(0.0,0.0,0.0), locvel;
905         MT_Matrix3x3 ori;
906         if (m_pPhysicsController1)
907         {
908                 velocity = m_pPhysicsController1->GetLinearVelocity();
909                 
910                 if (local)
911                 {
912                         ori = GetSGNode()->GetWorldOrientation();
913                         
914                         locvel = velocity * ori;
915                         return locvel;
916                 }
917         }
918         return velocity;        
919 }
920
921 MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
922 {
923         MT_Vector3 velocity(0.0,0.0,0.0), locvel;
924         MT_Matrix3x3 ori;
925         if (m_pPhysicsController1)
926         {
927                 velocity = m_pPhysicsController1->GetAngularVelocity();
928                 
929                 if (local)
930                 {
931                         ori = GetSGNode()->GetWorldOrientation();
932                         
933                         locvel = velocity * ori;
934                         return locvel;
935                 }
936         }
937         return velocity;        
938 }
939
940 MT_Vector3 KX_GameObject::GetVelocity(const MT_Point3& point)
941 {
942         if (m_pPhysicsController1)
943         {
944                 return m_pPhysicsController1->GetVelocity(point);
945         }
946         return MT_Vector3(0.0,0.0,0.0);
947 }
948
949 // scenegraph node stuff
950
951 void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans)
952 {
953         // check on valid node in case a python controller holds a reference to a deleted object
954         if (!GetSGNode())
955                 return;
956
957         if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
958         {
959                 // don't update physic controller if the object is a child:
960                 // 1) the transformation will not be right
961                 // 2) in this case, the physic controller is necessarily a static object
962                 //    that is updated from the normal kinematic synchronization
963                 m_pPhysicsController1->setPosition(trans);
964         }
965
966         GetSGNode()->SetLocalPosition(trans);
967
968 }
969
970
971
972 void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3& rot)
973 {
974         // check on valid node in case a python controller holds a reference to a deleted object
975         if (!GetSGNode())
976                 return;
977
978         if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
979         {
980                 // see note above
981                 m_pPhysicsController1->setOrientation(rot);
982         }
983         GetSGNode()->SetLocalOrientation(rot);
984 }
985
986 void KX_GameObject::NodeSetGlobalOrientation(const MT_Matrix3x3& rot)
987 {
988         // check on valid node in case a python controller holds a reference to a deleted object
989         if (!GetSGNode())
990                 return;
991
992         if (GetSGNode()->GetSGParent())
993                 GetSGNode()->SetLocalOrientation(GetSGNode()->GetSGParent()->GetWorldOrientation().inverse()*rot);
994         else
995                 GetSGNode()->SetLocalOrientation(rot);
996 }
997
998 void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale)
999 {
1000         // check on valid node in case a python controller holds a reference to a deleted object
1001         if (!GetSGNode())
1002                 return;
1003
1004         if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
1005         {
1006                 // see note above
1007                 m_pPhysicsController1->setScaling(scale);
1008         }
1009         GetSGNode()->SetLocalScale(scale);
1010 }
1011
1012
1013
1014 void KX_GameObject::NodeSetRelativeScale(const MT_Vector3& scale)
1015 {
1016         if (GetSGNode())
1017         {
1018                 GetSGNode()->RelativeScale(scale);
1019                 if (m_pPhysicsController1 && (!GetSGNode()->GetSGParent()))
1020                 {
1021                         // see note above
1022                         // we can use the local scale: it's the same thing for a root object 
1023                         // and the world scale is not yet updated
1024                         MT_Vector3 newscale = GetSGNode()->GetLocalScale();
1025                         m_pPhysicsController1->setScaling(newscale);
1026                 }
1027         }
1028 }
1029
1030 void KX_GameObject::NodeSetWorldPosition(const MT_Point3& trans)
1031 {
1032         if (!GetSGNode())
1033                 return;
1034         SG_Node* parent = GetSGNode()->GetSGParent();
1035         if (parent != NULL)
1036         {
1037                 // Make sure the objects have some scale
1038                 MT_Vector3 scale = parent->GetWorldScaling();
1039                 if (fabs(scale[0]) < FLT_EPSILON || 
1040                         fabs(scale[1]) < FLT_EPSILON || 
1041                         fabs(scale[2]) < FLT_EPSILON)
1042                 { 
1043                         return; 
1044                 }
1045                 scale[0] = 1.0/scale[0];
1046                 scale[1] = 1.0/scale[1];
1047                 scale[2] = 1.0/scale[2];
1048                 MT_Matrix3x3 invori = parent->GetWorldOrientation().inverse();
1049                 MT_Vector3 newpos = invori*(trans-parent->GetWorldPosition())*scale;
1050                 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
1051         }
1052         else 
1053         {
1054                 NodeSetLocalPosition(trans);
1055         }
1056 }
1057
1058
1059 void KX_GameObject::NodeUpdateGS(double time)
1060 {
1061         if (GetSGNode())
1062                 GetSGNode()->UpdateWorldData(time);
1063 }
1064
1065
1066
1067 const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
1068 {
1069         // check on valid node in case a python controller holds a reference to a deleted object
1070         if (!GetSGNode())
1071                 return dummy_orientation;
1072         return GetSGNode()->GetWorldOrientation();
1073 }
1074
1075 const MT_Matrix3x3& KX_GameObject::NodeGetLocalOrientation() const
1076 {
1077         // check on valid node in case a python controller holds a reference to a deleted object
1078         if (!GetSGNode())
1079                 return dummy_orientation;
1080         return GetSGNode()->GetLocalOrientation();
1081 }
1082
1083 const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const
1084 {
1085         // check on valid node in case a python controller holds a reference to a deleted object
1086         if (!GetSGNode())
1087                 return dummy_scaling;
1088
1089         return GetSGNode()->GetWorldScaling();
1090 }
1091
1092 const MT_Vector3& KX_GameObject::NodeGetLocalScaling() const
1093 {
1094         // check on valid node in case a python controller holds a reference to a deleted object
1095         if (!GetSGNode())
1096                 return dummy_scaling;
1097
1098         return GetSGNode()->GetLocalScale();
1099 }
1100
1101 const MT_Point3& KX_GameObject::NodeGetWorldPosition() const
1102 {
1103         // check on valid node in case a python controller holds a reference to a deleted object
1104         if (GetSGNode())
1105                 return GetSGNode()->GetWorldPosition();
1106         else
1107                 return dummy_point;
1108 }
1109
1110 const MT_Point3& KX_GameObject::NodeGetLocalPosition() const
1111 {
1112         // check on valid node in case a python controller holds a reference to a deleted object
1113         if (GetSGNode())
1114                 return GetSGNode()->GetLocalPosition();
1115         else
1116                 return dummy_point;
1117 }
1118
1119
1120 /* Suspend/ resume: for the dynamic behaviour, there is a simple
1121  * method. For the residual motion, there is not. I wonder what the
1122  * correct solution is for Sumo. Remove from the motion-update tree?
1123  *
1124  * So far, only switch the physics and logic.
1125  * */
1126
1127 void KX_GameObject::Resume(void)
1128 {
1129         if (m_suspended) {
1130                 SCA_IObject::Resume();
1131                 if(GetPhysicsController())
1132                         GetPhysicsController()->RestoreDynamics();
1133
1134                 m_suspended = false;
1135         }
1136 }
1137
1138 void KX_GameObject::Suspend()
1139 {
1140         if ((!m_ignore_activity_culling) 
1141                 && (!m_suspended))  {
1142                 SCA_IObject::Suspend();
1143                 if(GetPhysicsController())
1144                         GetPhysicsController()->SuspendDynamics();
1145                 m_suspended = true;
1146         }
1147 }
1148
1149 static void walk_children(SG_Node* node, CListValue* list, bool recursive)
1150 {
1151         if (!node)
1152                 return;
1153         NodeList& children = node->GetSGChildren();
1154
1155         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
1156         {
1157                 SG_Node* childnode = (*childit);
1158                 CValue* childobj = (CValue*)childnode->GetSGClientObject();
1159                 if (childobj != NULL) // This is a GameObject
1160                 {
1161                         // add to the list
1162                         list->Add(childobj->AddRef());
1163                 }
1164                 
1165                 // if the childobj is NULL then this may be an inverse parent link
1166                 // so a non recursive search should still look down this node.
1167                 if (recursive || childobj==NULL) {
1168                         walk_children(childnode, list, recursive);
1169                 }
1170         }
1171 }
1172
1173 CListValue* KX_GameObject::GetChildren()
1174 {
1175         CListValue* list = new CListValue();
1176         walk_children(GetSGNode(), list, 0); /* GetSGNode() is always valid or it would have raised an exception before this */
1177         return list;
1178 }
1179
1180 CListValue* KX_GameObject::GetChildrenRecursive()
1181 {
1182         CListValue* list = new CListValue();
1183         walk_children(GetSGNode(), list, 1);
1184         return list;
1185 }
1186
1187
1188 #ifdef USE_MATHUTILS
1189 extern "C" {
1190 #include "../../blender/python/generic/Mathutils.h" /* so we can have mathutils callbacks */
1191 }
1192
1193 /* These require an SGNode */
1194 #define MATHUTILS_VEC_CB_POS_LOCAL 1
1195 #define MATHUTILS_VEC_CB_POS_GLOBAL 2
1196 #define MATHUTILS_VEC_CB_SCALE_LOCAL 3
1197 #define MATHUTILS_VEC_CB_SCALE_GLOBAL 4
1198 #define MATHUTILS_VEC_CB_INERTIA_LOCAL 5
1199
1200 static int mathutils_kxgameob_vector_cb_index= -1; /* index for our callbacks */
1201
1202 static int mathutils_kxgameob_generic_check(PyObject *self_v)
1203 {
1204         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1205         if(self==NULL)
1206                 return 0;
1207         
1208         return 1;
1209 }
1210
1211 static int mathutils_kxgameob_vector_get(PyObject *self_v, int subtype, float *vec_from)
1212 {
1213         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1214         if(self==NULL)
1215                 return 0;
1216         
1217         switch(subtype) {
1218                 case MATHUTILS_VEC_CB_POS_LOCAL:
1219                         self->NodeGetLocalPosition().getValue(vec_from);
1220                         break;
1221                 case MATHUTILS_VEC_CB_POS_GLOBAL:
1222                         self->NodeGetWorldPosition().getValue(vec_from);
1223                         break;
1224                 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1225                         self->NodeGetLocalScaling().getValue(vec_from);
1226                         break;
1227                 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1228                         self->NodeGetWorldScaling().getValue(vec_from);
1229                         break;
1230                 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1231                         if(!self->GetPhysicsController()) return 0;
1232                         self->GetPhysicsController()->GetLocalInertia().getValue(vec_from);
1233                         break;
1234         }
1235         
1236         return 1;
1237 }
1238
1239 static int mathutils_kxgameob_vector_set(PyObject *self_v, int subtype, float *vec_to)
1240 {
1241         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1242         if(self==NULL)
1243                 return 0;
1244         
1245         switch(subtype) {
1246                 case MATHUTILS_VEC_CB_POS_LOCAL:
1247                         self->NodeSetLocalPosition(MT_Point3(vec_to));
1248                         self->NodeUpdateGS(0.f);
1249                         break;
1250                 case MATHUTILS_VEC_CB_POS_GLOBAL:
1251                         self->NodeSetWorldPosition(MT_Point3(vec_to));
1252                         self->NodeUpdateGS(0.f);
1253                         break;
1254                 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1255                         self->NodeSetLocalScale(MT_Point3(vec_to));
1256                         self->NodeUpdateGS(0.f);
1257                         break;
1258                 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1259                         break;
1260                 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1261                         /* read only */
1262                         break;
1263         }
1264         
1265         return 1;
1266 }
1267
1268 static int mathutils_kxgameob_vector_get_index(PyObject *self_v, int subtype, float *vec_from, int index)
1269 {
1270         float f[4];
1271         /* lazy, avoid repeteing the case statement */
1272         if(!mathutils_kxgameob_vector_get(self_v, subtype, f))
1273                 return 0;
1274         
1275         vec_from[index]= f[index];
1276         return 1;
1277 }
1278
1279 static int mathutils_kxgameob_vector_set_index(PyObject *self_v, int subtype, float *vec_to, int index)
1280 {
1281         float f= vec_to[index];
1282         
1283         /* lazy, avoid repeteing the case statement */
1284         if(!mathutils_kxgameob_vector_get(self_v, subtype, vec_to))
1285                 return 0;
1286         
1287         vec_to[index]= f;
1288         mathutils_kxgameob_vector_set(self_v, subtype, vec_to);
1289         
1290         return 1;
1291 }
1292
1293 Mathutils_Callback mathutils_kxgameob_vector_cb = {
1294         mathutils_kxgameob_generic_check,
1295         mathutils_kxgameob_vector_get,
1296         mathutils_kxgameob_vector_set,
1297         mathutils_kxgameob_vector_get_index,
1298         mathutils_kxgameob_vector_set_index
1299 };
1300
1301 /* Matrix */
1302 #define MATHUTILS_MAT_CB_ORI_LOCAL 1
1303 #define MATHUTILS_MAT_CB_ORI_GLOBAL 2
1304
1305 static int mathutils_kxgameob_matrix_cb_index= -1; /* index for our callbacks */
1306
1307 static int mathutils_kxgameob_matrix_get(PyObject *self_v, int subtype, float *mat_from)
1308 {
1309         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1310         if(self==NULL)
1311                 return 0;
1312         
1313         switch(subtype) {
1314                 case MATHUTILS_MAT_CB_ORI_LOCAL:
1315                         self->NodeGetLocalOrientation().getValue3x3(mat_from);
1316                         break;
1317                 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1318                         self->NodeGetWorldOrientation().getValue3x3(mat_from);
1319                         break;
1320         }
1321         
1322         return 1;
1323 }
1324
1325
1326 static int mathutils_kxgameob_matrix_set(PyObject *self_v, int subtype, float *mat_to)
1327 {
1328         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1329         if(self==NULL)
1330                 return 0;
1331         
1332         MT_Matrix3x3 mat3x3;
1333         switch(subtype) {
1334                 case MATHUTILS_MAT_CB_ORI_LOCAL:
1335                         mat3x3.setValue3x3(mat_to);
1336                         self->NodeSetLocalOrientation(mat3x3);
1337                         self->NodeUpdateGS(0.f);
1338                         break;
1339                 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1340                         mat3x3.setValue3x3(mat_to);
1341                         self->NodeSetLocalOrientation(mat3x3);
1342                         self->NodeUpdateGS(0.f);
1343                         break;
1344         }
1345         
1346         return 1;
1347 }
1348
1349 Mathutils_Callback mathutils_kxgameob_matrix_cb = {
1350         mathutils_kxgameob_generic_check,
1351         mathutils_kxgameob_matrix_get,
1352         mathutils_kxgameob_matrix_set,
1353         NULL,
1354         NULL
1355 };
1356
1357
1358 void KX_GameObject_Mathutils_Callback_Init(void)
1359 {
1360         // register mathutils callbacks, ok to run more then once.
1361         mathutils_kxgameob_vector_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_vector_cb);
1362         mathutils_kxgameob_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_matrix_cb);
1363 }
1364
1365 #endif // USE_MATHUTILS
1366
1367 /* ------- python stuff ---------------------------------------------------*/
1368
1369 PyMethodDef KX_GameObject::Methods[] = {
1370         {"applyForce", (PyCFunction)    KX_GameObject::sPyApplyForce, METH_VARARGS},
1371         {"applyTorque", (PyCFunction)   KX_GameObject::sPyApplyTorque, METH_VARARGS},
1372         {"applyRotation", (PyCFunction) KX_GameObject::sPyApplyRotation, METH_VARARGS},
1373         {"applyMovement", (PyCFunction) KX_GameObject::sPyApplyMovement, METH_VARARGS},
1374         {"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS},
1375         {"setLinearVelocity", (PyCFunction) KX_GameObject::sPySetLinearVelocity, METH_VARARGS},
1376         {"getAngularVelocity", (PyCFunction) KX_GameObject::sPyGetAngularVelocity, METH_VARARGS},
1377         {"setAngularVelocity", (PyCFunction) KX_GameObject::sPySetAngularVelocity, METH_VARARGS},
1378         {"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS},
1379         {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS},
1380         {"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS},
1381         {"getAxisVect",(PyCFunction) KX_GameObject::sPyGetAxisVect, METH_O},
1382         {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics,METH_NOARGS},
1383         {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_NOARGS},
1384         {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_NOARGS},
1385         {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_NOARGS},
1386         {"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS},
1387         {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_O},
1388         {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_VARARGS},
1389         {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},
1390         {"setOcclusion",(PyCFunction) KX_GameObject::sPySetOcclusion, METH_VARARGS},
1391         {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_NOARGS},
1392         {"getChildren", (PyCFunction)KX_GameObject::sPyGetChildren,METH_NOARGS},
1393         {"getChildrenRecursive", (PyCFunction)KX_GameObject::sPyGetChildrenRecursive,METH_NOARGS},
1394         {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS},
1395         {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS},
1396         {"replaceMesh",(PyCFunction) KX_GameObject::sPyReplaceMesh, METH_O},
1397         {"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS},
1398         
1399         KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
1400         KX_PYMETHODTABLE(KX_GameObject, rayCast),
1401         KX_PYMETHODTABLE_O(KX_GameObject, getDistanceTo),
1402         KX_PYMETHODTABLE_O(KX_GameObject, getVectTo),
1403         KX_PYMETHODTABLE(KX_GameObject, sendMessage),
1404         
1405         // dict style access for props
1406         {"has_key",(PyCFunction) KX_GameObject::sPyhas_key, METH_O},
1407         {"get",(PyCFunction) KX_GameObject::sPyget, METH_VARARGS},
1408         
1409         // deprecated
1410         {"getPosition", (PyCFunction) KX_GameObject::sPyGetPosition, METH_NOARGS},
1411         {"setPosition", (PyCFunction) KX_GameObject::sPySetPosition, METH_O},
1412         {"setWorldPosition", (PyCFunction) KX_GameObject::sPySetWorldPosition, METH_O},
1413         {"getOrientation", (PyCFunction) KX_GameObject::sPyGetOrientation, METH_NOARGS},
1414         {"setOrientation", (PyCFunction) KX_GameObject::sPySetOrientation, METH_O},
1415         {"getState",(PyCFunction) KX_GameObject::sPyGetState, METH_NOARGS},
1416         {"setState",(PyCFunction) KX_GameObject::sPySetState, METH_O},
1417         {"getParent", (PyCFunction)KX_GameObject::sPyGetParent,METH_NOARGS},
1418         {"getVisible",(PyCFunction) KX_GameObject::sPyGetVisible, METH_NOARGS},
1419         {"getMass", (PyCFunction) KX_GameObject::sPyGetMass, METH_NOARGS},
1420         {"getMesh", (PyCFunction)KX_GameObject::sPyGetMesh,METH_VARARGS},
1421         {NULL,NULL} //Sentinel
1422 };
1423
1424 PyAttributeDef KX_GameObject::Attributes[] = {
1425         KX_PYATTRIBUTE_RO_FUNCTION("name",              KX_GameObject, pyattr_get_name),
1426         KX_PYATTRIBUTE_RO_FUNCTION("parent",    KX_GameObject, pyattr_get_parent),
1427         KX_PYATTRIBUTE_RW_FUNCTION("mass",              KX_GameObject, pyattr_get_mass,         pyattr_set_mass),
1428         KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMin",            KX_GameObject, pyattr_get_lin_vel_min, pyattr_set_lin_vel_min),
1429         KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMax",            KX_GameObject, pyattr_get_lin_vel_max, pyattr_set_lin_vel_max),
1430         KX_PYATTRIBUTE_RW_FUNCTION("visible",   KX_GameObject, pyattr_get_visible,      pyattr_set_visible),
1431         KX_PYATTRIBUTE_BOOL_RW    ("occlusion", KX_GameObject, m_bOccluder),
1432         KX_PYATTRIBUTE_RW_FUNCTION("position",  KX_GameObject, pyattr_get_worldPosition,        pyattr_set_localPosition),
1433         KX_PYATTRIBUTE_RO_FUNCTION("localInertia",      KX_GameObject, pyattr_get_localInertia),
1434         KX_PYATTRIBUTE_RW_FUNCTION("orientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_localOrientation),
1435         KX_PYATTRIBUTE_RW_FUNCTION("scaling",   KX_GameObject, pyattr_get_worldScaling, pyattr_set_localScaling),
1436         KX_PYATTRIBUTE_RW_FUNCTION("timeOffset",KX_GameObject, pyattr_get_timeOffset,pyattr_set_timeOffset),
1437         KX_PYATTRIBUTE_RW_FUNCTION("state",             KX_GameObject, pyattr_get_state,        pyattr_set_state),
1438         KX_PYATTRIBUTE_RO_FUNCTION("meshes",    KX_GameObject, pyattr_get_meshes),
1439         KX_PYATTRIBUTE_RW_FUNCTION("localOrientation",KX_GameObject,pyattr_get_localOrientation,pyattr_set_localOrientation),
1440         KX_PYATTRIBUTE_RW_FUNCTION("worldOrientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_worldOrientation),
1441         KX_PYATTRIBUTE_RW_FUNCTION("localPosition",     KX_GameObject, pyattr_get_localPosition,        pyattr_set_localPosition),
1442         KX_PYATTRIBUTE_RW_FUNCTION("worldPosition",     KX_GameObject, pyattr_get_worldPosition,    pyattr_set_worldPosition),
1443         KX_PYATTRIBUTE_RW_FUNCTION("localScale",        KX_GameObject, pyattr_get_localScaling, pyattr_set_localScaling),
1444         KX_PYATTRIBUTE_RO_FUNCTION("worldScale",        KX_GameObject, pyattr_get_worldScaling),
1445         KX_PYATTRIBUTE_RO_FUNCTION("children",  KX_GameObject, pyattr_get_children),
1446         KX_PYATTRIBUTE_RO_FUNCTION("childrenRecursive", KX_GameObject, pyattr_get_children_recursive),
1447         KX_PYATTRIBUTE_RO_FUNCTION("attrDict",  KX_GameObject, pyattr_get_attrDict),
1448         
1449         /* Experemental, dont rely on these yet */
1450         KX_PYATTRIBUTE_RO_FUNCTION("sensors",           KX_GameObject, pyattr_get_sensors),
1451         KX_PYATTRIBUTE_RO_FUNCTION("controllers",       KX_GameObject, pyattr_get_controllers),
1452         KX_PYATTRIBUTE_RO_FUNCTION("actuators",         KX_GameObject, pyattr_get_actuators),
1453         {NULL} //Sentinel
1454 };
1455
1456
1457 /*
1458 bool KX_GameObject::ConvertPythonVectorArgs(PyObject* args,
1459                                                                                         MT_Vector3& pos,
1460                                                                                         MT_Vector3& pos2)
1461 {
1462         PyObject* pylist;
1463         PyObject* pylist2;
1464         bool error = (PyArg_ParseTuple(args,"OO",&pylist,&pylist2)) != 0;
1465
1466         pos = ConvertPythonPylist(pylist);
1467         pos2 = ConvertPythonPylist(pylist2);
1468                 
1469         return error;
1470 }
1471 */
1472
1473 PyObject* KX_GameObject::PyReplaceMesh(PyObject* value)
1474 {
1475         KX_Scene *scene = KX_GetActiveScene();
1476         RAS_MeshObject* new_mesh;
1477         
1478         if (!ConvertPythonToMesh(value, &new_mesh, false, "gameOb.replaceMesh(value): KX_GameObject"))
1479                 return NULL;
1480         
1481         scene->ReplaceMesh(this, new_mesh);
1482         Py_RETURN_NONE;
1483 }
1484
1485 PyObject* KX_GameObject::PyEndObject()
1486 {
1487         KX_Scene *scene = KX_GetActiveScene();
1488         
1489         scene->DelayedRemoveObject(this);
1490         
1491         Py_RETURN_NONE;
1492
1493 }
1494
1495
1496 PyObject* KX_GameObject::PyGetPosition()
1497 {
1498         ShowDeprecationWarning("getPosition()", "the position property");
1499         return PyObjectFrom(NodeGetWorldPosition());
1500 }
1501
1502 static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
1503 {
1504         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1505         const char *attr_str= PyString_AsString(item);
1506         CValue* resultattr;
1507         PyObject* pyconvert;
1508         
1509         if (self==NULL) {
1510                 PyErr_SetString(PyExc_SystemError, "val = gameOb[key]: KX_GameObject, "BGE_PROXY_ERROR_MSG);
1511                 return NULL;
1512         }
1513         
1514         /* first see if the attributes a string and try get the cvalue attribute */
1515         if(attr_str && (resultattr=self->GetProperty(attr_str))) {
1516                 pyconvert = resultattr->ConvertValueToPython();                 
1517                 return pyconvert ? pyconvert:resultattr->GetProxy();
1518         }
1519         /* no CValue attribute, try get the python only m_attr_dict attribute */
1520         else if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
1521                 
1522                 if (attr_str)
1523                         PyErr_Clear();
1524                 Py_INCREF(pyconvert);
1525                 return pyconvert;
1526         }
1527         else {
1528                 if(attr_str)    PyErr_Format(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key \"%s\" does not exist", attr_str);
1529                 else                    PyErr_SetString(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key does not exist");
1530                 return NULL;
1531         }
1532                 
1533 }
1534
1535
1536 static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
1537 {
1538         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1539         const char *attr_str= PyString_AsString(key);
1540         if(attr_str==NULL)
1541                 PyErr_Clear();
1542         
1543         if (self==NULL) {
1544                 PyErr_SetString(PyExc_SystemError, "gameOb[key] = value: KX_GameObject, "BGE_PROXY_ERROR_MSG);
1545                 return -1;
1546         }
1547         
1548         if (val==NULL) { /* del ob["key"] */
1549                 int del= 0;
1550                 
1551                 /* try remove both just incase */
1552                 if(attr_str)
1553                         del |= (self->RemoveProperty(attr_str)==true) ? 1:0;
1554                 
1555                 if(self->m_attr_dict)
1556                         del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
1557                 
1558                 if (del==0) {
1559                         if(attr_str)    PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" could not be set", attr_str);
1560                         else                    PyErr_SetString(PyExc_KeyError, "del gameOb[key]: KX_GameObject, key could not be deleted");
1561                         return -1;
1562                 }
1563                 else if (self->m_attr_dict) {
1564                         PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
1565                 }
1566         }
1567         else { /* ob["key"] = value */
1568                 int set= 0;
1569                 
1570                 /* as CValue */
1571                 if(attr_str && BGE_PROXY_CHECK_TYPE(val)==0) /* dont allow GameObjects for eg to be assigned to CValue props */
1572                 {
1573                         CValue* vallie = self->ConvertPythonToValue(val, ""); /* error unused */
1574                         
1575                         if(vallie)
1576                         {
1577                                 CValue* oldprop = self->GetProperty(attr_str);
1578                                 
1579                                 if (oldprop)
1580                                         oldprop->SetValue(vallie);
1581                                 else
1582                                         self->SetProperty(attr_str, vallie);
1583                                 
1584                                 vallie->Release();
1585                                 set= 1;
1586                                 
1587                                 /* try remove dict value to avoid double ups */
1588                                 if (self->m_attr_dict){
1589                                         if (PyDict_DelItem(self->m_attr_dict, key) != 0)
1590                                                 PyErr_Clear();
1591                                 }
1592                         }
1593                         else {
1594                                 PyErr_Clear();
1595                         }
1596                 }
1597                 
1598                 if(set==0)
1599                 {
1600                         if (self->m_attr_dict==NULL) /* lazy init */
1601                                 self->m_attr_dict= PyDict_New();
1602                         
1603                         
1604                         if(PyDict_SetItem(self->m_attr_dict, key, val)==0)
1605                         {
1606                                 if(attr_str)
1607                                         self->RemoveProperty(attr_str); /* overwrite the CValue if it exists */
1608                                 set= 1;
1609                         }
1610                         else {
1611                                 if(attr_str)    PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" not be added to internal dictionary", attr_str);
1612                                 else                    PyErr_SetString(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key not be added to internal dictionary");
1613                         }
1614                 }
1615                 
1616                 if(set==0)
1617                         return -1; /* pythons error value */
1618                 
1619         }
1620         
1621         return 0; /* success */
1622 }
1623
1624 static int Seq_Contains(PyObject *self_v, PyObject *value)
1625 {
1626         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1627         
1628         if (self==NULL) {
1629                 PyErr_SetString(PyExc_SystemError, "val in gameOb: KX_GameObject, "BGE_PROXY_ERROR_MSG);
1630                 return -1;
1631         }
1632         
1633         if(PyString_Check(value) && self->GetProperty(PyString_AsString(value)))
1634                 return 1;
1635         
1636         if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
1637                 return 1;
1638         
1639         return 0;
1640 }
1641
1642
1643 PyMappingMethods KX_GameObject::Mapping = {
1644         (lenfunc)NULL                                   ,                       /*inquiry mp_length */
1645         (binaryfunc)Map_GetItem,                /*binaryfunc mp_subscript */
1646         (objobjargproc)Map_SetItem,     /*objobjargproc mp_ass_subscript */
1647 };
1648
1649 PySequenceMethods KX_GameObject::Sequence = {
1650         NULL,           /* Cant set the len otherwise it can evaluate as false */
1651         NULL,           /* sq_concat */
1652         NULL,           /* sq_repeat */
1653         NULL,           /* sq_item */
1654         NULL,           /* sq_slice */
1655         NULL,           /* sq_ass_item */
1656         NULL,           /* sq_ass_slice */
1657         (objobjproc)Seq_Contains,       /* sq_contains */
1658 };
1659
1660 PyTypeObject KX_GameObject::Type = {
1661 #if (PY_VERSION_HEX >= 0x02060000)
1662         PyVarObject_HEAD_INIT(NULL, 0)
1663 #else
1664         /* python 2.5 and below */
1665         PyObject_HEAD_INIT( NULL )  /* required py macro */
1666         0,                          /* ob_size */
1667 #endif
1668                 "KX_GameObject",
1669                 sizeof(PyObjectPlus_Proxy),
1670                 0,
1671                 py_base_dealloc,
1672                 0,
1673                 0,
1674                 0,
1675                 0,
1676                 py_base_repr,
1677                 0,
1678                 &Sequence,
1679                 &Mapping,
1680                 0,0,0,
1681                 py_base_getattro,
1682                 py_base_setattro,
1683                 0,
1684                 Py_TPFLAGS_DEFAULT,
1685                 0,0,0,0,0,0,0,
1686                 Methods
1687 };
1688
1689
1690
1691
1692
1693
1694 PyParentObject KX_GameObject::Parents[] = {
1695         &KX_GameObject::Type,
1696                 &SCA_IObject::Type,
1697                 &CValue::Type,
1698                 NULL
1699 };
1700
1701 PyObject* KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1702 {
1703         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1704         return PyString_FromString(self->GetName().ReadPtr());
1705 }
1706
1707 PyObject* KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1708 {
1709         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1710         KX_GameObject* parent = self->GetParent();
1711         if (parent) {
1712                 parent->Release(); /* self->GetParent() AddRef's */
1713                 return parent->GetProxy();
1714         }
1715         Py_RETURN_NONE;
1716 }
1717
1718 PyObject* KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1719 {
1720         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1721         KX_IPhysicsController *spc = self->GetPhysicsController();
1722         return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0f);
1723 }
1724
1725 int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1726 {
1727         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1728         KX_IPhysicsController *spc = self->GetPhysicsController();
1729         MT_Scalar val = PyFloat_AsDouble(value);
1730         if (val < 0.0f) { /* also accounts for non float */
1731                 PyErr_SetString(PyExc_AttributeError, "gameOb.mass = float: KX_GameObject, expected a float zero or above");
1732                 return PY_SET_ATTR_FAIL;
1733         }
1734
1735         if (spc)
1736                 spc->SetMass(val);
1737
1738         return PY_SET_ATTR_SUCCESS;
1739 }
1740
1741 PyObject* KX_GameObject::pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1742 {
1743         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1744         KX_IPhysicsController *spc = self->GetPhysicsController();
1745         return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
1746 }
1747
1748 int KX_GameObject::pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1749 {
1750         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1751         KX_IPhysicsController *spc = self->GetPhysicsController();
1752         MT_Scalar val = PyFloat_AsDouble(value);
1753         if (val < 0.0f) { /* also accounts for non float */
1754                 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMin = float: KX_GameObject, expected a float zero or above");
1755                 return PY_SET_ATTR_FAIL;
1756         }
1757
1758         if (spc)
1759                 spc->SetLinVelocityMin(val);
1760
1761         return PY_SET_ATTR_SUCCESS;
1762 }
1763
1764 PyObject* KX_GameObject::pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1765 {
1766         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1767         KX_IPhysicsController *spc = self->GetPhysicsController();
1768         return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
1769 }
1770
1771 int KX_GameObject::pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1772 {
1773         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1774         KX_IPhysicsController *spc = self->GetPhysicsController();
1775         MT_Scalar val = PyFloat_AsDouble(value);
1776         if (val < 0.0f) { /* also accounts for non float */
1777                 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMax = float: KX_GameObject, expected a float zero or above");
1778                 return PY_SET_ATTR_FAIL;
1779         }
1780
1781         if (spc)
1782                 spc->SetLinVelocityMax(val);
1783
1784         return PY_SET_ATTR_SUCCESS;
1785 }
1786
1787
1788 PyObject* KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1789 {
1790         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1791         return PyBool_FromLong(self->GetVisible());
1792 }
1793
1794 int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1795 {
1796         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1797         int param = PyObject_IsTrue( value );
1798         if (param == -1) {
1799                 PyErr_SetString(PyExc_AttributeError, "gameOb.visible = bool: KX_GameObject, expected True or False");
1800                 return PY_SET_ATTR_FAIL;
1801         }
1802
1803         self->SetVisible(param, false);
1804         self->UpdateBuckets(false);
1805         return PY_SET_ATTR_SUCCESS;
1806 }
1807
1808 PyObject* KX_GameObject::pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1809 {
1810         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1811 #ifdef USE_MATHUTILS
1812         return newVectorObject_cb((PyObject *)self_v, 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_GLOBAL);
1813 #else
1814         return PyObjectFrom(self->NodeGetWorldPosition());
1815 #endif
1816 }
1817
1818 int KX_GameObject::pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1819 {
1820         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1821         MT_Point3 pos;
1822         if (!PyVecTo(value, pos))
1823                 return PY_SET_ATTR_FAIL;
1824         
1825         self->NodeSetWorldPosition(pos);
1826         self->NodeUpdateGS(0.f);
1827         return PY_SET_ATTR_SUCCESS;
1828 }
1829
1830 PyObject* KX_GameObject::pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1831 {
1832         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1833 #ifdef USE_MATHUTILS    
1834         return newVectorObject_cb((PyObject *)self_v, 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_LOCAL);
1835 #else   
1836         return PyObjectFrom(self->NodeGetLocalPosition());
1837 #endif
1838 }
1839
1840 int KX_GameObject::pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1841 {
1842         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1843         MT_Point3 pos;
1844         if (!PyVecTo(value, pos))
1845                 return PY_SET_ATTR_FAIL;
1846         
1847         self->NodeSetLocalPosition(pos);
1848         self->NodeUpdateGS(0.f);
1849         return PY_SET_ATTR_SUCCESS;
1850 }
1851
1852 PyObject* KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1853 {
1854         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1855 #ifdef USE_MATHUTILS
1856         return newVectorObject_cb((PyObject *)self_v, 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_INERTIA_LOCAL);
1857 #else
1858         if (self->GetPhysicsController())
1859                 return PyObjectFrom(self->GetPhysicsController()->GetLocalInertia());
1860         return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
1861 #endif
1862 }
1863
1864 PyObject* KX_GameObject::pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1865 {
1866 #ifdef USE_MATHUTILS
1867         return newMatrixObject_cb((PyObject *)self_v, 3, 3, mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_GLOBAL);
1868 #else
1869         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1870         return PyObjectFrom(self->NodeGetWorldOrientation());
1871 #endif
1872 }
1873
1874 int KX_GameObject::pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1875 {
1876         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1877         
1878         /* if value is not a sequence PyOrientationTo makes an error */
1879         MT_Matrix3x3 rot;
1880         if (!PyOrientationTo(value, rot, "gameOb.worldOrientation = sequence: KX_GameObject, "))
1881                 return PY_SET_ATTR_FAIL;
1882
1883         if (self->GetSGNode() && self->GetSGNode()->GetSGParent()) {
1884                 self->NodeSetLocalOrientation(self->GetSGNode()->GetSGParent()->GetWorldOrientation().inverse()*rot);
1885         }
1886         else {
1887                 self->NodeSetLocalOrientation(rot);
1888         }
1889         
1890         self->NodeUpdateGS(0.f);
1891         return PY_SET_ATTR_SUCCESS;
1892 }
1893
1894 PyObject* KX_GameObject::pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1895 {
1896 #ifdef USE_MATHUTILS
1897         return newMatrixObject_cb((PyObject *)self_v, 3, 3, mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_LOCAL);
1898 #else
1899         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1900         return PyObjectFrom(self->NodeGetLocalOrientation());
1901 #endif
1902 }
1903
1904 int KX_GameObject::pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1905 {
1906         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1907         
1908         /* if value is not a sequence PyOrientationTo makes an error */
1909         MT_Matrix3x3 rot;
1910         if (!PyOrientationTo(value, rot, "gameOb.localOrientation = sequence: KX_GameObject, "))
1911                 return PY_SET_ATTR_FAIL;
1912
1913         self->NodeSetLocalOrientation(rot);
1914         self->NodeUpdateGS(0.f);
1915         return PY_SET_ATTR_SUCCESS;
1916 }
1917
1918 PyObject* KX_GameObject::pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1919 {
1920         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1921 #ifdef USE_MATHUTILS
1922         return newVectorObject_cb((PyObject *)self_v, 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_GLOBAL);
1923 #else
1924         return PyObjectFrom(self->NodeGetWorldScaling());
1925 #endif
1926 }
1927
1928 PyObject* KX_GameObject::pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1929 {
1930         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1931 #ifdef USE_MATHUTILS
1932         return newVectorObject_cb((PyObject *)self_v, 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_LOCAL);
1933 #else
1934         return PyObjectFrom(self->NodeGetLocalScale());
1935 #endif
1936 }
1937
1938 int KX_GameObject::pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1939 {
1940         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1941         MT_Vector3 scale;
1942         if (!PyVecTo(value, scale))
1943                 return PY_SET_ATTR_FAIL;
1944
1945         self->NodeSetLocalScale(scale);
1946         self->NodeUpdateGS(0.f);
1947         return PY_SET_ATTR_SUCCESS;
1948 }
1949
1950 PyObject* KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1951 {
1952         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1953         SG_Node* sg_parent;
1954         if (self->GetSGNode() && (sg_parent = self->GetSGNode()->GetSGParent()) != NULL && sg_parent->IsSlowParent()) {
1955                 return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->GetTimeOffset());
1956         } else {
1957                 return PyFloat_FromDouble(0.0);
1958         }
1959 }
1960
1961 int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1962 {
1963         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1964         if (self->GetSGNode()) {
1965                 MT_Scalar val = PyFloat_AsDouble(value);
1966                 SG_Node* sg_parent= self->GetSGNode()->GetSGParent();
1967                 if (val < 0.0f) { /* also accounts for non float */
1968                         PyErr_SetString(PyExc_AttributeError, "gameOb.timeOffset = float: KX_GameObject, expected a float zero or above");
1969                         return PY_SET_ATTR_FAIL;
1970                 }
1971                 if (sg_parent && sg_parent->IsSlowParent())
1972                         static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->SetTimeOffset(val);
1973         }
1974         return PY_SET_ATTR_SUCCESS;
1975 }
1976
1977 PyObject* KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1978 {
1979         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1980         int state = 0;
1981         state |= self->GetState();
1982         return PyInt_FromLong(state);
1983 }
1984
1985 int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1986 {
1987         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1988         int state_i = PyInt_AsLong(value);
1989         unsigned int state = 0;
1990         
1991         if (state_i == -1 && PyErr_Occurred()) {
1992                 PyErr_SetString(PyExc_TypeError, "gameOb.state = int: KX_GameObject, expected an int bit field");
1993                 return PY_SET_ATTR_FAIL;
1994         }
1995         
1996         state |= state_i;
1997         if ((state & ((1<<30)-1)) == 0) {
1998                 PyErr_SetString(PyExc_AttributeError, "gameOb.state = int: KX_GameObject, state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
1999                 return PY_SET_ATTR_FAIL;
2000         }
2001         self->SetState(state);
2002         return PY_SET_ATTR_SUCCESS;
2003 }
2004
2005 PyObject* KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2006 {
2007         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2008         PyObject *meshes= PyList_New(self->m_meshes.size());
2009         int i;
2010         
2011         for(i=0; i < (int)self->m_meshes.size(); i++)
2012         {
2013                 KX_MeshProxy* meshproxy = new KX_MeshProxy(self->m_meshes[i]);
2014                 PyList_SET_ITEM(meshes, i, meshproxy->NewProxy(true));
2015         }
2016         
2017         return meshes;
2018 }
2019
2020 /* experemental! */
2021 PyObject* KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2022 {
2023         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_SENSORS);
2024 }
2025
2026 PyObject* KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2027 {
2028         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_CONTROLLERS);
2029 }
2030
2031 PyObject* KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2032 {
2033         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_ACTUATORS);
2034 }
2035
2036 PyObject* KX_GameObject::pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2037 {
2038         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2039         return self->GetChildren()->NewProxy(true);
2040 }
2041
2042 PyObject* KX_GameObject::pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2043 {
2044         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2045         return self->GetChildrenRecursive()->NewProxy(true);
2046 }
2047
2048 PyObject* KX_GameObject::pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2049 {
2050         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2051         
2052         if(self->m_attr_dict==NULL)
2053                 self->m_attr_dict= PyDict_New();
2054         
2055         Py_INCREF(self->m_attr_dict);
2056         return self->m_attr_dict;
2057 }
2058
2059 /* We need these because the macros have a return in them */
2060 PyObject* KX_GameObject::py_getattro__internal(PyObject *attr)
2061 {
2062         py_getattro_up(SCA_IObject);
2063 }
2064
2065 int KX_GameObject::py_setattro__internal(PyObject *attr, PyObject *value)       // py_setattro method
2066 {
2067         py_setattro_up(SCA_IObject);
2068 }
2069
2070
2071 PyObject* KX_GameObject::py_getattro(PyObject *attr)
2072 {
2073         PyObject *object= py_getattro__internal(attr);
2074         
2075         if (object==NULL && m_attr_dict)
2076         {
2077                 /* backup the exception incase the attr doesnt exist in the dict either */
2078                 PyObject *err_type, *err_value, *err_tb;
2079                 PyErr_Fetch(&err_type, &err_value, &err_tb);
2080                 
2081                 object= PyDict_GetItem(m_attr_dict, attr);
2082                 if (object) {
2083                         Py_INCREF(object);
2084                         
2085                         PyErr_Clear();
2086                         Py_XDECREF( err_type );
2087                         Py_XDECREF( err_value );
2088                         Py_XDECREF( err_tb );
2089                 }
2090                 else {
2091                         PyErr_Restore(err_type, err_value, err_tb); /* use the error from the parent function */
2092                 }
2093         }
2094         return object;
2095 }
2096
2097 PyObject* KX_GameObject::py_getattro_dict() {
2098         //py_getattro_dict_up(SCA_IObject);
2099         PyObject *dict= py_getattr_dict(SCA_IObject::py_getattro_dict(), Type.tp_dict);
2100         if(dict==NULL)
2101                 return NULL;
2102         
2103         /* normally just return this but KX_GameObject has some more items */
2104
2105         
2106         /* Not super fast getting as a list then making into dict keys but its only for dir() */
2107         PyObject *list= ConvertKeysToPython();
2108         if(list)
2109         {
2110                 int i;
2111                 for(i=0; i<PyList_Size(list); i++)
2112                         PyDict_SetItem(dict, PyList_GET_ITEM(list, i), Py_None);
2113         }
2114         else
2115                 PyErr_Clear();
2116         
2117         Py_DECREF(list);
2118         
2119         /* Add m_attr_dict if we have it */
2120         if(m_attr_dict)
2121                 PyDict_Update(dict, m_attr_dict);
2122         
2123         return dict;
2124 }
2125
2126 int KX_GameObject::py_setattro(PyObject *attr, PyObject *value) // py_setattro method
2127 {
2128         int ret= py_setattro__internal(attr, value);
2129         
2130         if (ret==PY_SET_ATTR_SUCCESS) {
2131                 /* remove attribute in our own dict to avoid double ups */
2132                 /* NOTE: Annoying that we also do this for setting builtin attributes like mass and visibility :/ */
2133                 if (m_attr_dict) {
2134                         if (PyDict_DelItem(m_attr_dict, attr) != 0)
2135                                 PyErr_Clear();
2136                 }
2137         }
2138         
2139         if (ret==PY_SET_ATTR_COERCE_FAIL) {
2140                 /* CValue attribute exists, remove CValue and add PyDict value */
2141                 RemoveProperty(PyString_AsString(attr));
2142                 ret= PY_SET_ATTR_MISSING;
2143         }
2144         
2145         if (ret==PY_SET_ATTR_MISSING) {
2146                 /* Lazy initialization */
2147                 if (m_attr_dict==NULL)
2148                         m_attr_dict = PyDict_New();
2149                 
2150                 if (PyDict_SetItem(m_attr_dict, attr, value)==0) {
2151                         PyErr_Clear();
2152                         ret= PY_SET_ATTR_SUCCESS;
2153                 }
2154                 else {
2155                         PyErr_Format(PyExc_AttributeError, "gameOb.myAttr = value: KX_GameObject, failed assigning value to internal dictionary");
2156                         ret= PY_SET_ATTR_FAIL;
2157                 }
2158         }
2159         
2160         return ret;     
2161 }
2162
2163
2164 int     KX_GameObject::py_delattro(PyObject *attr)
2165 {
2166         ShowDeprecationWarning("del ob.attr", "del ob['attr'] for user defined properties");
2167         
2168         char *attr_str= PyString_AsString(attr); 
2169         
2170         if (RemoveProperty(attr_str)) // XXX - should call CValues instead but its only 2 lines here
2171                 return PY_SET_ATTR_SUCCESS;
2172         
2173         if (m_attr_dict && (PyDict_DelItem(m_attr_dict, attr) == 0))
2174                 return PY_SET_ATTR_SUCCESS;
2175         
2176         PyErr_Format(PyExc_AttributeError, "del gameOb.myAttr: KX_GameObject, attribute \"%s\" dosnt exist", attr_str);
2177         return PY_SET_ATTR_MISSING;
2178 }
2179
2180
2181 PyObject* KX_GameObject::PyApplyForce(PyObject* args)
2182 {
2183         int local = 0;
2184         PyObject* pyvect;
2185
2186         if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) {
2187                 MT_Vector3 force;
2188                 if (PyVecTo(pyvect, force)) {
2189                         ApplyForce(force, (local!=0));
2190                         Py_RETURN_NONE;
2191                 }
2192         }
2193         return NULL;
2194 }
2195
2196 PyObject* KX_GameObject::PyApplyTorque(PyObject* args)
2197 {
2198         int local = 0;
2199         PyObject* pyvect;
2200
2201         if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) {
2202                 MT_Vector3 torque;
2203                 if (PyVecTo(pyvect, torque)) {
2204                         ApplyTorque(torque, (local!=0));
2205                         Py_RETURN_NONE;
2206                 }
2207         }
2208         return NULL;
2209 }
2210
2211 PyObject* KX_GameObject::PyApplyRotation(PyObject* args)
2212 {
2213         int local = 0;
2214         PyObject* pyvect;
2215
2216         if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) {
2217                 MT_Vector3 rotation;
2218                 if (PyVecTo(pyvect, rotation)) {
2219                         ApplyRotation(rotation, (local!=0));
2220                         Py_RETURN_NONE;
2221                 }
2222         }
2223         return NULL;
2224 }
2225
2226 PyObject* KX_GameObject::PyApplyMovement(PyObject* args)
2227 {
2228         int local = 0;
2229         PyObject* pyvect;
2230
2231         if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) {
2232                 MT_Vector3 movement;
2233                 if (PyVecTo(pyvect, movement)) {
2234                         ApplyMovement(movement, (local!=0));
2235                         Py_RETURN_NONE;
2236                 }
2237         }
2238         return NULL;
2239 }
2240
2241 PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* args)
2242 {
2243         // only can get the velocity if we have a physics object connected to us...
2244         int local = 0;
2245         if (PyArg_ParseTuple(args,"|i:getLinearVelocity",&local))
2246         {
2247                 return PyObjectFrom(GetLinearVelocity((local!=0)));
2248         }
2249         else
2250         {
2251                 return NULL;
2252         }
2253 }
2254
2255 PyObject* KX_GameObject::PySetLinearVelocity(PyObject* args)
2256 {
2257         int local = 0;
2258         PyObject* pyvect;
2259         
2260         if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) {
2261                 MT_Vector3 velocity;
2262                 if (PyVecTo(pyvect, velocity)) {
2263                         setLinearVelocity(velocity, (local!=0));
2264                         Py_RETURN_NONE;
2265                 }
2266         }
2267         return NULL;
2268 }
2269
2270 PyObject* KX_GameObject::PyGetAngularVelocity(PyObject* args)
2271 {
2272         // only can get the velocity if we have a physics object connected to us...
2273         int local = 0;
2274         if (PyArg_ParseTuple(args,"|i:getAngularVelocity",&local))
2275         {
2276                 return PyObjectFrom(GetAngularVelocity((local!=0)));
2277         }
2278         else
2279         {
2280                 return NULL;
2281         }
2282 }
2283
2284 PyObject* KX_GameObject::PySetAngularVelocity(PyObject* args)
2285 {
2286         int local = 0;
2287         PyObject* pyvect;
2288         
2289         if (PyArg_ParseTuple(args,"O|i:setAngularVelocity",&pyvect,&local)) {
2290                 MT_Vector3 velocity;
2291                 if (PyVecTo(pyvect, velocity)) {
2292                         setAngularVelocity(velocity, (local!=0));
2293                         Py_RETURN_NONE;
2294                 }
2295         }
2296         return NULL;
2297 }
2298
2299 PyObject* KX_GameObject::PySetVisible(PyObject* args)
2300 {
2301         int visible, recursive = 0;
2302         if (!PyArg_ParseTuple(args,"i|i:setVisible",&visible, &recursive))
2303                 return NULL;
2304         
2305         SetVisible(visible ? true:false, recursive ? true:false);
2306         UpdateBuckets(recursive ? true:false);
2307         Py_RETURN_NONE;
2308         
2309 }
2310
2311 PyObject* KX_GameObject::PySetOcclusion(PyObject* args)
2312 {
2313         int occlusion, recursive = 0;
2314         if (!PyArg_ParseTuple(args,"i|i:setOcclusion",&occlusion, &recursive))
2315                 return NULL;
2316         
2317         SetOccluder(occlusion ? true:false, recursive ? true:false);
2318         Py_RETURN_NONE;
2319 }
2320
2321 PyObject* KX_GameObject::PyGetVisible()
2322 {
2323         ShowDeprecationWarning("getVisible()", "the visible property");
2324         return PyInt_FromLong(m_bVisible);      
2325 }
2326
2327 PyObject* KX_GameObject::PyGetState()
2328 {
2329         ShowDeprecationWarning("getState()", "the state property");
2330         int state = 0;
2331         state |= GetState();
2332         return PyInt_FromLong(state);
2333 }
2334
2335 PyObject* KX_GameObject::PySetState(PyObject* value)
2336 {
2337         ShowDeprecationWarning("setState()", "the state property");
2338         int state_i = PyInt_AsLong(value);
2339         unsigned int state = 0;
2340         
2341         if (state_i == -1 && PyErr_Occurred()) {
2342                 PyErr_SetString(PyExc_TypeError, "expected an int bit field");
2343                 return NULL;
2344         }
2345         
2346         state |= state_i;
2347         if ((state & ((1<<30)-1)) == 0) {
2348                 PyErr_SetString(PyExc_AttributeError, "The state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
2349                 return NULL;
2350         }
2351         SetState(state);
2352         
2353         Py_RETURN_NONE;
2354 }
2355
2356 PyObject* KX_GameObject::PyGetVelocity(PyObject* args)
2357 {
2358         // only can get the velocity if we have a physics object connected to us...
2359         MT_Point3 point(0.0,0.0,0.0);
2360         PyObject* pypos = NULL;
2361         
2362         if (!PyArg_ParseTuple(args, "|O:getVelocity", &pypos) || (pypos && !PyVecTo(pypos, point)))
2363                 return NULL;
2364         
2365         if (m_pPhysicsController1)
2366         {
2367                 return PyObjectFrom(m_pPhysicsController1->GetVelocity(point));
2368         }
2369         else {
2370                 return PyObjectFrom(MT_Vector3(0.0,0.0,0.0));
2371         }
2372 }
2373
2374
2375
2376 PyObject* KX_GameObject::PyGetMass()
2377 {
2378         ShowDeprecationWarning("getMass()", "the mass property");
2379         return PyFloat_FromDouble((GetPhysicsController() != NULL) ? GetPhysicsController()->GetMass() : 0.0f);
2380 }
2381
2382 PyObject* KX_GameObject::PyGetReactionForce()
2383 {
2384         // only can get the velocity if we have a physics object connected to us...
2385         
2386         // XXX - Currently not working with bullet intergration, see KX_BulletPhysicsController.cpp's getReactionForce
2387         /*
2388         if (GetPhysicsController())
2389                 return PyObjectFrom(GetPhysicsController()->getReactionForce());
2390         return PyObjectFrom(dummy_point);
2391         */
2392         
2393         return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
2394         
2395 }
2396
2397
2398
2399 PyObject* KX_GameObject::PyEnableRigidBody()
2400 {
2401         if(GetPhysicsController())
2402                 GetPhysicsController()->setRigidBody(true);
2403
2404         Py_RETURN_NONE;
2405 }
2406
2407
2408
2409 PyObject* KX_GameObject::PyDisableRigidBody()
2410 {
2411         if(GetPhysicsController())
2412                 GetPhysicsController()->setRigidBody(false);
2413
2414         Py_RETURN_NONE;
2415 }
2416
2417
2418
2419 PyObject* KX_GameObject::PyGetParent()
2420 {
2421         ShowDeprecationWarning("getParent()", "the parent property");
2422         KX_GameObject* parent = this->GetParent();
2423         if (parent) {
2424                 parent->Release(); /* self->GetParent() AddRef's */
2425                 return parent->GetProxy();
2426         }
2427         Py_RETURN_NONE;
2428 }
2429
2430 PyObject* KX_GameObject::PySetParent(PyObject* args)
2431 {
2432         KX_Scene *scene = KX_GetActiveScene();
2433         PyObject* pyobj;
2434         KX_GameObject *obj;
2435         int addToCompound=1, ghost=1;
2436         
2437         if (!PyArg_ParseTuple(args,"O|ii:setParent", &pyobj, &addToCompound, &ghost)) {
2438                 return NULL; // Python sets a simple error
2439         }
2440         if (!ConvertPythonToGameObject(pyobj, &obj, true, "gameOb.setParent(obj): KX_GameObject"))
2441                 return NULL;
2442         if (obj)
2443                 this->SetParent(scene, obj, addToCompound, ghost);
2444         Py_RETURN_NONE;
2445 }
2446
2447 PyObject* KX_GameObject::PyRemoveParent()
2448 {
2449         KX_Scene *scene = KX_GetActiveScene();
2450         
2451         this->RemoveParent(scene);
2452         Py_RETURN_NONE;
2453 }
2454
2455 PyObject* KX_GameObject::PyGetChildren()
2456 {
2457         ShowDeprecationWarning("getChildren()", "the children property");
2458         
2459         return GetChildren()->NewProxy(true);
2460 }
2461
2462 PyObject* KX_GameObject::PyGetChildrenRecursive()
2463 {
2464         ShowDeprecationWarning("getChildrenRecursive()", "the childrenRecursive property");
2465         
2466         return GetChildrenRecursive()->NewProxy(true);
2467 }
2468
2469 PyObject* KX_GameObject::PyGetMesh(PyObject* args)
2470 {
2471         ShowDeprecationWarning("getMesh()", "the meshes property (now a list of meshes)");
2472         
2473         int mesh = 0;
2474
2475         if (!PyArg_ParseTuple(args, "|i:getMesh", &mesh))
2476                 return NULL; // python sets a simple error
2477         
2478         if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0)
2479         {
2480                 KX_MeshProxy* meshproxy = new KX_MeshProxy(m_meshes[mesh]);
2481                 return meshproxy->NewProxy(true); // XXX Todo Python own.
2482         }
2483         
2484         Py_RETURN_NONE;
2485 }
2486
2487
2488
2489
2490
2491 PyObject* KX_GameObject::PySetCollisionMargin(PyObject* value)
2492 {
2493         float collisionMargin = PyFloat_AsDouble(value);
2494         
2495         if (collisionMargin==-1 && PyErr_Occurred()) {
2496                 PyErr_SetString(PyExc_TypeError, "expected a float");
2497                 return NULL;
2498         }
2499         
2500         if (m_pPhysicsController1)
2501         {
2502                 m_pPhysicsController1->setMargin(collisionMargin);
2503                 Py_RETURN_NONE;
2504         }
2505         PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
2506         return NULL;
2507 }
2508
2509
2510
2511 PyObject* KX_GameObject::PyApplyImpulse(PyObject* args)
2512 {
2513         PyObject* pyattach;
2514         PyObject* pyimpulse;
2515         
2516         if (!m_pPhysicsController1)     {
2517                 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
2518                 return NULL;
2519         }
2520         
2521         if (PyArg_ParseTuple(args, "OO:applyImpulse", &pyattach, &pyimpulse))
2522         {
2523                 MT_Point3  attach;
2524                 MT_Vector3 impulse;
2525                 if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
2526                 {
2527                         m_pPhysicsController1->applyImpulse(attach, impulse);
2528                         Py_RETURN_NONE;
2529                 }
2530
2531         }
2532         
2533         return NULL;
2534 }
2535
2536
2537
2538 PyObject* KX_GameObject::PySuspendDynamics()
2539 {
2540         SuspendDynamics();
2541         Py_RETURN_NONE;
2542 }
2543
2544
2545
2546 PyObject* KX_GameObject::PyRestoreDynamics()
2547 {
2548         RestoreDynamics();
2549         Py_RETURN_NONE;
2550 }
2551
2552
2553
2554 PyObject* KX_GameObject::PyGetOrientation() //keywords
2555 {
2556         ShowDeprecationWarning("getOrientation()", "the orientation property");
2557         return PyObjectFrom(NodeGetWorldOrientation());
2558 }
2559
2560
2561
2562 PyObject* KX_GameObject::PySetOrientation(PyObject* value)
2563 {
2564         ShowDeprecationWarning("setOrientation()", "the orientation property");
2565         MT_Matrix3x3 rot;
2566         
2567         /* if value is not a sequence PyOrientationTo makes an error */
2568         if (!PyOrientationTo(value, rot, "gameOb.setOrientation(sequence): KX_GameObject, "))
2569                 return NULL;
2570
2571         NodeSetLocalOrientation(rot);
2572         NodeUpdateGS(0.f);
2573         Py_RETURN_NONE;
2574 }
2575
2576 PyObject* KX_GameObject::PyAlignAxisToVect(PyObject* args)
2577 {
2578         PyObject* pyvect;
2579         int axis = 2; //z axis is the default
2580         float fac = 1.0;
2581         
2582         if (PyArg_ParseTuple(args,"O|if:alignAxisToVect",&pyvect,&axis, &fac))
2583         {
2584                 MT_Vector3 vect;
2585                 if (PyVecTo(pyvect, vect))
2586                 {
2587                         if (fac<=0.0) Py_RETURN_NONE; // Nothing to do.
2588                         if (fac> 1.0) fac= 1.0;
2589                         
2590                         AlignAxisToVect(vect,axis,fac);
2591                         NodeUpdateGS(0.f);
2592                         Py_RETURN_NONE;
2593                 }
2594         }
2595         return NULL;
2596 }
2597
2598 PyObject* KX_GameObject::PyGetAxisVect(PyObject* value)
2599 {
2600         MT_Vector3 vect;
2601         if (PyVecTo(value, vect))
2602         {
2603                 return PyObjectFrom(NodeGetWorldOrientation() * vect);
2604         }
2605         return NULL;
2606 }
2607
2608 PyObject* KX_GameObject::PySetPosition(PyObject* value)
2609 {
2610         ShowDeprecationWarning("setPosition()", "the localPosition property");
2611         MT_Point3 pos;
2612         if (PyVecTo(value, pos))
2613         {
2614                 NodeSetLocalPosition(pos);
2615                 NodeUpdateGS(0.f);
2616                 Py_RETURN_NONE;
2617         }
2618
2619         return NULL;
2620 }
2621
2622 PyObject* KX_GameObject::PySetWorldPosition(PyObject* value)
2623 {
2624         ShowDeprecationWarning("setWorldPosition()", "the worldPosition property");
2625         MT_Point3 pos;
2626         if (PyVecTo(value, pos))
2627         {
2628                 NodeSetWorldPosition(pos);
2629                 NodeUpdateGS(0.f);
2630                 Py_RETURN_NONE;
2631         }
2632
2633         return NULL;
2634 }
2635
2636 PyObject* KX_GameObject::PyGetPhysicsId()
2637 {
2638         KX_IPhysicsController* ctrl = GetPhysicsController();
2639         uint_ptr physid=0;
2640         if (ctrl)
2641         {
2642                 physid= (uint_ptr)ctrl->GetUserData();
2643         }
2644         return PyInt_FromLong((long)physid);
2645 }
2646
2647 PyObject* KX_GameObject::PyGetPropertyNames()
2648 {
2649         PyObject *list=  ConvertKeysToPython();
2650         
2651         if(m_attr_dict) {
2652                 PyObject *key, *value;
2653                 Py_ssize_t pos = 0;
2654
2655                 while (PyDict_Next(m_attr_dict, &pos, &key, &value)) {
2656                         PyList_Append(list, key);
2657                 }
2658         }
2659         return list;
2660 }
2661
2662 KX_PYMETHODDEF_DOC_O(KX_GameObject, getDistanceTo,
2663 "getDistanceTo(other): get distance to another point/KX_GameObject")
2664 {
2665         MT_Point3 b;
2666         if (PyVecTo(value, b))
2667         {
2668                 return PyFloat_FromDouble(NodeGetWorldPosition().distance(b));
2669         }
2670         PyErr_Clear();
2671         
2672         KX_GameObject *other;
2673         if (ConvertPythonToGameObject(value, &other, false, "gameOb.getDistanceTo(value): KX_GameObject"))
2674         {
2675                 return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition()));
2676         }
2677         
2678         return NULL;
2679 }
2680
2681 KX_PYMETHODDEF_DOC_O(KX_GameObject, getVectTo,
2682 "getVectTo(other): get vector and the distance to another point/KX_GameObject\n"
2683 "Returns a 3-tuple with (distance,worldVector,localVector)\n")
2684 {
2685         MT_Point3 toPoint, fromPoint;
2686         MT_Vector3 toDir, locToDir;
2687         MT_Scalar distance;
2688
2689         PyObject *returnValue;
2690
2691         if (!PyVecTo(value, toPoint))
2692         {
2693                 PyErr_Clear();
2694                 
2695                 KX_GameObject *other;
2696                 if (ConvertPythonToGameObject(value, &other, false, "")) /* error will be overwritten */
2697                 {
2698                         toPoint = other->NodeGetWorldPosition();
2699                 } else
2700                 {
2701                         PyErr_SetString(PyExc_TypeError, "gameOb.getVectTo(other): KX_GameObject, expected a 3D Vector or KX_GameObject type");
2702                         return NULL;
2703                 }
2704         }
2705
2706         fromPoint = NodeGetWorldPosition();
2707         toDir = toPoint-fromPoint;
2708         distance = toDir.length();
2709
2710         if (MT_fuzzyZero(distance))
2711         {
2712                 //cout << "getVectTo() Error: Null vector!\n";
2713                 locToDir = toDir = MT_Vector3(0.0,0.0,0.0);
2714                 distance = 0.0;
2715         } else {
2716                 toDir.normalize();
2717                 locToDir = toDir * NodeGetWorldOrientation();
2718         }
2719         
2720         returnValue = PyTuple_New(3);
2721         if (returnValue) { // very unlikely to fail, python sets a memory error here.
2722                 PyTuple_SET_ITEM(returnValue, 0, PyFloat_FromDouble(distance));
2723                 PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(toDir));
2724                 PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(locToDir));
2725         }
2726         return returnValue;
2727 }
2728
2729 bool KX_GameObject::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
2730 {
2731         KX_GameObject* hitKXObj = client->m_gameobject;
2732         
2733         // if X-ray option is selected, the unwnted objects were not tested, so get here only with true hit
2734         // if not, all objects were tested and the front one may not be the correct one.
2735         if (m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
2736         {
2737                 m_pHitObject = hitKXObj;
2738                 return true;
2739         }
2740         // return true to stop RayCast::RayTest from looping, the above test was decisive
2741         // We would want to loop only if we want to get more than one hit point
2742         return true;
2743 }
2744
2745 /* this function is used to pre-filter the object before casting the ray on them.
2746    This is useful for "X-Ray" option when we want to see "through" unwanted object.
2747  */
2748 bool KX_GameObject::NeedRayCast(KX_ClientObjectInfo* client)
2749 {
2750         KX_GameObject* hitKXObj = client->m_gameobject;
2751         
2752         if (client->m_type > KX_ClientObjectInfo::ACTOR)
2753         {
2754                 // Unknown type of object, skip it.
2755                 // Should not occur as the sensor objects are filtered in RayTest()
2756                 printf("Invalid client type %d found in ray casting\n", client->m_type);
2757                 return false;
2758         }
2759         
2760         // if X-Ray option is selected, skip object that don't match the criteria as we see through them
2761         // if not, test all objects because we don't know yet which one will be on front
2762         if (!m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
2763         {
2764                 return true;
2765         }
2766         // skip the object
2767         return false;
2768 }
2769
2770 KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
2771 "rayCastTo(other,dist,prop): look towards another point/KX_GameObject and return first object hit within dist that matches prop\n"
2772 " prop = property name that object must have; can be omitted => detect any object\n"
2773 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to other\n"
2774 " other = 3-tuple or object reference")
2775 {
2776         MT_Point3 toPoint;
2777         PyObject* pyarg;
2778         float dist = 0.0f;
2779         char *propName = NULL;
2780
2781         if (!PyArg_ParseTuple(args,"O|fs:rayCastTo", &pyarg, &dist, &propName)) {
2782                 return NULL; // python sets simple error
2783         }
2784
2785         if (!PyVecTo(pyarg, toPoint))
2786         {
2787                 KX_GameObject *other;
2788                 PyErr_Clear();
2789                 
2790                 if (ConvertPythonToGameObject(pyarg, &other, false, "")) /* error will be overwritten */
2791                 {
2792                         toPoint = other->NodeGetWorldPosition();
2793                 } else
2794                 {
2795                         PyErr_SetString(PyExc_TypeError, "gameOb.rayCastTo(other,dist,prop): KX_GameObject, the first argument to rayCastTo must be a vector or a KX_GameObject");
2796                         return NULL;
2797                 }
2798         }
2799         MT_Point3 fromPoint = NodeGetWorldPosition();
2800         if (dist != 0.0f)
2801         {
2802                 MT_Vector3 toDir = toPoint-fromPoint;
2803                 toDir.normalize();
2804                 toPoint = fromPoint + (dist) * toDir;
2805         }
2806
2807         PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
2808         KX_IPhysicsController *spc = GetPhysicsController();
2809         KX_GameObject *parent = GetParent();
2810         if (!spc && parent)
2811                 spc = parent->GetPhysicsController();
2812         if (parent)
2813                 parent->Release();
2814         
2815         m_pHitObject = NULL;
2816         if (propName)
2817                 m_testPropName = propName;
2818         else
2819                 m_testPropName.SetLength(0);
2820         KX_RayCast::Callback<KX_GameObject> callback(this,spc);
2821         KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
2822
2823     if (m_pHitObject)
2824                 return m_pHitObject->GetProxy();
2825         
2826         Py_RETURN_NONE;
2827 }
2828
2829 /* faster then Py_BuildValue since some scripts call raycast a lot */
2830 static PyObject *none_tuple_3()
2831 {
2832         PyObject *ret= PyTuple_New(3);
2833         PyTuple_SET_ITEM(ret, 0, Py_None);
2834         PyTuple_SET_ITEM(ret, 1, Py_None);
2835         PyTuple_SET_ITEM(ret, 2, Py_None);
2836         
2837         Py_INCREF(Py_None);
2838         Py_INCREF(Py_None);
2839         Py_INCREF(Py_None);
2840         return ret;
2841 }
2842 static PyObject *none_tuple_4()
2843 {
2844         PyObject *ret= PyTuple_New(4);
2845         PyTuple_SET_ITEM(ret, 0, Py_None);
2846         PyTuple_SET_ITEM(ret, 1, Py_None);
2847         PyTuple_SET_ITEM(ret, 2, Py_None);
2848         PyTuple_SET_ITEM(ret, 3, Py_None);
2849         
2850         Py_INCREF(Py_None);
2851         Py_INCREF(Py_None);
2852         Py_INCREF(Py_None);
2853         Py_INCREF(Py_None);
2854         return ret;
2855 }
2856
2857 KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
2858                                    "rayCast(to,from,dist,prop,face,xray,poly): cast a ray and return 3-tuple (object,hit,normal) or 4-tuple (object,hit,normal,polygon) of contact point with object within dist that matches prop.\n"
2859                                    " If no hit, return (None,None,None) or (None,None,None,None).\n"
2860 " to   = 3-tuple or object reference for destination of ray (if object, use center of object)\n"
2861 " from = 3-tuple or object reference for origin of ray (if object, use center of object)\n"
2862 "        Can be None or omitted => start from self object center\n"
2863 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to to\n"
2864 " prop = property name that object must have; can be omitted => detect any object\n"
2865 " face = normal option: 1=>return face normal; 0 or omitted => normal is oriented towards origin\n"
2866 " xray = X-ray option: 1=>skip objects that don't match prop; 0 or omitted => stop on first object\n"
2867 " poly = polygon option: 1=>return value is a 4-tuple and the 4th element is a KX_PolyProxy object\n"
2868 "                           which can be None if hit object has no mesh or if there is no hit\n"
2869 "        If 0 or omitted, return value is a 3-tuple\n"
2870 "Note: The object on which you call this method matters: the ray will ignore it.\n"
2871 "      prop and xray option interact as follow:\n"
2872 "        prop off, xray off: return closest hit or no hit if there is no object on the full extend of the ray\n"
2873 "        prop off, xray on : idem\n"
2874 "        prop on,  xray off: return closest hit if it matches prop, no hit otherwise\n"
2875 "        prop on,  xray on : return closest hit matching prop or no hit if there is no object matching prop on the full extend of the ray\n")
2876 {
2877         MT_Point3 toPoint;
2878         MT_Point3 fromPoint;
2879         PyObject* pyto;
2880         PyObject* pyfrom = NULL;
2881         float dist = 0.0f;
2882         char *propName = NULL;
2883         KX_GameObject *other;
2884         int face=0, xray=0, poly=0;
2885
2886         if (!PyArg_ParseTuple(args,"O|Ofsiii:rayCast", &pyto, &pyfrom, &dist, &propName, &face, &xray, &poly)) {
2887                 return NULL; // Python sets a simple error
2888         }
2889
2890         if (!PyVecTo(pyto, toPoint))
2891         {
2892                 PyErr_Clear();
2893                 
2894                 if (ConvertPythonToGameObject(pyto, &other, false, ""))  /* error will be overwritten */
2895                 {
2896                         toPoint = other->NodeGetWorldPosition();
2897                 } else
2898                 {
2899                         PyErr_SetString(PyExc_TypeError, "the first argument to rayCast must be a vector or a KX_GameObject");
2900                         return NULL;
2901                 }
2902         }
2903         if (!pyfrom || pyfrom == Py_None)
2904         {
2905                 fromPoint = NodeGetWorldPosition();
2906         }
2907         else if (!PyVecTo(pyfrom, fromPoint))
2908         {
2909                 PyErr_Clear();
2910                 
2911                 if (ConvertPythonToGameObject(pyfrom, &other, false, "")) /* error will be overwritten */
2912                 {
2913                         fromPoint = other->NodeGetWorldPosition();
2914                 } else
2915                 {
2916                         PyErr_SetString(PyExc_TypeError, "gameOb.rayCast(to,from,dist,prop,face,xray,poly): KX_GameObject, the second optional argument to rayCast must be a vector or a KX_GameObject");
2917                         return NULL;
2918                 }
2919         }
2920         
2921         if (dist != 0.0f) {
2922                 MT_Vector3 toDir = toPoint-fromPoint;
2923                 if (MT_fuzzyZero(toDir.length2())) {
2924                         //return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2925                         return none_tuple_3();
2926                 }
2927                 toDir.normalize();
2928                 toPoint = fromPoint + (dist) * toDir;
2929         } else if (MT_fuzzyZero((toPoint-fromPoint).length2())) {
2930                 //return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2931                 return none_tuple_3();
2932         }
2933         
2934         PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
2935         KX_IPhysicsController *spc = GetPhysicsController();
2936         KX_GameObject *parent = GetParent();
2937         if (!spc && parent)
2938                 spc = parent->GetPhysicsController();
2939         if (parent)
2940                 parent->Release();
2941         
2942         m_pHitObject = NULL;
2943         if (propName)
2944                 m_testPropName = propName;
2945         else
2946                 m_testPropName.SetLength(0);
2947         m_xray = xray;
2948         // to get the hit results
2949         KX_RayCast::Callback<KX_GameObject> callback(this,spc,NULL,face);
2950         KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
2951
2952         if (m_pHitObject)
2953         {
2954                 PyObject* returnValue = (poly) ? PyTuple_New(4) : PyTuple_New(3);
2955                 if (returnValue) { // unlikely this would ever fail, if it does python sets an error
2956                         PyTuple_SET_ITEM(returnValue, 0, m_pHitObject->GetProxy());
2957                         PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(callback.m_hitPoint));
2958                         PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(callback.m_hitNormal));
2959                         if (poly)
2960                         {
2961                                 if (callback.m_hitMesh)
2962                                 {
2963                                         // if this field is set, then we can trust that m_hitPolygon is a valid polygon
2964                                         RAS_Polygon* polygon = callback.m_hitMesh->GetPolygon(callback.m_hitPolygon);
2965                                         KX_PolyProxy* polyproxy = new KX_PolyProxy(callback.m_hitMesh, polygon);
2966                                         PyTuple_SET_ITEM(returnValue, 3, polyproxy->NewProxy(true));
2967                                 }
2968                                 else
2969                                 {
2970                                         Py_INCREF(Py_None);
2971                                         PyTuple_SET_ITEM(returnValue, 3, Py_None);
2972                                 }
2973                         }
2974                 }
2975                 return returnValue;
2976         }
2977         // no hit
2978         if (poly)
2979                 //return Py_BuildValue("OOOO", Py_None, Py_None, Py_None, Py_None);
2980                 return none_tuple_4();
2981         else
2982                 //return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2983                 return none_tuple_3();
2984 }
2985
2986 KX_PYMETHODDEF_DOC_VARARGS(KX_GameObject, sendMessage, 
2987                                                    "sendMessage(subject, [body, to])\n"
2988 "sends a message in same manner as a message actuator"
2989 "subject = Subject of the message (string)"
2990 "body = Message body (string)"
2991 "to = Name of object to send the message to")
2992 {
2993         KX_Scene *scene = KX_GetActiveScene();
2994         char* subject;
2995         char* body = (char *)"";
2996         char* to = (char *)"";
2997         const STR_String& from = GetName();
2998
2999         if (!PyArg_ParseTuple(args, "s|sss:sendMessage", &subject, &body, &to))
3000                 return NULL;
3001         
3002         scene->GetNetworkScene()->SendMessage(to, from, subject, body);
3003         Py_RETURN_NONE;
3004 }
3005
3006 /* dict style access */
3007
3008
3009 /* Matches python dict.get(key, [default]) */
3010 PyObject* KX_GameObject::Pyget(PyObject *args)
3011 {
3012         PyObject *key;
3013         PyObject* def = Py_None;
3014         PyObject* ret;
3015
3016         if (!PyArg_ParseTuple(args, "O|O:get", &key, &def))
3017                 return NULL;
3018         
3019         
3020         if(PyString_Check(key)) {
3021                 CValue *item = GetProperty(PyString_AsString(key));
3022                 if (item) {
3023                         ret = item->ConvertValueToPython();
3024                         if(ret)
3025                                 return ret;
3026                         else
3027                                 return item->GetProxy();
3028                 }
3029         }
3030         
3031         if (m_attr_dict && (ret=PyDict_GetItem(m_attr_dict, key))) {
3032                 Py_INCREF(ret);
3033                 return ret;
3034         }
3035         
3036         Py_INCREF(def);
3037         return def;
3038 }
3039
3040 /* Matches python dict.has_key() */
3041 PyObject* KX_GameObject::Pyhas_key(PyObject* value)
3042 {
3043         // the ONLY error case is invalid data, this is checked by the macro'd static function
3044         // that calls this one. but make sure Seq_Contains doesnt add extra errors later on.
3045         return PyBool_FromLong(Seq_Contains((PyObject *)this, value));
3046 }
3047
3048 /* --------------------------------------------------------------------- 
3049  * Some stuff taken from the header
3050  * --------------------------------------------------------------------- */
3051 void KX_GameObject::Relink(GEN_Map<GEN_HashedPtr, void*> *map_parameter)        
3052 {
3053         // we will relink the sensors and actuators that use object references
3054         // if the object is part of the replicated hierarchy, use the new
3055         // object reference instead
3056         SCA_SensorList& sensorlist = GetSensors();
3057         SCA_SensorList::iterator sit;
3058         for (sit=sensorlist.begin(); sit != sensorlist.end(); sit++)
3059         {
3060                 (*sit)->Relink(map_parameter);
3061         }
3062         SCA_ActuatorList& actuatorlist = GetActuators();
3063         SCA_ActuatorList::iterator ait;
3064         for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++)
3065         {
3066                 (*ait)->Relink(map_parameter);
3067         }
3068 }
3069
3070
3071 bool ConvertPythonToGameObject(PyObject * value, KX_GameObject **object, bool py_none_ok, const char *error_prefix)
3072 {
3073         if (value==NULL) {
3074                 PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix);
3075                 *object = NULL;
3076                 return false;
3077         }
3078                 
3079         if (value==Py_None) {
3080                 *object = NULL;
3081                 
3082                 if (py_none_ok) {
3083                         return true;
3084                 } else {
3085                         PyErr_Format(PyExc_TypeError, "%s, expected KX_GameObject or a KX_GameObject name, None is invalid", error_prefix);
3086                         return false;
3087                 }
3088         }
3089         
3090         if (PyString_Check(value)) {
3091                 *object = (KX_GameObject*)SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String( PyString_AsString(value) ));
3092                 
3093                 if (*object) {
3094                         return true;
3095                 } else {
3096                         PyErr_Format(PyExc_ValueError, "%s, requested name \"%s\" did not match any KX_GameObject in this scene", error_prefix, PyString_AsString(value));
3097                         return false;
3098                 }
3099         }
3100         
3101         if (    PyObject_TypeCheck(value, &KX_GameObject::Type) ||
3102                         PyObject_TypeCheck(value, &KX_LightObject::Type)        ||
3103                         PyObject_TypeCheck(value, &KX_Camera::Type)     )
3104         {
3105                 *object = static_cast<KX_GameObject*>BGE_PROXY_REF(value);
3106                 
3107                 /* sets the error */
3108                 if (*object==NULL) {
3109                         PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix);
3110                         return false;
3111                 }
3112                 
3113                 return true;
3114         }
3115         
3116         *object = NULL;
3117         
3118         if (py_none_ok) {
3119                 PyErr_Format(PyExc_TypeError, "%s, expect a KX_GameObject, a string or None", error_prefix);
3120         } else {
3121                 PyErr_Format(PyExc_TypeError, "%s, expect a KX_GameObject or a string", error_prefix);
3122         }
3123         
3124         return false;
3125 }