- correct some spelling errors.
[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 parallel to the pivot?
850                                 ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]); //change the pivot!
851                         if (fac == 1.0) {
852                                 x = vect;
853                         } else {
854                                 x = (vect * fac) + ((orimat * MT_Vector3(1.0, 0.0, 0.0)) * (1-fac));
855                                 len = x.length();
856                                 if (MT_fuzzyZero(len)) x = vect;
857                                 else x /= len;
858                         }
859                         y = ori.cross(x);
860                         z = x.cross(y);
861                         break;
862                 case 1: //y axis
863                         ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
864                         if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
865                                 ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]);
866                         if (fac == 1.0) {
867                                 y = vect;
868                         } else {
869                                 y = (vect * fac) + ((orimat * MT_Vector3(0.0, 1.0, 0.0)) * (1-fac));
870                                 len = y.length();
871                                 if (MT_fuzzyZero(len)) y = vect;
872                                 else y /= len;
873                         }
874                         z = ori.cross(y);
875                         x = y.cross(z);
876                         break;
877                 case 2: //z axis
878                         ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]);
879                         if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
880                                 ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
881                         if (fac == 1.0) {
882                                 z = vect;
883                         } else {
884                                 z = (vect * fac) + ((orimat * MT_Vector3(0.0, 0.0, 1.0)) * (1-fac));
885                                 len = z.length();
886                                 if (MT_fuzzyZero(len)) z = vect;
887                                 else z /= len;
888                         }
889                         x = ori.cross(z);
890                         y = z.cross(x);
891                         break;
892                 default: //wrong input?
893                         cout << "alignAxisToVect(): Wrong axis '" << axis <<"'\n";
894                         return;
895         }
896         x.normalize(); //normalize the vectors
897         y.normalize();
898         z.normalize();
899         orimat.setValue(        x[0],y[0],z[0],
900                                                 x[1],y[1],z[1],
901                                                 x[2],y[2],z[2]);
902         if (GetSGNode()->GetSGParent() != NULL)
903         {
904                 // the object is a child, adapt its local orientation so that 
905                 // the global orientation is aligned as we want.
906                 MT_Matrix3x3 invori = GetSGNode()->GetSGParent()->GetWorldOrientation().inverse();
907                 NodeSetLocalOrientation(invori*orimat);
908         }
909         else
910                 NodeSetLocalOrientation(orimat);
911 }
912
913 MT_Scalar KX_GameObject::GetMass()
914 {
915         if (m_pPhysicsController1)
916         {
917                 return m_pPhysicsController1->GetMass();
918         }
919         return 0.0;
920 }
921
922 MT_Vector3 KX_GameObject::GetLocalInertia()
923 {
924         MT_Vector3 local_inertia(0.0,0.0,0.0);
925         if (m_pPhysicsController1)
926         {
927                 local_inertia = m_pPhysicsController1->GetLocalInertia();
928         }
929         return local_inertia;
930 }
931
932 MT_Vector3 KX_GameObject::GetLinearVelocity(bool local)
933 {
934         MT_Vector3 velocity(0.0,0.0,0.0), locvel;
935         MT_Matrix3x3 ori;
936         if (m_pPhysicsController1)
937         {
938                 velocity = m_pPhysicsController1->GetLinearVelocity();
939                 
940                 if (local)
941                 {
942                         ori = GetSGNode()->GetWorldOrientation();
943                         
944                         locvel = velocity * ori;
945                         return locvel;
946                 }
947         }
948         return velocity;        
949 }
950
951 MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
952 {
953         MT_Vector3 velocity(0.0,0.0,0.0), locvel;
954         MT_Matrix3x3 ori;
955         if (m_pPhysicsController1)
956         {
957                 velocity = m_pPhysicsController1->GetAngularVelocity();
958                 
959                 if (local)
960                 {
961                         ori = GetSGNode()->GetWorldOrientation();
962                         
963                         locvel = velocity * ori;
964                         return locvel;
965                 }
966         }
967         return velocity;        
968 }
969
970 MT_Vector3 KX_GameObject::GetVelocity(const MT_Point3& point)
971 {
972         if (m_pPhysicsController1)
973         {
974                 return m_pPhysicsController1->GetVelocity(point);
975         }
976         return MT_Vector3(0.0,0.0,0.0);
977 }
978
979 // scenegraph node stuff
980
981 void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans)
982 {
983         // check on valid node in case a python controller holds a reference to a deleted object
984         if (!GetSGNode())
985                 return;
986
987         if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
988         {
989                 // don't update physic controller if the object is a child:
990                 // 1) the transformation will not be right
991                 // 2) in this case, the physic controller is necessarily a static object
992                 //    that is updated from the normal kinematic synchronization
993                 m_pPhysicsController1->setPosition(trans);
994         }
995
996         GetSGNode()->SetLocalPosition(trans);
997
998 }
999
1000
1001
1002 void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3& rot)
1003 {
1004         // check on valid node in case a python controller holds a reference to a deleted object
1005         if (!GetSGNode())
1006                 return;
1007
1008         if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
1009         {
1010                 // see note above
1011                 m_pPhysicsController1->setOrientation(rot);
1012         }
1013         GetSGNode()->SetLocalOrientation(rot);
1014 }
1015
1016 void KX_GameObject::NodeSetGlobalOrientation(const MT_Matrix3x3& rot)
1017 {
1018         // check on valid node in case a python controller holds a reference to a deleted object
1019         if (!GetSGNode())
1020                 return;
1021
1022         if (GetSGNode()->GetSGParent())
1023                 GetSGNode()->SetLocalOrientation(GetSGNode()->GetSGParent()->GetWorldOrientation().inverse()*rot);
1024         else
1025                 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(BaseMathObject *bmo)
1256 {
1257         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1258         if(self==NULL)
1259                 return 0;
1260         
1261         return 1;
1262 }
1263
1264 static int mathutils_kxgameob_vector_get(BaseMathObject *bmo, int subtype)
1265 {
1266         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1267         if(self==NULL)
1268                 return 0;
1269         
1270         switch(subtype) {
1271                 case MATHUTILS_VEC_CB_POS_LOCAL:
1272                         self->NodeGetLocalPosition().getValue(bmo->data);
1273                         break;
1274                 case MATHUTILS_VEC_CB_POS_GLOBAL:
1275                         self->NodeGetWorldPosition().getValue(bmo->data);
1276                         break;
1277                 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1278                         self->NodeGetLocalScaling().getValue(bmo->data);
1279                         break;
1280                 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1281                         self->NodeGetWorldScaling().getValue(bmo->data);
1282                         break;
1283                 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1284                         if(!self->GetPhysicsController()) return 0;
1285                         self->GetPhysicsController()->GetLocalInertia().getValue(bmo->data);
1286                         break;
1287                 case MATHUTILS_VEC_CB_OBJECT_COLOR:
1288                         self->GetObjectColor().getValue(bmo->data);
1289                         break;
1290                 case MATHUTILS_VEC_CB_LINVEL_LOCAL:
1291                         if(!self->GetPhysicsController()) return 0;
1292                         self->GetLinearVelocity(true).getValue(bmo->data);
1293                         break;
1294                 case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
1295                         if(!self->GetPhysicsController()) return 0;
1296                         self->GetLinearVelocity(false).getValue(bmo->data);
1297                         break;
1298                 case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
1299                         if(!self->GetPhysicsController()) return 0;
1300                         self->GetAngularVelocity(true).getValue(bmo->data);
1301                         break;
1302                 case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
1303                         if(!self->GetPhysicsController()) return 0;
1304                         self->GetAngularVelocity(false).getValue(bmo->data);
1305                         break;
1306                         
1307         }
1308         
1309         return 1;
1310 }
1311
1312 static int mathutils_kxgameob_vector_set(BaseMathObject *bmo, int subtype)
1313 {
1314         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1315         if(self==NULL)
1316                 return 0;
1317         
1318         switch(subtype) {
1319                 case MATHUTILS_VEC_CB_POS_LOCAL:
1320                         self->NodeSetLocalPosition(MT_Point3(bmo->data));
1321                         self->NodeUpdateGS(0.f);
1322                         break;
1323                 case MATHUTILS_VEC_CB_POS_GLOBAL:
1324                         self->NodeSetWorldPosition(MT_Point3(bmo->data));
1325                         self->NodeUpdateGS(0.f);
1326                         break;
1327                 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1328                         self->NodeSetLocalScale(MT_Point3(bmo->data));
1329                         self->NodeUpdateGS(0.f);
1330                         break;
1331                 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1332                         PyErr_SetString(PyExc_AttributeError, "KX_GameObject.worldScale is read-only");
1333                         return 0;
1334                 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1335                         /* read only */
1336                         break;
1337                 case MATHUTILS_VEC_CB_OBJECT_COLOR:
1338                         self->SetObjectColor(MT_Vector4(bmo->data));
1339                         break;
1340                 case MATHUTILS_VEC_CB_LINVEL_LOCAL:
1341                         self->setLinearVelocity(MT_Point3(bmo->data),true);
1342                         break;
1343                 case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
1344                         self->setLinearVelocity(MT_Point3(bmo->data),false);
1345                         break;
1346                 case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
1347                         self->setAngularVelocity(MT_Point3(bmo->data),true);
1348                         break;
1349                 case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
1350                         self->setAngularVelocity(MT_Point3(bmo->data),false);
1351                         break;
1352         }
1353         
1354         return 1;
1355 }
1356
1357 static int mathutils_kxgameob_vector_get_index(BaseMathObject *bmo, int subtype, int index)
1358 {
1359         /* lazy, avoid repeteing the case statement */
1360         if(!mathutils_kxgameob_vector_get(bmo, subtype))
1361                 return 0;
1362         return 1;
1363 }
1364
1365 static int mathutils_kxgameob_vector_set_index(BaseMathObject *bmo, int subtype, int index)
1366 {
1367         float f= bmo->data[index];
1368         
1369         /* lazy, avoid repeteing the case statement */
1370         if(!mathutils_kxgameob_vector_get(bmo, subtype))
1371                 return 0;
1372         
1373         bmo->data[index]= f;
1374         return mathutils_kxgameob_vector_set(bmo, subtype);
1375 }
1376
1377 Mathutils_Callback mathutils_kxgameob_vector_cb = {
1378         mathutils_kxgameob_generic_check,
1379         mathutils_kxgameob_vector_get,
1380         mathutils_kxgameob_vector_set,
1381         mathutils_kxgameob_vector_get_index,
1382         mathutils_kxgameob_vector_set_index
1383 };
1384
1385 /* Matrix */
1386 #define MATHUTILS_MAT_CB_ORI_LOCAL 1
1387 #define MATHUTILS_MAT_CB_ORI_GLOBAL 2
1388
1389 static int mathutils_kxgameob_matrix_cb_index= -1; /* index for our callbacks */
1390
1391 static int mathutils_kxgameob_matrix_get(BaseMathObject *bmo, int subtype)
1392 {
1393         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1394         if(self==NULL)
1395                 return 0;
1396
1397         switch(subtype) {
1398                 case MATHUTILS_MAT_CB_ORI_LOCAL:
1399                         self->NodeGetLocalOrientation().getValue3x3(bmo->data);
1400                         break;
1401                 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1402                         self->NodeGetWorldOrientation().getValue3x3(bmo->data);
1403                         break;
1404         }
1405         
1406         return 1;
1407 }
1408
1409
1410 static int mathutils_kxgameob_matrix_set(BaseMathObject *bmo, int subtype)
1411 {
1412         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1413         if(self==NULL)
1414                 return 0;
1415         
1416         MT_Matrix3x3 mat3x3;
1417         switch(subtype) {
1418                 case MATHUTILS_MAT_CB_ORI_LOCAL:
1419                         mat3x3.setValue3x3(bmo->data);
1420                         self->NodeSetLocalOrientation(mat3x3);
1421                         self->NodeUpdateGS(0.f);
1422                         break;
1423                 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1424                         mat3x3.setValue3x3(bmo->data);
1425                         self->NodeSetLocalOrientation(mat3x3);
1426                         self->NodeUpdateGS(0.f);
1427                         break;
1428         }
1429         
1430         return 1;
1431 }
1432
1433 Mathutils_Callback mathutils_kxgameob_matrix_cb = {
1434         mathutils_kxgameob_generic_check,
1435         mathutils_kxgameob_matrix_get,
1436         mathutils_kxgameob_matrix_set,
1437         NULL,
1438         NULL
1439 };
1440
1441
1442 void KX_GameObject_Mathutils_Callback_Init(void)
1443 {
1444         // register mathutils callbacks, ok to run more then once.
1445         mathutils_kxgameob_vector_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_vector_cb);
1446         mathutils_kxgameob_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_matrix_cb);
1447 }
1448
1449 #endif // USE_MATHUTILS
1450
1451 #ifndef DISABLE_PYTHON
1452 /* ------- python stuff ---------------------------------------------------*/
1453 PyMethodDef KX_GameObject::Methods[] = {
1454         {"applyForce", (PyCFunction)    KX_GameObject::sPyApplyForce, METH_VARARGS},
1455         {"applyTorque", (PyCFunction)   KX_GameObject::sPyApplyTorque, METH_VARARGS},
1456         {"applyRotation", (PyCFunction) KX_GameObject::sPyApplyRotation, METH_VARARGS},
1457         {"applyMovement", (PyCFunction) KX_GameObject::sPyApplyMovement, METH_VARARGS},
1458         {"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS},
1459         {"setLinearVelocity", (PyCFunction) KX_GameObject::sPySetLinearVelocity, METH_VARARGS},
1460         {"getAngularVelocity", (PyCFunction) KX_GameObject::sPyGetAngularVelocity, METH_VARARGS},
1461         {"setAngularVelocity", (PyCFunction) KX_GameObject::sPySetAngularVelocity, METH_VARARGS},
1462         {"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS},
1463         {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS},
1464         {"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS},
1465         {"getAxisVect",(PyCFunction) KX_GameObject::sPyGetAxisVect, METH_O},
1466         {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics,METH_NOARGS},
1467         {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_NOARGS},
1468         {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_NOARGS},
1469         {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_NOARGS},
1470         {"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS},
1471         {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_O},
1472         {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_VARARGS},
1473         {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},
1474         {"setOcclusion",(PyCFunction) KX_GameObject::sPySetOcclusion, METH_VARARGS},
1475         {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_NOARGS},
1476
1477
1478         {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS},
1479         {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS},
1480         {"replaceMesh",(PyCFunction) KX_GameObject::sPyReplaceMesh, METH_VARARGS},
1481         {"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS},
1482         {"reinstancePhysicsMesh", (PyCFunction)KX_GameObject::sPyReinstancePhysicsMesh,METH_VARARGS},
1483         
1484         KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
1485         KX_PYMETHODTABLE(KX_GameObject, rayCast),
1486         KX_PYMETHODTABLE_O(KX_GameObject, getDistanceTo),
1487         KX_PYMETHODTABLE_O(KX_GameObject, getVectTo),
1488         KX_PYMETHODTABLE(KX_GameObject, sendMessage),
1489         
1490         // dict style access for props
1491         {"get",(PyCFunction) KX_GameObject::sPyget, METH_VARARGS},
1492         
1493         {NULL,NULL} //Sentinel
1494 };
1495
1496 PyAttributeDef KX_GameObject::Attributes[] = {
1497         KX_PYATTRIBUTE_RO_FUNCTION("name",              KX_GameObject, pyattr_get_name),
1498         KX_PYATTRIBUTE_RO_FUNCTION("parent",    KX_GameObject, pyattr_get_parent),
1499         KX_PYATTRIBUTE_RW_FUNCTION("mass",              KX_GameObject, pyattr_get_mass,         pyattr_set_mass),
1500         KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMin",            KX_GameObject, pyattr_get_lin_vel_min, pyattr_set_lin_vel_min),
1501         KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMax",            KX_GameObject, pyattr_get_lin_vel_max, pyattr_set_lin_vel_max),
1502         KX_PYATTRIBUTE_RW_FUNCTION("visible",   KX_GameObject, pyattr_get_visible,      pyattr_set_visible),
1503         KX_PYATTRIBUTE_BOOL_RW    ("occlusion", KX_GameObject, m_bOccluder),
1504         KX_PYATTRIBUTE_RW_FUNCTION("position",  KX_GameObject, pyattr_get_worldPosition,        pyattr_set_localPosition),
1505         KX_PYATTRIBUTE_RO_FUNCTION("localInertia",      KX_GameObject, pyattr_get_localInertia),
1506         KX_PYATTRIBUTE_RW_FUNCTION("orientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_localOrientation),
1507         KX_PYATTRIBUTE_RW_FUNCTION("scaling",   KX_GameObject, pyattr_get_worldScaling, pyattr_set_localScaling),
1508         KX_PYATTRIBUTE_RW_FUNCTION("timeOffset",KX_GameObject, pyattr_get_timeOffset,pyattr_set_timeOffset),
1509         KX_PYATTRIBUTE_RW_FUNCTION("state",             KX_GameObject, pyattr_get_state,        pyattr_set_state),
1510         KX_PYATTRIBUTE_RO_FUNCTION("meshes",    KX_GameObject, pyattr_get_meshes),
1511         KX_PYATTRIBUTE_RW_FUNCTION("localOrientation",KX_GameObject,pyattr_get_localOrientation,pyattr_set_localOrientation),
1512         KX_PYATTRIBUTE_RW_FUNCTION("worldOrientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_worldOrientation),
1513         KX_PYATTRIBUTE_RW_FUNCTION("localPosition",     KX_GameObject, pyattr_get_localPosition,        pyattr_set_localPosition),
1514         KX_PYATTRIBUTE_RW_FUNCTION("worldPosition",     KX_GameObject, pyattr_get_worldPosition,    pyattr_set_worldPosition),
1515         KX_PYATTRIBUTE_RW_FUNCTION("localScale",        KX_GameObject, pyattr_get_localScaling, pyattr_set_localScaling),
1516         KX_PYATTRIBUTE_RO_FUNCTION("worldScale",        KX_GameObject, pyattr_get_worldScaling),
1517         KX_PYATTRIBUTE_RW_FUNCTION("linearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_worldLinearVelocity),
1518         KX_PYATTRIBUTE_RW_FUNCTION("localLinearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_localLinearVelocity),
1519         KX_PYATTRIBUTE_RW_FUNCTION("worldLinearVelocity", KX_GameObject, pyattr_get_worldLinearVelocity, pyattr_set_worldLinearVelocity),
1520         KX_PYATTRIBUTE_RW_FUNCTION("angularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_worldAngularVelocity),
1521         KX_PYATTRIBUTE_RW_FUNCTION("localAngularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_localAngularVelocity),
1522         KX_PYATTRIBUTE_RW_FUNCTION("worldAngularVelocity", KX_GameObject, pyattr_get_worldAngularVelocity, pyattr_set_worldAngularVelocity),
1523         KX_PYATTRIBUTE_RO_FUNCTION("children",  KX_GameObject, pyattr_get_children),
1524         KX_PYATTRIBUTE_RO_FUNCTION("childrenRecursive", KX_GameObject, pyattr_get_children_recursive),
1525         KX_PYATTRIBUTE_RO_FUNCTION("attrDict",  KX_GameObject, pyattr_get_attrDict),
1526         KX_PYATTRIBUTE_RW_FUNCTION("color", KX_GameObject, pyattr_get_obcolor, pyattr_set_obcolor),
1527         
1528         /* Experemental, dont rely on these yet */
1529         KX_PYATTRIBUTE_RO_FUNCTION("sensors",           KX_GameObject, pyattr_get_sensors),
1530         KX_PYATTRIBUTE_RO_FUNCTION("controllers",       KX_GameObject, pyattr_get_controllers),
1531         KX_PYATTRIBUTE_RO_FUNCTION("actuators",         KX_GameObject, pyattr_get_actuators),
1532         {NULL} //Sentinel
1533 };
1534
1535 PyObject* KX_GameObject::PyReplaceMesh(PyObject* args)
1536 {
1537         KX_Scene *scene = KX_GetActiveScene();
1538         
1539         PyObject *value;
1540         int use_gfx= 1, use_phys= 0;
1541         RAS_MeshObject *new_mesh;
1542         
1543         if (!PyArg_ParseTuple(args,"O|ii:replaceMesh", &value, &use_gfx, &use_phys))
1544                 return NULL;
1545         
1546         if (!ConvertPythonToMesh(value, &new_mesh, false, "gameOb.replaceMesh(value): KX_GameObject"))
1547                 return NULL;
1548         
1549         scene->ReplaceMesh(this, new_mesh, (bool)use_gfx, (bool)use_phys);
1550         Py_RETURN_NONE;
1551 }
1552
1553 PyObject* KX_GameObject::PyEndObject()
1554 {
1555         KX_Scene *scene = KX_GetActiveScene();
1556         
1557         scene->DelayedRemoveObject(this);
1558         
1559         Py_RETURN_NONE;
1560
1561 }
1562
1563 PyObject* KX_GameObject::PyReinstancePhysicsMesh(PyObject* args)
1564 {
1565         KX_GameObject *gameobj= NULL;
1566         RAS_MeshObject *mesh= NULL;
1567         
1568         PyObject *gameobj_py= NULL;
1569         PyObject *mesh_py= NULL;
1570
1571         if (    !PyArg_ParseTuple(args,"|OO:reinstancePhysicsMesh",&gameobj_py, &mesh_py) ||
1572                         (gameobj_py && !ConvertPythonToGameObject(gameobj_py, &gameobj, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject")) || 
1573                         (mesh_py && !ConvertPythonToMesh(mesh_py, &mesh, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject"))
1574                 ) {
1575                 return NULL;
1576         }
1577         
1578         /* gameobj and mesh can be NULL */
1579         if(KX_ReInstanceBulletShapeFromMesh(this, gameobj, mesh))
1580                 Py_RETURN_TRUE;
1581
1582         Py_RETURN_FALSE;
1583 }
1584
1585 static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
1586 {
1587         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1588         const char *attr_str= _PyUnicode_AsString(item);
1589         CValue* resultattr;
1590         PyObject* pyconvert;
1591         
1592         if (self==NULL) {
1593                 PyErr_SetString(PyExc_SystemError, "val = gameOb[key]: KX_GameObject, "BGE_PROXY_ERROR_MSG);
1594                 return NULL;
1595         }
1596         
1597         /* first see if the attributes a string and try get the cvalue attribute */
1598         if(attr_str && (resultattr=self->GetProperty(attr_str))) {
1599                 pyconvert = resultattr->ConvertValueToPython();                 
1600                 return pyconvert ? pyconvert:resultattr->GetProxy();
1601         }
1602         /* no CValue attribute, try get the python only m_attr_dict attribute */
1603         else if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
1604                 
1605                 if (attr_str)
1606                         PyErr_Clear();
1607                 Py_INCREF(pyconvert);
1608                 return pyconvert;
1609         }
1610         else {
1611                 if(attr_str)    PyErr_Format(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key \"%s\" does not exist", attr_str);
1612                 else                    PyErr_SetString(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key does not exist");
1613                 return NULL;
1614         }
1615                 
1616 }
1617
1618
1619 static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
1620 {
1621         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1622         const char *attr_str= _PyUnicode_AsString(key);
1623         if(attr_str==NULL)
1624                 PyErr_Clear();
1625         
1626         if (self==NULL) {
1627                 PyErr_SetString(PyExc_SystemError, "gameOb[key] = value: KX_GameObject, "BGE_PROXY_ERROR_MSG);
1628                 return -1;
1629         }
1630         
1631         if (val==NULL) { /* del ob["key"] */
1632                 int del= 0;
1633                 
1634                 /* try remove both just incase */
1635                 if(attr_str)
1636                         del |= (self->RemoveProperty(attr_str)==true) ? 1:0;
1637                 
1638                 if(self->m_attr_dict)
1639                         del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
1640                 
1641                 if (del==0) {
1642                         if(attr_str)    PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" could not be set", attr_str);
1643                         else                    PyErr_SetString(PyExc_KeyError, "del gameOb[key]: KX_GameObject, key could not be deleted");
1644                         return -1;
1645                 }
1646                 else if (self->m_attr_dict) {
1647                         PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
1648                 }
1649         }
1650         else { /* ob["key"] = value */
1651                 int set= 0;
1652                 
1653                 /* as CValue */
1654                 if(attr_str && PyObject_TypeCheck(val, &PyObjectPlus::Type)==0) /* dont allow GameObjects for eg to be assigned to CValue props */
1655                 {
1656                         CValue* vallie = self->ConvertPythonToValue(val, ""); /* error unused */
1657                         
1658                         if(vallie)
1659                         {
1660                                 CValue* oldprop = self->GetProperty(attr_str);
1661                                 
1662                                 if (oldprop)
1663                                         oldprop->SetValue(vallie);
1664                                 else
1665                                         self->SetProperty(attr_str, vallie);
1666                                 
1667                                 vallie->Release();
1668                                 set= 1;
1669                                 
1670                                 /* try remove dict value to avoid double ups */
1671                                 if (self->m_attr_dict){
1672                                         if (PyDict_DelItem(self->m_attr_dict, key) != 0)
1673                                                 PyErr_Clear();
1674                                 }
1675                         }
1676                         else {
1677                                 PyErr_Clear();
1678                         }
1679                 }
1680                 
1681                 if(set==0)
1682                 {
1683                         if (self->m_attr_dict==NULL) /* lazy init */
1684                                 self->m_attr_dict= PyDict_New();
1685                         
1686                         
1687                         if(PyDict_SetItem(self->m_attr_dict, key, val)==0)
1688                         {
1689                                 if(attr_str)
1690                                         self->RemoveProperty(attr_str); /* overwrite the CValue if it exists */
1691                                 set= 1;
1692                         }
1693                         else {
1694                                 if(attr_str)    PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" not be added to internal dictionary", attr_str);
1695                                 else                    PyErr_SetString(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key not be added to internal dictionary");
1696                         }
1697                 }
1698                 
1699                 if(set==0)
1700                         return -1; /* pythons error value */
1701                 
1702         }
1703         
1704         return 0; /* success */
1705 }
1706
1707 static int Seq_Contains(PyObject *self_v, PyObject *value)
1708 {
1709         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1710         
1711         if (self==NULL) {
1712                 PyErr_SetString(PyExc_SystemError, "val in gameOb: KX_GameObject, "BGE_PROXY_ERROR_MSG);
1713                 return -1;
1714         }
1715         
1716         if(PyUnicode_Check(value) && self->GetProperty(_PyUnicode_AsString(value)))
1717                 return 1;
1718         
1719         if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
1720                 return 1;
1721         
1722         return 0;
1723 }
1724
1725
1726 PyMappingMethods KX_GameObject::Mapping = {
1727         (lenfunc)NULL                                   ,                       /*inquiry mp_length */
1728         (binaryfunc)Map_GetItem,                /*binaryfunc mp_subscript */
1729         (objobjargproc)Map_SetItem,     /*objobjargproc mp_ass_subscript */
1730 };
1731
1732 PySequenceMethods KX_GameObject::Sequence = {
1733         NULL,           /* Cant set the len otherwise it can evaluate as false */
1734         NULL,           /* sq_concat */
1735         NULL,           /* sq_repeat */
1736         NULL,           /* sq_item */
1737         NULL,           /* sq_slice */
1738         NULL,           /* sq_ass_item */
1739         NULL,           /* sq_ass_slice */
1740         (objobjproc)Seq_Contains,       /* sq_contains */
1741         (binaryfunc) NULL, /* sq_inplace_concat */
1742         (ssizeargfunc) NULL, /* sq_inplace_repeat */
1743 };
1744
1745 PyTypeObject KX_GameObject::Type = {
1746         PyVarObject_HEAD_INIT(NULL, 0)
1747         "KX_GameObject",
1748         sizeof(PyObjectPlus_Proxy),
1749         0,
1750         py_base_dealloc,
1751         0,
1752         0,
1753         0,
1754         0,
1755         py_base_repr,
1756         0,
1757         &Sequence,
1758         &Mapping,
1759         0,0,0,
1760         NULL,
1761         NULL,
1762         0,
1763         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
1764         0,0,0,0,0,0,0,
1765         Methods,
1766         0,
1767         0,
1768         &SCA_IObject::Type,
1769         0,0,0,0,0,0,
1770         py_base_new
1771 };
1772
1773 PyObject* KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1774 {
1775         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1776         return PyUnicode_FromString(self->GetName().ReadPtr());
1777 }
1778
1779 PyObject* KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1780 {
1781         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1782         KX_GameObject* parent = self->GetParent();
1783         if (parent) {
1784                 parent->Release(); /* self->GetParent() AddRef's */
1785                 return parent->GetProxy();
1786         }
1787         Py_RETURN_NONE;
1788 }
1789
1790 PyObject* KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1791 {
1792         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1793         KX_IPhysicsController *spc = self->GetPhysicsController();
1794         return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0f);
1795 }
1796
1797 int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1798 {
1799         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1800         KX_IPhysicsController *spc = self->GetPhysicsController();
1801         MT_Scalar val = PyFloat_AsDouble(value);
1802         if (val < 0.0f) { /* also accounts for non float */
1803                 PyErr_SetString(PyExc_AttributeError, "gameOb.mass = float: KX_GameObject, expected a float zero or above");
1804                 return PY_SET_ATTR_FAIL;
1805         }
1806
1807         if (spc)
1808                 spc->SetMass(val);
1809
1810         return PY_SET_ATTR_SUCCESS;
1811 }
1812
1813 PyObject* KX_GameObject::pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1814 {
1815         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1816         KX_IPhysicsController *spc = self->GetPhysicsController();
1817         return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
1818 }
1819
1820 int KX_GameObject::pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1821 {
1822         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1823         KX_IPhysicsController *spc = self->GetPhysicsController();
1824         MT_Scalar val = PyFloat_AsDouble(value);
1825         if (val < 0.0f) { /* also accounts for non float */
1826                 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMin = float: KX_GameObject, expected a float zero or above");
1827                 return PY_SET_ATTR_FAIL;
1828         }
1829
1830         if (spc)
1831                 spc->SetLinVelocityMin(val);
1832
1833         return PY_SET_ATTR_SUCCESS;
1834 }
1835
1836 PyObject* KX_GameObject::pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1837 {
1838         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1839         KX_IPhysicsController *spc = self->GetPhysicsController();
1840         return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
1841 }
1842
1843 int KX_GameObject::pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1844 {
1845         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1846         KX_IPhysicsController *spc = self->GetPhysicsController();
1847         MT_Scalar val = PyFloat_AsDouble(value);
1848         if (val < 0.0f) { /* also accounts for non float */
1849                 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMax = float: KX_GameObject, expected a float zero or above");
1850                 return PY_SET_ATTR_FAIL;
1851         }
1852
1853         if (spc)
1854                 spc->SetLinVelocityMax(val);
1855
1856         return PY_SET_ATTR_SUCCESS;
1857 }
1858
1859
1860 PyObject* KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1861 {
1862         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1863         return PyBool_FromLong(self->GetVisible());
1864 }
1865
1866 int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1867 {
1868         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1869         int param = PyObject_IsTrue( value );
1870         if (param == -1) {
1871                 PyErr_SetString(PyExc_AttributeError, "gameOb.visible = bool: KX_GameObject, expected True or False");
1872                 return PY_SET_ATTR_FAIL;
1873         }
1874
1875         self->SetVisible(param, false);
1876         self->UpdateBuckets(false);
1877         return PY_SET_ATTR_SUCCESS;
1878 }
1879
1880 PyObject* KX_GameObject::pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1881 {
1882 #ifdef USE_MATHUTILS
1883         return newVectorObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_GLOBAL);
1884 #else
1885         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1886         return PyObjectFrom(self->NodeGetWorldPosition());
1887 #endif
1888 }
1889
1890 int KX_GameObject::pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1891 {
1892         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1893         MT_Point3 pos;
1894         if (!PyVecTo(value, pos))
1895                 return PY_SET_ATTR_FAIL;
1896         
1897         self->NodeSetWorldPosition(pos);
1898         self->NodeUpdateGS(0.f);
1899         return PY_SET_ATTR_SUCCESS;
1900 }
1901
1902 PyObject* KX_GameObject::pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1903 {
1904 #ifdef USE_MATHUTILS    
1905         return newVectorObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_LOCAL);
1906 #else   
1907         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1908         return PyObjectFrom(self->NodeGetLocalPosition());
1909 #endif
1910 }
1911
1912 int KX_GameObject::pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1913 {
1914         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1915         MT_Point3 pos;
1916         if (!PyVecTo(value, pos))
1917                 return PY_SET_ATTR_FAIL;
1918         
1919         self->NodeSetLocalPosition(pos);
1920         self->NodeUpdateGS(0.f);
1921         return PY_SET_ATTR_SUCCESS;
1922 }
1923
1924 PyObject* KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1925 {
1926 #ifdef USE_MATHUTILS
1927         return newVectorObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_INERTIA_LOCAL);
1928 #else
1929         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1930         if (self->GetPhysicsController())
1931                 return PyObjectFrom(self->GetPhysicsController()->GetLocalInertia());
1932         return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
1933 #endif
1934 }
1935
1936 PyObject* KX_GameObject::pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1937 {
1938 #ifdef USE_MATHUTILS
1939         return newMatrixObject_cb(BGE_PROXY_FROM_REF(self_v), 3, 3, mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_GLOBAL);
1940 #else
1941         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1942         return PyObjectFrom(self->NodeGetWorldOrientation());
1943 #endif
1944 }
1945
1946 int KX_GameObject::pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1947 {
1948         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1949         
1950         /* if value is not a sequence PyOrientationTo makes an error */
1951         MT_Matrix3x3 rot;
1952         if (!PyOrientationTo(value, rot, "gameOb.worldOrientation = sequence: KX_GameObject, "))
1953                 return PY_SET_ATTR_FAIL;
1954
1955         self->NodeSetGlobalOrientation(rot);
1956         
1957         self->NodeUpdateGS(0.f);
1958         return PY_SET_ATTR_SUCCESS;
1959 }
1960
1961 PyObject* KX_GameObject::pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1962 {
1963 #ifdef USE_MATHUTILS
1964         return newMatrixObject_cb(BGE_PROXY_FROM_REF(self_v), 3, 3, mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_LOCAL);
1965 #else
1966         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1967         return PyObjectFrom(self->NodeGetLocalOrientation());
1968 #endif
1969 }
1970
1971 int KX_GameObject::pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1972 {
1973         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1974         
1975         /* if value is not a sequence PyOrientationTo makes an error */
1976         MT_Matrix3x3 rot;
1977         if (!PyOrientationTo(value, rot, "gameOb.localOrientation = sequence: KX_GameObject, "))
1978                 return PY_SET_ATTR_FAIL;
1979
1980         self->NodeSetLocalOrientation(rot);
1981         self->NodeUpdateGS(0.f);
1982         return PY_SET_ATTR_SUCCESS;
1983 }
1984
1985 PyObject* KX_GameObject::pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1986 {
1987 #ifdef USE_MATHUTILS
1988         return newVectorObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_GLOBAL);
1989 #else
1990         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1991         return PyObjectFrom(self->NodeGetWorldScaling());
1992 #endif
1993 }
1994
1995 PyObject* KX_GameObject::pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1996 {
1997 #ifdef USE_MATHUTILS
1998         return newVectorObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_LOCAL);
1999 #else
2000         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2001         return PyObjectFrom(self->NodeGetLocalScaling());
2002 #endif
2003 }
2004
2005 int KX_GameObject::pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2006 {
2007         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2008         MT_Vector3 scale;
2009         if (!PyVecTo(value, scale))
2010                 return PY_SET_ATTR_FAIL;
2011
2012         self->NodeSetLocalScale(scale);
2013         self->NodeUpdateGS(0.f);
2014         return PY_SET_ATTR_SUCCESS;
2015 }
2016
2017
2018 PyObject* KX_GameObject::pyattr_get_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2019 {
2020 #ifdef USE_MATHUTILS
2021         return newVectorObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_GLOBAL);
2022 #else
2023         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2024         return PyObjectFrom(GetLinearVelocity(false));
2025 #endif
2026 }
2027
2028 int KX_GameObject::pyattr_set_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2029 {
2030         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2031         MT_Vector3 velocity;
2032         if (!PyVecTo(value, velocity))
2033                 return PY_SET_ATTR_FAIL;
2034
2035         self->setLinearVelocity(velocity, false);
2036
2037         return PY_SET_ATTR_SUCCESS;
2038 }
2039
2040 PyObject* KX_GameObject::pyattr_get_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2041 {
2042 #ifdef USE_MATHUTILS
2043         return newVectorObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_LOCAL);
2044 #else
2045         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2046         return PyObjectFrom(GetLinearVelocity(true));
2047 #endif
2048 }
2049
2050 int KX_GameObject::pyattr_set_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2051 {
2052         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2053         MT_Vector3 velocity;
2054         if (!PyVecTo(value, velocity))
2055                 return PY_SET_ATTR_FAIL;
2056
2057         self->setLinearVelocity(velocity, true);
2058
2059         return PY_SET_ATTR_SUCCESS;
2060 }
2061
2062 PyObject* KX_GameObject::pyattr_get_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2063 {
2064 #ifdef USE_MATHUTILS
2065         return newVectorObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_GLOBAL);
2066 #else
2067         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2068         return PyObjectFrom(GetAngularVelocity(false));
2069 #endif
2070 }
2071
2072 int KX_GameObject::pyattr_set_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2073 {
2074         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2075         MT_Vector3 velocity;
2076         if (!PyVecTo(value, velocity))
2077                 return PY_SET_ATTR_FAIL;
2078
2079         self->setAngularVelocity(velocity, false);
2080
2081         return PY_SET_ATTR_SUCCESS;
2082 }
2083
2084 PyObject* KX_GameObject::pyattr_get_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2085 {
2086 #ifdef USE_MATHUTILS
2087         return newVectorObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_LOCAL);
2088 #else
2089         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2090         return PyObjectFrom(GetAngularVelocity(true));
2091 #endif
2092 }
2093
2094 int KX_GameObject::pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2095 {
2096         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2097         MT_Vector3 velocity;
2098         if (!PyVecTo(value, velocity))
2099                 return PY_SET_ATTR_FAIL;
2100
2101         self->setAngularVelocity(velocity, true);
2102
2103         return PY_SET_ATTR_SUCCESS;
2104 }
2105
2106
2107 PyObject* KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2108 {
2109         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2110         SG_Node* sg_parent;
2111         if (self->GetSGNode() && (sg_parent = self->GetSGNode()->GetSGParent()) != NULL && sg_parent->IsSlowParent()) {
2112                 return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->GetTimeOffset());
2113         } else {
2114                 return PyFloat_FromDouble(0.0);
2115         }
2116 }
2117
2118 int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2119 {
2120         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2121         if (self->GetSGNode()) {
2122                 MT_Scalar val = PyFloat_AsDouble(value);
2123                 SG_Node* sg_parent= self->GetSGNode()->GetSGParent();
2124                 if (val < 0.0f) { /* also accounts for non float */
2125                         PyErr_SetString(PyExc_AttributeError, "gameOb.timeOffset = float: KX_GameObject, expected a float zero or above");
2126                         return PY_SET_ATTR_FAIL;
2127                 }
2128                 if (sg_parent && sg_parent->IsSlowParent())
2129                         static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->SetTimeOffset(val);
2130         }
2131         return PY_SET_ATTR_SUCCESS;
2132 }
2133
2134 PyObject* KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2135 {
2136         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2137         int state = 0;
2138         state |= self->GetState();
2139         return PyLong_FromSsize_t(state);
2140 }
2141
2142 int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2143 {
2144         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2145         int state_i = PyLong_AsSsize_t(value);
2146         unsigned int state = 0;
2147         
2148         if (state_i == -1 && PyErr_Occurred()) {
2149                 PyErr_SetString(PyExc_TypeError, "gameOb.state = int: KX_GameObject, expected an int bit field");
2150                 return PY_SET_ATTR_FAIL;
2151         }
2152         
2153         state |= state_i;
2154         if ((state & ((1<<30)-1)) == 0) {
2155                 PyErr_SetString(PyExc_AttributeError, "gameOb.state = int: KX_GameObject, state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
2156                 return PY_SET_ATTR_FAIL;
2157         }
2158         self->SetState(state);
2159         return PY_SET_ATTR_SUCCESS;
2160 }
2161
2162 PyObject* KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2163 {
2164         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2165         PyObject *meshes= PyList_New(self->m_meshes.size());
2166         int i;
2167         
2168         for(i=0; i < (int)self->m_meshes.size(); i++)
2169         {
2170                 KX_MeshProxy* meshproxy = new KX_MeshProxy(self->m_meshes[i]);
2171                 PyList_SET_ITEM(meshes, i, meshproxy->NewProxy(true));
2172         }
2173         
2174         return meshes;
2175 }
2176
2177 PyObject* KX_GameObject::pyattr_get_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2178 {
2179 #ifdef USE_MATHUTILS
2180         return newVectorObject_cb(BGE_PROXY_FROM_REF(self_v), 4, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_OBJECT_COLOR);
2181 #else
2182         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2183         return PyObjectFrom(self->GetObjectColor());
2184 #endif
2185 }
2186
2187 int KX_GameObject::pyattr_set_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2188 {
2189         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2190         MT_Vector4 obcolor;
2191         if (!PyVecTo(value, obcolor))
2192                 return PY_SET_ATTR_FAIL;
2193
2194         self->SetObjectColor(obcolor);
2195         return PY_SET_ATTR_SUCCESS;
2196 }
2197
2198 /* These are experimental! */
2199 PyObject* KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2200 {
2201         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_SENSORS);
2202 }
2203
2204 PyObject* KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2205 {
2206         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_CONTROLLERS);
2207 }
2208
2209 PyObject* KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2210 {
2211         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_ACTUATORS);
2212 }
2213 /* End experimental */
2214
2215 PyObject* KX_GameObject::pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2216 {
2217         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2218         return self->GetChildren()->NewProxy(true);
2219 }
2220
2221 PyObject* KX_GameObject::pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2222 {
2223         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2224         return self->GetChildrenRecursive()->NewProxy(true);
2225 }
2226
2227 PyObject* KX_GameObject::pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2228 {
2229         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2230         
2231         if(self->m_attr_dict==NULL)
2232                 self->m_attr_dict= PyDict_New();
2233         
2234         Py_INCREF(self->m_attr_dict);
2235         return self->m_attr_dict;
2236 }
2237
2238 PyObject* KX_GameObject::PyApplyForce(PyObject* args)
2239 {
2240         int local = 0;
2241         PyObject* pyvect;
2242
2243         if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) {
2244                 MT_Vector3 force;
2245                 if (PyVecTo(pyvect, force)) {
2246                         ApplyForce(force, (local!=0));
2247                         Py_RETURN_NONE;
2248                 }
2249         }
2250         return NULL;
2251 }
2252
2253 PyObject* KX_GameObject::PyApplyTorque(PyObject* args)
2254 {
2255         int local = 0;
2256         PyObject* pyvect;
2257
2258         if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) {
2259                 MT_Vector3 torque;
2260                 if (PyVecTo(pyvect, torque)) {
2261                         ApplyTorque(torque, (local!=0));
2262                         Py_RETURN_NONE;
2263                 }
2264         }
2265         return NULL;
2266 }
2267
2268 PyObject* KX_GameObject::PyApplyRotation(PyObject* args)
2269 {
2270         int local = 0;
2271         PyObject* pyvect;
2272
2273         if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) {
2274                 MT_Vector3 rotation;
2275                 if (PyVecTo(pyvect, rotation)) {
2276                         ApplyRotation(rotation, (local!=0));
2277                         Py_RETURN_NONE;
2278                 }
2279         }
2280         return NULL;
2281 }
2282
2283 PyObject* KX_GameObject::PyApplyMovement(PyObject* args)
2284 {
2285         int local = 0;
2286         PyObject* pyvect;
2287
2288         if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) {
2289                 MT_Vector3 movement;
2290                 if (PyVecTo(pyvect, movement)) {
2291                         ApplyMovement(movement, (local!=0));
2292                         Py_RETURN_NONE;
2293                 }
2294         }
2295         return NULL;
2296 }
2297
2298 PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* args)
2299 {
2300         // only can get the velocity if we have a physics object connected to us...
2301         int local = 0;
2302         if (PyArg_ParseTuple(args,"|i:getLinearVelocity",&local))
2303         {
2304                 return PyObjectFrom(GetLinearVelocity((local!=0)));
2305         }
2306         else
2307         {
2308                 return NULL;
2309         }
2310 }
2311
2312 PyObject* KX_GameObject::PySetLinearVelocity(PyObject* args)
2313 {
2314         int local = 0;
2315         PyObject* pyvect;
2316         
2317         if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) {
2318                 MT_Vector3 velocity;
2319                 if (PyVecTo(pyvect, velocity)) {
2320                         setLinearVelocity(velocity, (local!=0));
2321                         Py_RETURN_NONE;
2322                 }
2323         }
2324         return NULL;
2325 }
2326
2327 PyObject* KX_GameObject::PyGetAngularVelocity(PyObject* args)
2328 {
2329         // only can get the velocity if we have a physics object connected to us...
2330         int local = 0;
2331         if (PyArg_ParseTuple(args,"|i:getAngularVelocity",&local))
2332         {
2333                 return PyObjectFrom(GetAngularVelocity((local!=0)));
2334         }
2335         else
2336         {
2337                 return NULL;
2338         }
2339 }
2340
2341 PyObject* KX_GameObject::PySetAngularVelocity(PyObject* args)
2342 {
2343         int local = 0;
2344         PyObject* pyvect;
2345         
2346         if (PyArg_ParseTuple(args,"O|i:setAngularVelocity",&pyvect,&local)) {
2347                 MT_Vector3 velocity;
2348                 if (PyVecTo(pyvect, velocity)) {
2349                         setAngularVelocity(velocity, (local!=0));
2350                         Py_RETURN_NONE;
2351                 }
2352         }
2353         return NULL;
2354 }
2355
2356 PyObject* KX_GameObject::PySetVisible(PyObject* args)
2357 {
2358         int visible, recursive = 0;
2359         if (!PyArg_ParseTuple(args,"i|i:setVisible",&visible, &recursive))
2360                 return NULL;
2361         
2362         SetVisible(visible ? true:false, recursive ? true:false);
2363         UpdateBuckets(recursive ? true:false);
2364         Py_RETURN_NONE;
2365         
2366 }
2367
2368 PyObject* KX_GameObject::PySetOcclusion(PyObject* args)
2369 {
2370         int occlusion, recursive = 0;
2371         if (!PyArg_ParseTuple(args,"i|i:setOcclusion",&occlusion, &recursive))
2372                 return NULL;
2373         
2374         SetOccluder(occlusion ? true:false, recursive ? true:false);
2375         Py_RETURN_NONE;
2376 }
2377
2378 PyObject* KX_GameObject::PyGetVelocity(PyObject* args)
2379 {
2380         // only can get the velocity if we have a physics object connected to us...
2381         MT_Point3 point(0.0,0.0,0.0);
2382         PyObject* pypos = NULL;
2383         
2384         if (!PyArg_ParseTuple(args, "|O:getVelocity", &pypos) || (pypos && !PyVecTo(pypos, point)))
2385                 return NULL;
2386         
2387         if (m_pPhysicsController1)
2388         {
2389                 return PyObjectFrom(m_pPhysicsController1->GetVelocity(point));
2390         }
2391         else {
2392                 return PyObjectFrom(MT_Vector3(0.0,0.0,0.0));
2393         }
2394 }
2395
2396 PyObject* KX_GameObject::PyGetReactionForce()
2397 {
2398         // only can get the velocity if we have a physics object connected to us...
2399         
2400         // XXX - Currently not working with bullet intergration, see KX_BulletPhysicsController.cpp's getReactionForce
2401         /*
2402         if (GetPhysicsController())
2403                 return PyObjectFrom(GetPhysicsController()->getReactionForce());
2404         return PyObjectFrom(dummy_point);
2405         */
2406         
2407         return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
2408         
2409 }
2410
2411
2412
2413 PyObject* KX_GameObject::PyEnableRigidBody()
2414 {
2415         if(GetPhysicsController())
2416                 GetPhysicsController()->setRigidBody(true);
2417
2418         Py_RETURN_NONE;
2419 }
2420
2421
2422
2423 PyObject* KX_GameObject::PyDisableRigidBody()
2424 {
2425         if(GetPhysicsController())
2426                 GetPhysicsController()->setRigidBody(false);
2427
2428         Py_RETURN_NONE;
2429 }
2430
2431
2432 PyObject* KX_GameObject::PySetParent(PyObject* args)
2433 {
2434         KX_Scene *scene = KX_GetActiveScene();
2435         PyObject* pyobj;
2436         KX_GameObject *obj;
2437         int addToCompound=1, ghost=1;
2438         
2439         if (!PyArg_ParseTuple(args,"O|ii:setParent", &pyobj, &addToCompound, &ghost)) {
2440                 return NULL; // Python sets a simple error
2441         }
2442         if (!ConvertPythonToGameObject(pyobj, &obj, true, "gameOb.setParent(obj): KX_GameObject"))
2443                 return NULL;
2444         if (obj)
2445                 this->SetParent(scene, obj, addToCompound, ghost);
2446         Py_RETURN_NONE;
2447 }
2448
2449 PyObject* KX_GameObject::PyRemoveParent()
2450 {
2451         KX_Scene *scene = KX_GetActiveScene();
2452         
2453         this->RemoveParent(scene);
2454         Py_RETURN_NONE;
2455 }
2456
2457
2458 PyObject* KX_GameObject::PySetCollisionMargin(PyObject* value)
2459 {
2460         float collisionMargin = PyFloat_AsDouble(value);
2461         
2462         if (collisionMargin==-1 && PyErr_Occurred()) {
2463                 PyErr_SetString(PyExc_TypeError, "expected a float");
2464                 return NULL;
2465         }
2466         
2467         if (m_pPhysicsController1)
2468         {
2469                 m_pPhysicsController1->setMargin(collisionMargin);
2470                 Py_RETURN_NONE;
2471         }
2472         PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
2473         return NULL;
2474 }
2475
2476
2477
2478 PyObject* KX_GameObject::PyApplyImpulse(PyObject* args)
2479 {
2480         PyObject* pyattach;
2481         PyObject* pyimpulse;
2482         
2483         if (!m_pPhysicsController1)     {
2484                 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
2485                 return NULL;
2486         }
2487         
2488         if (PyArg_ParseTuple(args, "OO:applyImpulse", &pyattach, &pyimpulse))
2489         {
2490                 MT_Point3  attach;
2491                 MT_Vector3 impulse;
2492                 if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
2493                 {
2494                         m_pPhysicsController1->applyImpulse(attach, impulse);
2495                         Py_RETURN_NONE;
2496                 }
2497
2498         }
2499         
2500         return NULL;
2501 }
2502
2503
2504
2505 PyObject* KX_GameObject::PySuspendDynamics()
2506 {
2507         SuspendDynamics();
2508         Py_RETURN_NONE;
2509 }
2510
2511
2512
2513 PyObject* KX_GameObject::PyRestoreDynamics()
2514 {
2515         RestoreDynamics();
2516         Py_RETURN_NONE;
2517 }
2518
2519
2520 PyObject* KX_GameObject::PyAlignAxisToVect(PyObject* args)
2521 {
2522         PyObject* pyvect;
2523         int axis = 2; //z axis is the default
2524         float fac = 1.0;
2525         
2526         if (PyArg_ParseTuple(args,"O|if:alignAxisToVect",&pyvect,&axis, &fac))
2527         {
2528                 MT_Vector3 vect;
2529                 if (PyVecTo(pyvect, vect))
2530                 {
2531                         if (fac<=0.0) Py_RETURN_NONE; // Nothing to do.
2532                         if (fac> 1.0) fac= 1.0;
2533                         
2534                         AlignAxisToVect(vect,axis,fac);
2535                         NodeUpdateGS(0.f);
2536                         Py_RETURN_NONE;
2537                 }
2538         }
2539         return NULL;
2540 }
2541
2542 PyObject* KX_GameObject::PyGetAxisVect(PyObject* value)
2543 {
2544         MT_Vector3 vect;
2545         if (PyVecTo(value, vect))
2546         {
2547                 return PyObjectFrom(NodeGetWorldOrientation() * vect);
2548         }
2549         return NULL;
2550 }
2551
2552
2553 PyObject* KX_GameObject::PyGetPhysicsId()
2554 {
2555         KX_IPhysicsController* ctrl = GetPhysicsController();
2556         uint_ptr physid=0;
2557         if (ctrl)
2558         {
2559                 physid= (uint_ptr)ctrl->GetUserData();
2560         }
2561         return PyLong_FromSsize_t((long)physid);
2562 }
2563
2564 PyObject* KX_GameObject::PyGetPropertyNames()
2565 {
2566         PyObject *list=  ConvertKeysToPython();
2567         
2568         if(m_attr_dict) {
2569                 PyObject *key, *value;
2570                 Py_ssize_t pos = 0;
2571
2572                 while (PyDict_Next(m_attr_dict, &pos, &key, &value)) {
2573                         PyList_Append(list, key);
2574                 }
2575         }
2576         return list;
2577 }
2578
2579 KX_PYMETHODDEF_DOC_O(KX_GameObject, getDistanceTo,
2580 "getDistanceTo(other): get distance to another point/KX_GameObject")
2581 {
2582         MT_Point3 b;
2583         if (PyVecTo(value, b))
2584         {
2585                 return PyFloat_FromDouble(NodeGetWorldPosition().distance(b));
2586         }
2587         PyErr_Clear();
2588         
2589         KX_GameObject *other;
2590         if (ConvertPythonToGameObject(value, &other, false, "gameOb.getDistanceTo(value): KX_GameObject"))
2591         {
2592                 return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition()));
2593         }
2594         
2595         return NULL;
2596 }
2597
2598 KX_PYMETHODDEF_DOC_O(KX_GameObject, getVectTo,
2599 "getVectTo(other): get vector and the distance to another point/KX_GameObject\n"
2600 "Returns a 3-tuple with (distance,worldVector,localVector)\n")
2601 {
2602         MT_Point3 toPoint, fromPoint;
2603         MT_Vector3 toDir, locToDir;
2604         MT_Scalar distance;
2605
2606         PyObject *returnValue;
2607
2608         if (!PyVecTo(value, toPoint))
2609         {
2610                 PyErr_Clear();
2611                 
2612                 KX_GameObject *other;
2613                 if (ConvertPythonToGameObject(value, &other, false, "")) /* error will be overwritten */
2614                 {
2615                         toPoint = other->NodeGetWorldPosition();
2616                 } else
2617                 {
2618                         PyErr_SetString(PyExc_TypeError, "gameOb.getVectTo(other): KX_GameObject, expected a 3D Vector or KX_GameObject type");
2619                         return NULL;
2620                 }
2621         }
2622
2623         fromPoint = NodeGetWorldPosition();
2624         toDir = toPoint-fromPoint;
2625         distance = toDir.length();
2626
2627         if (MT_fuzzyZero(distance))
2628         {
2629                 //cout << "getVectTo() Error: Null vector!\n";
2630                 locToDir = toDir = MT_Vector3(0.0,0.0,0.0);
2631                 distance = 0.0;
2632         } else {
2633                 toDir.normalize();
2634                 locToDir = toDir * NodeGetWorldOrientation();
2635         }
2636         
2637         returnValue = PyTuple_New(3);
2638         if (returnValue) { // very unlikely to fail, python sets a memory error here.
2639                 PyTuple_SET_ITEM(returnValue, 0, PyFloat_FromDouble(distance));
2640                 PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(toDir));
2641                 PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(locToDir));
2642         }
2643         return returnValue;
2644 }
2645
2646 bool KX_GameObject::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
2647 {
2648         KX_GameObject* hitKXObj = client->m_gameobject;
2649         
2650         // if X-ray option is selected, the unwnted objects were not tested, so get here only with true hit
2651         // if not, all objects were tested and the front one may not be the correct one.
2652         if (m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
2653         {
2654                 m_pHitObject = hitKXObj;
2655                 return true;
2656         }
2657         // return true to stop RayCast::RayTest from looping, the above test was decisive
2658         // We would want to loop only if we want to get more than one hit point
2659         return true;
2660 }
2661
2662 /* this function is used to pre-filter the object before casting the ray on them.
2663    This is useful for "X-Ray" option when we want to see "through" unwanted object.
2664  */
2665 bool KX_GameObject::NeedRayCast(KX_ClientObjectInfo* client)
2666 {
2667         KX_GameObject* hitKXObj = client->m_gameobject;
2668         
2669         if (client->m_type > KX_ClientObjectInfo::ACTOR)
2670         {
2671                 // Unknown type of object, skip it.
2672                 // Should not occur as the sensor objects are filtered in RayTest()
2673                 printf("Invalid client type %d found in ray casting\n", client->m_type);
2674                 return false;
2675         }
2676         
2677         // if X-Ray option is selected, skip object that don't match the criteria as we see through them
2678         // if not, test all objects because we don't know yet which one will be on front
2679         if (!m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
2680         {
2681                 return true;
2682         }
2683         // skip the object
2684         return false;
2685 }
2686
2687 KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
2688 "rayCastTo(other,dist,prop): look towards another point/KX_GameObject and return first object hit within dist that matches prop\n"
2689 " prop = property name that object must have; can be omitted => detect any object\n"
2690 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to other\n"
2691 " other = 3-tuple or object reference")
2692 {
2693         MT_Point3 toPoint;
2694         PyObject* pyarg;
2695         float dist = 0.0f;
2696         char *propName = NULL;
2697
2698         if (!PyArg_ParseTuple(args,"O|fs:rayCastTo", &pyarg, &dist, &propName)) {
2699                 return NULL; // python sets simple error
2700         }
2701
2702         if (!PyVecTo(pyarg, toPoint))
2703         {
2704                 KX_GameObject *other;
2705                 PyErr_Clear();
2706                 
2707                 if (ConvertPythonToGameObject(pyarg, &other, false, "")) /* error will be overwritten */
2708                 {
2709                         toPoint = other->NodeGetWorldPosition();
2710                 } else
2711                 {
2712                         PyErr_SetString(PyExc_TypeError, "gameOb.rayCastTo(other,dist,prop): KX_GameObject, the first argument to rayCastTo must be a vector or a KX_GameObject");
2713                         return NULL;
2714                 }
2715         }
2716         MT_Point3 fromPoint = NodeGetWorldPosition();
2717         
2718         if (dist != 0.0f)
2719                 toPoint = fromPoint + dist * (toPoint-fromPoint).safe_normalized();
2720         
2721         PHY_IPhysicsEnvironment* pe = KX_GetActiveScene()->GetPhysicsEnvironment();
2722         KX_IPhysicsController *spc = GetPhysicsController();
2723         KX_GameObject *parent = GetParent();
2724         if (!spc && parent)
2725                 spc = parent->GetPhysicsController();
2726         if (parent)
2727                 parent->Release();
2728         
2729         m_pHitObject = NULL;
2730         if (propName)
2731                 m_testPropName = propName;
2732         else
2733                 m_testPropName.SetLength(0);
2734         KX_RayCast::Callback<KX_GameObject> callback(this,spc);
2735         KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
2736
2737         if (m_pHitObject)
2738                 return m_pHitObject->GetProxy();
2739         
2740         Py_RETURN_NONE;
2741 }
2742
2743 /* faster then Py_BuildValue since some scripts call raycast a lot */
2744 static PyObject *none_tuple_3()
2745 {
2746         PyObject *ret= PyTuple_New(3);
2747         PyTuple_SET_ITEM(ret, 0, Py_None);
2748         PyTuple_SET_ITEM(ret, 1, Py_None);
2749         PyTuple_SET_ITEM(ret, 2, Py_None);
2750         
2751         Py_INCREF(Py_None);
2752         Py_INCREF(Py_None);
2753         Py_INCREF(Py_None);
2754         return ret;
2755 }
2756 static PyObject *none_tuple_4()
2757 {
2758         PyObject *ret= PyTuple_New(4);
2759         PyTuple_SET_ITEM(ret, 0, Py_None);
2760         PyTuple_SET_ITEM(ret, 1, Py_None);
2761         PyTuple_SET_ITEM(ret, 2, Py_None);
2762         PyTuple_SET_ITEM(ret, 3, Py_None);
2763         
2764         Py_INCREF(Py_None);
2765         Py_INCREF(Py_None);
2766         Py_INCREF(Py_None);
2767         Py_INCREF(Py_None);
2768         return ret;
2769 }
2770
2771 static PyObject *none_tuple_5()
2772 {
2773         PyObject *ret= PyTuple_New(5);
2774         PyTuple_SET_ITEM(ret, 0, Py_None);
2775         PyTuple_SET_ITEM(ret, 1, Py_None);
2776         PyTuple_SET_ITEM(ret, 2, Py_None);
2777         PyTuple_SET_ITEM(ret, 3, Py_None);
2778         PyTuple_SET_ITEM(ret, 4, Py_None);
2779         
2780         Py_INCREF(Py_None);
2781         Py_INCREF(Py_None);
2782         Py_INCREF(Py_None);
2783         Py_INCREF(Py_None);
2784         Py_INCREF(Py_None);
2785         return ret;
2786 }
2787
2788 KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
2789                                    "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"
2790                                    " If no hit, return (None,None,None) or (None,None,None,None) or (None,None,None,None,None).\n"
2791 " to   = 3-tuple or object reference for destination of ray (if object, use center of object)\n"
2792 " from = 3-tuple or object reference for origin of ray (if object, use center of object)\n"
2793 "        Can be None or omitted => start from self object center\n"
2794 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to to\n"
2795 " prop = property name that object must have; can be omitted => detect any object\n"
2796 " face = normal option: 1=>return face normal; 0 or omitted => normal is oriented towards origin\n"
2797 " xray = X-ray option: 1=>skip objects that don't match prop; 0 or omitted => stop on first object\n"
2798 " poly = polygon option: 1=>return value is a 4-tuple and the 4th element is a KX_PolyProxy object\n"
2799 "                           which can be None if hit object has no mesh or if there is no hit\n"
2800 "                        2=>return value is a 5-tuple, the 4th element is the KX_PolyProxy object\n"
2801 "                           and the 5th element is the vector of UV coordinates at the hit point of the None if there is no UV mapping\n"
2802 "        If 0 or omitted, return value is a 3-tuple\n"
2803 "Note: The object on which you call this method matters: the ray will ignore it.\n"
2804 "      prop and xray option interact as follow:\n"
2805 "        prop off, xray off: return closest hit or no hit if there is no object on the full extend of the ray\n"
2806 "        prop off, xray on : idem\n"
2807 "        prop on,  xray off: return closest hit if it matches prop, no hit otherwise\n"
2808 "        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")
2809 {
2810         MT_Point3 toPoint;
2811         MT_Point3 fromPoint;
2812         PyObject* pyto;
2813         PyObject* pyfrom = NULL;
2814         float dist = 0.0f;
2815         char *propName = NULL;
2816         KX_GameObject *other;
2817         int face=0, xray=0, poly=0;
2818
2819         if (!PyArg_ParseTuple(args,"O|Ofsiii:rayCast", &pyto, &pyfrom, &dist, &propName, &face, &xray, &poly)) {
2820                 return NULL; // Python sets a simple error
2821         }
2822
2823         if (!PyVecTo(pyto, toPoint))
2824         {
2825                 PyErr_Clear();
2826                 
2827                 if (ConvertPythonToGameObject(pyto, &other, false, ""))  /* error will be overwritten */
2828                 {
2829                         toPoint = other->NodeGetWorldPosition();
2830                 } else
2831                 {
2832                         PyErr_SetString(PyExc_TypeError, "the first argument to rayCast must be a vector or a KX_GameObject");
2833                         return NULL;
2834                 }
2835         }
2836         if (!pyfrom || pyfrom == Py_None)
2837         {
2838                 fromPoint = NodeGetWorldPosition();
2839         }
2840         else if (!PyVecTo(pyfrom, fromPoint))
2841         {
2842                 PyErr_Clear();
2843                 
2844                 if (ConvertPythonToGameObject(pyfrom, &other, false, "")) /* error will be overwritten */
2845                 {
2846                         fromPoint = other->NodeGetWorldPosition();
2847                 } else
2848                 {
2849                         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");
2850                         return NULL;
2851                 }
2852         }
2853         
2854         if (dist != 0.0f) {
2855                 MT_Vector3 toDir = toPoint-fromPoint;
2856                 if (MT_fuzzyZero(toDir.length2())) {
2857                         //return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2858                         return none_tuple_3();
2859                 }
2860                 toDir.normalize();
2861                 toPoint = fromPoint + (dist) * toDir;
2862         } else if (MT_fuzzyZero((toPoint-fromPoint).length2())) {
2863                 //return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2864                 return none_tuple_3();
2865         }
2866         
2867         PHY_IPhysicsEnvironment* pe = KX_GetActiveScene()->GetPhysicsEnvironment();
2868         KX_IPhysicsController *spc = GetPhysicsController();
2869         KX_GameObject *parent = GetParent();
2870         if (!spc && parent)
2871                 spc = parent->GetPhysicsController();
2872         if (parent)
2873                 parent->Release();
2874         
2875         m_pHitObject = NULL;
2876         if (propName)
2877                 m_testPropName = propName;
2878         else
2879                 m_testPropName.SetLength(0);
2880         m_xray = xray;
2881         // to get the hit results
2882         KX_RayCast::Callback<KX_GameObject> callback(this,spc,NULL,face,(poly==2));
2883         KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
2884
2885         if (m_pHitObject)
2886         {
2887                 PyObject* returnValue = (poly==2) ? PyTuple_New(5) : (poly) ? PyTuple_New(4) : PyTuple_New(3);
2888                 if (returnValue) { // unlikely this would ever fail, if it does python sets an error
2889                         PyTuple_SET_ITEM(returnValue, 0, m_pHitObject->GetProxy());
2890                         PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(callback.m_hitPoint));
2891                         PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(callback.m_hitNormal));
2892                         if (poly)
2893                         {
2894                                 if (callback.m_hitMesh)
2895                                 {
2896                                         // if this field is set, then we can trust that m_hitPolygon is a valid polygon
2897                                         RAS_Polygon* polygon = callback.m_hitMesh->GetPolygon(callback.m_hitPolygon);
2898                                         KX_PolyProxy* polyproxy = new KX_PolyProxy(callback.m_hitMesh, polygon);
2899                                         PyTuple_SET_ITEM(returnValue, 3, polyproxy->NewProxy(true));
2900                                         if (poly == 2)
2901                                         {
2902                                                 if (callback.m_hitUVOK)
2903                                                         PyTuple_SET_ITEM(returnValue, 4, PyObjectFrom(callback.m_hitUV));
2904                                                 else {
2905                                                         Py_INCREF(Py_None);
2906                                                         PyTuple_SET_ITEM(returnValue, 4, Py_None);
2907                                                 }
2908                                         }
2909                                 }
2910                                 else
2911                                 {
2912                                         Py_INCREF(Py_None);
2913                                         PyTuple_SET_ITEM(returnValue, 3, Py_None);
2914                                         if (poly==2)
2915                                         {
2916                                                 Py_INCREF(Py_None);
2917                                                 PyTuple_SET_ITEM(returnValue, 4, Py_None);
2918                                         }
2919                                 }
2920                         }
2921                 }
2922                 return returnValue;
2923         }
2924         // no hit
2925         if (poly == 2)
2926                 return none_tuple_5();
2927         else if (poly)
2928                 return none_tuple_4();
2929         else
2930                 return none_tuple_3();
2931 }
2932
2933 KX_PYMETHODDEF_DOC_VARARGS(KX_GameObject, sendMessage, 
2934                                                    "sendMessage(subject, [body, to])\n"
2935 "sends a message in same manner as a message actuator"
2936 "subject = Subject of the message (string)"
2937 "body = Message body (string)"
2938 "to = Name of object to send the message to")
2939 {
2940         KX_Scene *scene = KX_GetActiveScene();
2941         char* subject;
2942         char* body = (char *)"";
2943         char* to = (char *)"";
2944         const STR_String& from = GetName();
2945
2946         if (!PyArg_ParseTuple(args, "s|ss:sendMessage", &subject, &body, &to))
2947                 return NULL;
2948         
2949         scene->GetNetworkScene()->SendMessage(to, from, subject, body);
2950         Py_RETURN_NONE;
2951 }
2952
2953 /* dict style access */
2954
2955
2956 /* Matches python dict.get(key, [default]) */
2957 PyObject* KX_GameObject::Pyget(PyObject *args)
2958 {
2959         PyObject *key;
2960         PyObject* def = Py_None;
2961         PyObject* ret;
2962
2963         if (!PyArg_ParseTuple(args, "O|O:get", &key, &def))
2964                 return NULL;
2965         
2966         
2967         if(PyUnicode_Check(key)) {
2968                 CValue *item = GetProperty(_PyUnicode_AsString(key));
2969                 if (item) {
2970                         ret = item->ConvertValueToPython();
2971                         if(ret)
2972                                 return ret;
2973                         else
2974                                 return item->GetProxy();
2975                 }
2976         }
2977         
2978         if (m_attr_dict && (ret=PyDict_GetItem(m_attr_dict, key))) {
2979                 Py_INCREF(ret);
2980                 return ret;
2981         }
2982         
2983         Py_INCREF(def);
2984         return def;
2985 }
2986
2987 bool ConvertPythonToGameObject(PyObject * value, KX_GameObject **object, bool py_none_ok, const char *error_prefix)
2988 {
2989         if (value==NULL) {
2990                 PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix);
2991                 *object = NULL;
2992                 return false;
2993         }
2994                 
2995         if (value==Py_None) {
2996                 *object = NULL;
2997                 
2998                 if (py_none_ok) {
2999                         return true;
3000                 } else {
3001                         PyErr_Format(PyExc_TypeError, "%s, expected KX_GameObject or a KX_GameObject name, None is invalid", error_prefix);
3002                         return false;
3003                 }
3004         }
3005         
3006         if (PyUnicode_Check(value)) {
3007                 *object = (KX_GameObject*)SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String( _PyUnicode_AsString(value) ));
3008                 
3009                 if (*object) {
3010                         return true;
3011                 } else {
3012                         PyErr_Format(PyExc_ValueError, "%s, requested name \"%s\" did not match any KX_GameObject in this scene", error_prefix, _PyUnicode_AsString(value));
3013                         return false;
3014                 }
3015         }
3016         
3017         if (    PyObject_TypeCheck(value, &KX_GameObject::Type) ||
3018                         PyObject_TypeCheck(value, &KX_LightObject::Type)        ||
3019                         PyObject_TypeCheck(value, &KX_Camera::Type)     )
3020         {
3021                 *object = static_cast<KX_GameObject*>BGE_PROXY_REF(value);
3022                 
3023                 /* sets the error */
3024                 if (*object==NULL) {
3025                         PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix);
3026                         return false;
3027                 }
3028                 
3029                 return true;
3030         }
3031         
3032         *object = NULL;
3033         
3034         if (py_none_ok) {
3035                 PyErr_Format(PyExc_TypeError, "%s, expect a KX_GameObject, a string or None", error_prefix);
3036         } else {
3037                 PyErr_Format(PyExc_TypeError, "%s, expect a KX_GameObject or a string", error_prefix);
3038         }
3039         
3040         return false;
3041 }
3042 #endif // DISABLE_PYTHON