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