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