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