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