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