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