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