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