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