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