BGE: some more cleanup, remove useless ReplicaSetName(), move code to ProcessReplica.
[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_RO_FUNCTION("worldOrientation",KX_GameObject,pyattr_get_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
1196 Py_ssize_t KX_GameObject::Map_Len(PyObject* self_v)
1197 {
1198         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1199         
1200         if (self==NULL) /* not sure what to do here */
1201                 return 0;
1202         
1203         Py_ssize_t len= self->GetPropertyCount();
1204         if(self->m_attr_dict)
1205                 len += PyDict_Size(self->m_attr_dict);
1206         return len;
1207 }
1208
1209
1210 PyObject *KX_GameObject::Map_GetItem(PyObject *self_v, PyObject *item)
1211 {
1212         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1213         const char *attr_str= PyString_AsString(item);
1214         CValue* resultattr;
1215         PyObject* pyconvert;
1216         
1217         if (self==NULL) {
1218                 PyErr_SetString(PyExc_RuntimeError, BGE_PROXY_ERROR_MSG);
1219                 return NULL;
1220         }
1221         
1222         /* first see if the attributes a string and try get the cvalue attribute */
1223         if(attr_str && (resultattr=self->GetProperty(attr_str))) {
1224                 pyconvert = resultattr->ConvertValueToPython();                 
1225                 return pyconvert ? pyconvert:resultattr->GetProxy();
1226         }
1227         /* no CValue attribute, try get the python only m_attr_dict attribute */
1228         else if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
1229                 
1230                 if (attr_str)
1231                         PyErr_Clear();
1232                 Py_INCREF(pyconvert);
1233                 return pyconvert;
1234         }
1235         else {
1236                 if(attr_str)    PyErr_Format(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key \"%s\" does not exist", attr_str);
1237                 else                    PyErr_SetString(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key does not exist");
1238                 return NULL;
1239         }
1240                 
1241 }
1242
1243
1244 int KX_GameObject::Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
1245 {
1246         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1247         const char *attr_str= PyString_AsString(key);
1248         if(attr_str==NULL)
1249                 PyErr_Clear();
1250         
1251         if (self==NULL) {
1252                 PyErr_SetString(PyExc_RuntimeError, BGE_PROXY_ERROR_MSG);
1253                 return -1;
1254         }
1255         
1256         if (val==NULL) { /* del ob["key"] */
1257                 int del= 0;
1258                 
1259                 /* try remove both just incase */
1260                 if(attr_str)
1261                         del |= (self->RemoveProperty(attr_str)==true) ? 1:0;
1262                 
1263                 if(self->m_attr_dict)
1264                         del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
1265                 
1266                 if (del==0) {
1267                         if(attr_str)    PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" could not be set", attr_str);
1268                         else                    PyErr_SetString(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key could not be set");
1269                         return -1;
1270                 }
1271                 else if (self->m_attr_dict) {
1272                         PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
1273                 }
1274         }
1275         else { /* ob["key"] = value */
1276                 int set= 0;
1277                 
1278                 /* as CValue */
1279                 if(attr_str)
1280                 {
1281                         CValue* vallie = self->ConvertPythonToValue(val);
1282                         
1283                         if(vallie)
1284                         {
1285                                 CValue* oldprop = self->GetProperty(attr_str);
1286                                 
1287                                 if (oldprop)
1288                                         oldprop->SetValue(vallie);
1289                                 else
1290                                         self->SetProperty(attr_str, vallie);
1291                                 
1292                                 vallie->Release();
1293                                 set= 1;
1294                                 
1295                                 /* try remove dict value to avoid double ups */
1296                                 if (self->m_attr_dict){
1297                                         if (PyDict_DelItem(self->m_attr_dict, key) != 0)
1298                                                 PyErr_Clear();
1299                                 }
1300                         }
1301                         else {
1302                                 PyErr_Clear();
1303                         }
1304                 }
1305                 
1306                 if(set==0)
1307                 {
1308                         if (self->m_attr_dict==NULL) /* lazy init */
1309                                 self->m_attr_dict= PyDict_New();
1310                         
1311                         
1312                         if(PyDict_SetItem(self->m_attr_dict, key, val)==0)
1313                         {
1314                                 if(attr_str)
1315                                         self->RemoveProperty(attr_str); /* overwrite the CValue if it exists */
1316                                 set= 1;
1317                         }
1318                         else {
1319                                 if(attr_str)    PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" not be added to internal dictionary", attr_str);
1320                                 else                    PyErr_SetString(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key not be added to internal dictionary");
1321                         }
1322                 }
1323                 
1324                 if(set==0)
1325                         return -1; /* pythons error value */
1326                 
1327         }
1328         
1329         return 0; /* success */
1330 }
1331
1332
1333 PyMappingMethods KX_GameObject::Mapping = {
1334         (lenfunc)KX_GameObject::Map_Len,                        /*inquiry mp_length */
1335         (binaryfunc)KX_GameObject::Map_GetItem,         /*binaryfunc mp_subscript */
1336         (objobjargproc)KX_GameObject::Map_SetItem,      /*objobjargproc mp_ass_subscript */
1337 };
1338
1339
1340 PyTypeObject KX_GameObject::Type = {
1341         PyObject_HEAD_INIT(NULL)
1342                 0,
1343                 "KX_GameObject",
1344                 sizeof(PyObjectPlus_Proxy),
1345                 0,
1346                 py_base_dealloc,
1347                 0,
1348                 0,
1349                 0,
1350                 0,
1351                 py_base_repr,
1352                 0,0,
1353                 &Mapping,
1354                 0,0,0,
1355                 py_base_getattro,
1356                 py_base_setattro,
1357                 0,0,0,0,0,0,0,0,0,
1358                 Methods
1359 };
1360
1361
1362
1363
1364
1365
1366 PyParentObject KX_GameObject::Parents[] = {
1367         &KX_GameObject::Type,
1368                 &SCA_IObject::Type,
1369                 &CValue::Type,
1370                 NULL
1371 };
1372
1373 PyObject* KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1374 {
1375         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1376         return PyString_FromString(self->GetName().ReadPtr());
1377 }
1378
1379 PyObject* KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1380 {
1381         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1382         KX_GameObject* parent = self->GetParent();
1383         if (parent)
1384                 return parent->GetProxy();
1385         Py_RETURN_NONE;
1386 }
1387
1388 PyObject* KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1389 {
1390         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1391         KX_IPhysicsController *spc = self->GetPhysicsController();
1392         return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0f);
1393 }
1394
1395 int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1396 {
1397         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1398         KX_IPhysicsController *spc = self->GetPhysicsController();
1399         MT_Scalar val = PyFloat_AsDouble(value);
1400         if (val < 0.0f) { /* also accounts for non float */
1401                 PyErr_SetString(PyExc_AttributeError, "gameOb.mass = float: KX_GameObject, expected a float zero or above");
1402                 return 1;
1403         }
1404
1405         if (spc)
1406                 spc->SetMass(val);
1407
1408         return 0;
1409 }
1410
1411 PyObject* KX_GameObject::pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1412 {
1413         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1414         KX_IPhysicsController *spc = self->GetPhysicsController();
1415         return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
1416 }
1417
1418 int KX_GameObject::pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1419 {
1420         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1421         KX_IPhysicsController *spc = self->GetPhysicsController();
1422         MT_Scalar val = PyFloat_AsDouble(value);
1423         if (val < 0.0f) { /* also accounts for non float */
1424                 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMin = float: KX_GameObject, expected a float zero or above");
1425                 return 1;
1426         }
1427
1428         if (spc)
1429                 spc->SetLinVelocityMin(val);
1430
1431         return 0;
1432 }
1433
1434 PyObject* KX_GameObject::pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1435 {
1436         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1437         KX_IPhysicsController *spc = self->GetPhysicsController();
1438         return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
1439 }
1440
1441 int KX_GameObject::pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1442 {
1443         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1444         KX_IPhysicsController *spc = self->GetPhysicsController();
1445         MT_Scalar val = PyFloat_AsDouble(value);
1446         if (val < 0.0f) { /* also accounts for non float */
1447                 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMax = float: KX_GameObject, expected a float zero or above");
1448                 return 1;
1449         }
1450
1451         if (spc)
1452                 spc->SetLinVelocityMax(val);
1453
1454         return 0;
1455 }
1456
1457
1458 PyObject* KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1459 {
1460         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1461         return PyBool_FromLong(self->GetVisible());
1462 }
1463
1464 int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1465 {
1466         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1467         int param = PyObject_IsTrue( value );
1468         if (param == -1) {
1469                 PyErr_SetString(PyExc_AttributeError, "gameOb.visible = bool: KX_GameObject, expected True or False");
1470                 return 1;
1471         }
1472
1473         self->SetVisible(param, false);
1474         self->UpdateBuckets(false);
1475         return 0;
1476 }
1477
1478 PyObject* KX_GameObject::pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1479 {
1480         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1481         return PyObjectFrom(self->NodeGetWorldPosition());
1482 }
1483
1484 int KX_GameObject::pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1485 {
1486         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1487         MT_Point3 pos;
1488         if (!PyVecTo(value, pos))
1489                 return 1;
1490         
1491         self->NodeSetWorldPosition(pos);
1492         self->NodeUpdateGS(0.f);
1493         return 0;
1494 }
1495
1496 PyObject* KX_GameObject::pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1497 {
1498         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1499         if (self->GetSGNode())
1500                 return PyObjectFrom(self->GetSGNode()->GetLocalPosition());
1501         else
1502                 return PyObjectFrom(dummy_point);
1503 }
1504
1505 int KX_GameObject::pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1506 {
1507         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1508         MT_Point3 pos;
1509         if (!PyVecTo(value, pos))
1510                 return 1;
1511         
1512         self->NodeSetLocalPosition(pos);
1513         self->NodeUpdateGS(0.f);
1514         return 0;
1515 }
1516
1517 PyObject* KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1518 {
1519         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1520         if (self->GetPhysicsController())
1521         {
1522                 return PyObjectFrom(self->GetPhysicsController()->GetLocalInertia());
1523         }
1524         return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
1525 }
1526
1527 PyObject* KX_GameObject::pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1528 {
1529         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1530         return PyObjectFrom(self->NodeGetWorldOrientation());
1531 }
1532
1533 PyObject* KX_GameObject::pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1534 {
1535         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1536         if (self->GetSGNode())
1537                 return PyObjectFrom(self->GetSGNode()->GetLocalOrientation());
1538         else
1539                 return PyObjectFrom(dummy_orientation);
1540 }
1541
1542 int KX_GameObject::pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1543 {
1544         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1545         
1546         /* if value is not a sequence PyOrientationTo makes an error */
1547         MT_Matrix3x3 rot;
1548         if (!PyOrientationTo(value, rot, "gameOb.orientation = sequence: KX_GameObject, "))
1549                 return NULL;
1550
1551         self->NodeSetLocalOrientation(rot);
1552         self->NodeUpdateGS(0.f);
1553         return 0;
1554 }
1555
1556 PyObject* KX_GameObject::pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1557 {
1558         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1559         return PyObjectFrom(self->NodeGetWorldScaling());
1560 }
1561
1562 PyObject* KX_GameObject::pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1563 {
1564         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1565         if (self->GetSGNode())
1566                 return PyObjectFrom(self->GetSGNode()->GetLocalScale());
1567         else
1568                 return PyObjectFrom(dummy_scaling);
1569 }
1570
1571 int KX_GameObject::pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1572 {
1573         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1574         MT_Vector3 scale;
1575         if (!PyVecTo(value, scale))
1576                 return 1;
1577
1578         self->NodeSetLocalScale(scale);
1579         self->NodeUpdateGS(0.f);
1580         return 0;
1581 }
1582
1583 PyObject* KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1584 {
1585         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1586         SG_Node* sg_parent;
1587         if (self->GetSGNode() && (sg_parent = self->GetSGNode()->GetSGParent()) != NULL && sg_parent->IsSlowParent()) {
1588                 return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->GetTimeOffset());
1589         } else {
1590                 return PyFloat_FromDouble(0.0);
1591         }
1592 }
1593
1594 int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1595 {
1596         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1597         if (self->GetSGNode()) {
1598                 MT_Scalar val = PyFloat_AsDouble(value);
1599                 SG_Node* sg_parent= self->GetSGNode()->GetSGParent();
1600                 if (val < 0.0f) { /* also accounts for non float */
1601                         PyErr_SetString(PyExc_AttributeError, "gameOb.timeOffset = float: KX_GameObject, expected a float zero or above");
1602                         return 1;
1603                 }
1604                 if (sg_parent && sg_parent->IsSlowParent())
1605                         static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->SetTimeOffset(val);
1606         }
1607         return 0;
1608 }
1609
1610 PyObject* KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1611 {
1612         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1613         int state = 0;
1614         state |= self->GetState();
1615         return PyInt_FromLong(state);
1616 }
1617
1618 int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1619 {
1620         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1621         int state_i = PyInt_AsLong(value);
1622         unsigned int state = 0;
1623         
1624         if (state_i == -1 && PyErr_Occurred()) {
1625                 PyErr_SetString(PyExc_TypeError, "gameOb.state = int: KX_GameObject, expected an int bit field");
1626                 return 1;
1627         }
1628         
1629         state |= state_i;
1630         if ((state & ((1<<30)-1)) == 0) {
1631                 PyErr_SetString(PyExc_AttributeError, "gameOb.state = int: KX_GameObject, state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
1632                 return 1;
1633         }
1634         self->SetState(state);
1635         return 0;
1636 }
1637
1638 PyObject* KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1639 {
1640         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1641         PyObject *meshes= PyList_New(self->m_meshes.size());
1642         int i;
1643         
1644         for(i=0; i < (int)self->m_meshes.size(); i++)
1645         {
1646                 KX_MeshProxy* meshproxy = new KX_MeshProxy(self->m_meshes[i]);
1647                 PyList_SET_ITEM(meshes, i, meshproxy->GetProxy());
1648         }
1649         
1650         return meshes;
1651 }
1652
1653 /* experemental! */
1654 PyObject* KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1655 {
1656         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1657         SCA_SensorList& sensors= self->GetSensors();
1658         PyObject* resultlist = PyList_New(sensors.size());
1659         
1660         for (unsigned int index=0;index<sensors.size();index++)
1661                 PyList_SET_ITEM(resultlist, index, sensors[index]->GetProxy());
1662         
1663         return resultlist;
1664 }
1665
1666 PyObject* KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1667 {
1668         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1669         SCA_ControllerList& controllers= self->GetControllers();
1670         PyObject* resultlist = PyList_New(controllers.size());
1671         
1672         for (unsigned int index=0;index<controllers.size();index++)
1673                 PyList_SET_ITEM(resultlist, index, controllers[index]->GetProxy());
1674         
1675         return resultlist;
1676 }
1677
1678 PyObject* KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1679 {
1680         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1681         SCA_ActuatorList& actuators= self->GetActuators();
1682         PyObject* resultlist = PyList_New(actuators.size());
1683         
1684         for (unsigned int index=0;index<actuators.size();index++)
1685                 PyList_SET_ITEM(resultlist, index, actuators[index]->GetProxy());
1686         
1687         return resultlist;
1688 }
1689
1690 /* We need these because the macros have a return in them */
1691 PyObject* KX_GameObject::py_getattro__internal(PyObject *attr)
1692 {
1693         py_getattro_up(SCA_IObject);
1694 }
1695
1696 int KX_GameObject::py_setattro__internal(PyObject *attr, PyObject *value)       // py_setattro method
1697 {
1698         py_setattro_up(SCA_IObject);
1699 }
1700
1701
1702 PyObject* KX_GameObject::py_getattro(PyObject *attr)
1703 {
1704         PyObject *object= py_getattro__internal(attr);
1705         
1706         if (object==NULL && m_attr_dict)
1707         {
1708                 /* backup the exception incase the attr doesnt exist in the dict either */
1709                 PyObject *err_type, *err_value, *err_tb;
1710                 PyErr_Fetch(&err_type, &err_value, &err_tb);
1711                 
1712                 object= PyDict_GetItem(m_attr_dict, attr);
1713                 if (object) {
1714                         Py_INCREF(object);
1715                         
1716                         PyErr_Clear();
1717                         Py_XDECREF( err_type );
1718                         Py_XDECREF( err_value );
1719                         Py_XDECREF( err_tb );
1720                 }
1721                 else {
1722                         PyErr_Restore(err_type, err_value, err_tb); /* use the error from the parent function */
1723                 }
1724         }
1725         return object;
1726 }
1727
1728 PyObject* KX_GameObject::py_getattro_dict() {
1729         //py_getattro_dict_up(SCA_IObject);
1730         PyObject *dict= py_getattr_dict(SCA_IObject::py_getattro_dict(), Type.tp_dict);
1731         if(dict==NULL)
1732                 return NULL;
1733         
1734         /* normally just return this but KX_GameObject has some more items */
1735
1736         
1737         /* Not super fast getting as a list then making into dict keys but its only for dir() */
1738         PyObject *list= ConvertKeysToPython();
1739         if(list)
1740         {
1741                 int i;
1742                 for(i=0; i<PyList_Size(list); i++)
1743                         PyDict_SetItem(dict, PyList_GET_ITEM(list, i), Py_None);
1744         }
1745         else
1746                 PyErr_Clear();
1747         
1748         Py_DECREF(list);
1749         
1750         /* Add m_attr_dict if we have it */
1751         if(m_attr_dict)
1752                 PyDict_Update(dict, m_attr_dict);
1753         
1754         return dict;
1755 }
1756
1757 int KX_GameObject::py_setattro(PyObject *attr, PyObject *value) // py_setattro method
1758 {
1759         int ret;
1760         
1761         ret= py_setattro__internal(attr, value);
1762         
1763         if (ret==PY_SET_ATTR_SUCCESS) {
1764                 /* remove attribute in our own dict to avoid double ups */
1765                 /* NOTE: Annoying that we also do this for setting builtin attributes like mass and visibility :/ */
1766                 if (m_attr_dict) {
1767                         if (PyDict_DelItem(m_attr_dict, attr) != 0)
1768                                 PyErr_Clear();
1769                 }
1770         }
1771         
1772         if (ret==PY_SET_ATTR_COERCE_FAIL) {
1773                 /* CValue attribute exists, remove CValue and add PyDict value */
1774                 RemoveProperty(STR_String(PyString_AsString(attr)));
1775                 ret= PY_SET_ATTR_MISSING;
1776         }
1777         
1778         if (ret==PY_SET_ATTR_MISSING) {
1779                 /* Lazy initialization */
1780                 if (m_attr_dict==NULL)
1781                         m_attr_dict = PyDict_New();
1782                 
1783                 if (PyDict_SetItem(m_attr_dict, attr, value)==0) {
1784                         PyErr_Clear();
1785                         ret= PY_SET_ATTR_SUCCESS;
1786                 }
1787                 else {
1788                         PyErr_Format(PyExc_AttributeError, "gameOb.myAttr = value: KX_GameObject, failed assigning value to internal dictionary");
1789                         ret= PY_SET_ATTR_FAIL;
1790                 }
1791         }
1792         
1793         return ret;     
1794 }
1795
1796
1797 int     KX_GameObject::py_delattro(PyObject *attr)
1798 {
1799         char *attr_str= PyString_AsString(attr); 
1800         
1801         if (RemoveProperty(STR_String(attr_str))) // XXX - should call CValues instead but its only 2 lines here
1802                 return 0;
1803         
1804         if (m_attr_dict && (PyDict_DelItem(m_attr_dict, attr) == 0))
1805                 return 0;
1806         
1807         PyErr_Format(PyExc_AttributeError, "del gameOb.myAttr: KX_GameObject, attribute \"%s\" dosnt exist", attr_str);
1808         return 1;
1809 }
1810
1811
1812 PyObject* KX_GameObject::PyApplyForce(PyObject* args)
1813 {
1814         int local = 0;
1815         PyObject* pyvect;
1816
1817         if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) {
1818                 MT_Vector3 force;
1819                 if (PyVecTo(pyvect, force)) {
1820                         ApplyForce(force, (local!=0));
1821                         Py_RETURN_NONE;
1822                 }
1823         }
1824         return NULL;
1825 }
1826
1827 PyObject* KX_GameObject::PyApplyTorque(PyObject* args)
1828 {
1829         int local = 0;
1830         PyObject* pyvect;
1831
1832         if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) {
1833                 MT_Vector3 torque;
1834                 if (PyVecTo(pyvect, torque)) {
1835                         ApplyTorque(torque, (local!=0));
1836                         Py_RETURN_NONE;
1837                 }
1838         }
1839         return NULL;
1840 }
1841
1842 PyObject* KX_GameObject::PyApplyRotation(PyObject* args)
1843 {
1844         int local = 0;
1845         PyObject* pyvect;
1846
1847         if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) {
1848                 MT_Vector3 rotation;
1849                 if (PyVecTo(pyvect, rotation)) {
1850                         ApplyRotation(rotation, (local!=0));
1851                         Py_RETURN_NONE;
1852                 }
1853         }
1854         return NULL;
1855 }
1856
1857 PyObject* KX_GameObject::PyApplyMovement(PyObject* args)
1858 {
1859         int local = 0;
1860         PyObject* pyvect;
1861
1862         if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) {
1863                 MT_Vector3 movement;
1864                 if (PyVecTo(pyvect, movement)) {
1865                         ApplyMovement(movement, (local!=0));
1866                         Py_RETURN_NONE;
1867                 }
1868         }
1869         return NULL;
1870 }
1871
1872 PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* args)
1873 {
1874         // only can get the velocity if we have a physics object connected to us...
1875         int local = 0;
1876         if (PyArg_ParseTuple(args,"|i:getLinearVelocity",&local))
1877         {
1878                 return PyObjectFrom(GetLinearVelocity((local!=0)));
1879         }
1880         else
1881         {
1882                 return NULL;
1883         }
1884 }
1885
1886 PyObject* KX_GameObject::PySetLinearVelocity(PyObject* args)
1887 {
1888         int local = 0;
1889         PyObject* pyvect;
1890         
1891         if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) {
1892                 MT_Vector3 velocity;
1893                 if (PyVecTo(pyvect, velocity)) {
1894                         setLinearVelocity(velocity, (local!=0));
1895                         Py_RETURN_NONE;
1896                 }
1897         }
1898         return NULL;
1899 }
1900
1901 PyObject* KX_GameObject::PyGetAngularVelocity(PyObject* args)
1902 {
1903         // only can get the velocity if we have a physics object connected to us...
1904         int local = 0;
1905         if (PyArg_ParseTuple(args,"|i:getAngularVelocity",&local))
1906         {
1907                 return PyObjectFrom(GetAngularVelocity((local!=0)));
1908         }
1909         else
1910         {
1911                 return NULL;
1912         }
1913 }
1914
1915 PyObject* KX_GameObject::PySetAngularVelocity(PyObject* args)
1916 {
1917         int local = 0;
1918         PyObject* pyvect;
1919         
1920         if (PyArg_ParseTuple(args,"O|i:setAngularVelocity",&pyvect,&local)) {
1921                 MT_Vector3 velocity;
1922                 if (PyVecTo(pyvect, velocity)) {
1923                         setAngularVelocity(velocity, (local!=0));
1924                         Py_RETURN_NONE;
1925                 }
1926         }
1927         return NULL;
1928 }
1929
1930 PyObject* KX_GameObject::PySetVisible(PyObject* args)
1931 {
1932         int visible, recursive = 0;
1933         if (!PyArg_ParseTuple(args,"i|i:setVisible",&visible, &recursive))
1934                 return NULL;
1935         
1936         SetVisible(visible ? true:false, recursive ? true:false);
1937         UpdateBuckets(recursive ? true:false);
1938         Py_RETURN_NONE;
1939         
1940 }
1941
1942 PyObject* KX_GameObject::PySetOcclusion(PyObject* args)
1943 {
1944         int occlusion, recursive = 0;
1945         if (!PyArg_ParseTuple(args,"i|i:setOcclusion",&occlusion, &recursive))
1946                 return NULL;
1947         
1948         SetOccluder(occlusion ? true:false, recursive ? true:false);
1949         Py_RETURN_NONE;
1950 }
1951
1952 PyObject* KX_GameObject::PyGetVisible()
1953 {
1954         ShowDeprecationWarning("getVisible()", "the visible property");
1955         return PyInt_FromLong(m_bVisible);      
1956 }
1957
1958 PyObject* KX_GameObject::PyGetState()
1959 {
1960         ShowDeprecationWarning("getState()", "the state property");
1961         int state = 0;
1962         state |= GetState();
1963         return PyInt_FromLong(state);
1964 }
1965
1966 PyObject* KX_GameObject::PySetState(PyObject* value)
1967 {
1968         ShowDeprecationWarning("setState()", "the state property");
1969         int state_i = PyInt_AsLong(value);
1970         unsigned int state = 0;
1971         
1972         if (state_i == -1 && PyErr_Occurred()) {
1973                 PyErr_SetString(PyExc_TypeError, "expected an int bit field");
1974                 return NULL;
1975         }
1976         
1977         state |= state_i;
1978         if ((state & ((1<<30)-1)) == 0) {
1979                 PyErr_SetString(PyExc_AttributeError, "The state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
1980                 return NULL;
1981         }
1982         SetState(state);
1983         
1984         Py_RETURN_NONE;
1985 }
1986
1987 PyObject* KX_GameObject::PyGetVelocity(PyObject* args)
1988 {
1989         // only can get the velocity if we have a physics object connected to us...
1990         MT_Point3 point(0.0,0.0,0.0);
1991         PyObject* pypos = NULL;
1992         
1993         if (PyArg_ParseTuple(args, "|O:getVelocity", &pypos))
1994         {
1995                 if (pypos)
1996                         PyVecTo(pypos, point);
1997         }
1998         else {
1999                 return NULL;
2000         }
2001         
2002         if (m_pPhysicsController1)
2003         {
2004                 return PyObjectFrom(m_pPhysicsController1->GetVelocity(point));
2005         }
2006         else {
2007                 return PyObjectFrom(MT_Vector3(0.0,0.0,0.0));
2008         }
2009 }
2010
2011
2012
2013 PyObject* KX_GameObject::PyGetMass()
2014 {
2015         ShowDeprecationWarning("getMass()", "the mass property");
2016         return PyFloat_FromDouble((GetPhysicsController() != NULL) ? GetPhysicsController()->GetMass() : 0.0f);
2017 }
2018
2019 PyObject* KX_GameObject::PyGetReactionForce()
2020 {
2021         // only can get the velocity if we have a physics object connected to us...
2022         
2023         // XXX - Currently not working with bullet intergration, see KX_BulletPhysicsController.cpp's getReactionForce
2024         /*
2025         if (GetPhysicsController())
2026                 return PyObjectFrom(GetPhysicsController()->getReactionForce());
2027         return PyObjectFrom(dummy_point);
2028         */
2029         
2030         return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
2031         
2032 }
2033
2034
2035
2036 PyObject* KX_GameObject::PyEnableRigidBody()
2037 {
2038         if(GetPhysicsController())
2039                 GetPhysicsController()->setRigidBody(true);
2040
2041         Py_RETURN_NONE;
2042 }
2043
2044
2045
2046 PyObject* KX_GameObject::PyDisableRigidBody()
2047 {
2048         if(GetPhysicsController())
2049                 GetPhysicsController()->setRigidBody(false);
2050
2051         Py_RETURN_NONE;
2052 }
2053
2054
2055
2056 PyObject* KX_GameObject::PyGetParent()
2057 {
2058         ShowDeprecationWarning("getParent()", "the parent property");
2059         KX_GameObject* parent = this->GetParent();
2060         if (parent)
2061                 return parent->GetProxy();
2062         Py_RETURN_NONE;
2063 }
2064
2065 PyObject* KX_GameObject::PySetParent(PyObject* value)
2066 {
2067         KX_GameObject *obj;
2068         if (!ConvertPythonToGameObject(value, &obj, false, "gameOb.setParent(value): KX_GameObject"))
2069                 return NULL;
2070         
2071         this->SetParent(KX_GetActiveScene(), obj);
2072         Py_RETURN_NONE;
2073 }
2074
2075 PyObject* KX_GameObject::PyRemoveParent()
2076 {
2077         KX_Scene *scene = KX_GetActiveScene();
2078         this->RemoveParent(scene);
2079         Py_RETURN_NONE;
2080 }
2081
2082 PyObject* KX_GameObject::PyGetChildren()
2083 {
2084         return GetChildren()->NewProxy(true);
2085 }
2086
2087 PyObject* KX_GameObject::PyGetChildrenRecursive()
2088 {
2089         return GetChildrenRecursive()->NewProxy(true);
2090 }
2091
2092 PyObject* KX_GameObject::PyGetMesh(PyObject* args)
2093 {
2094         ShowDeprecationWarning("getMesh()", "the meshes property");
2095         
2096         int mesh = 0;
2097
2098         if (!PyArg_ParseTuple(args, "|i:getMesh", &mesh))
2099                 return NULL; // python sets a simple error
2100         
2101         if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0)
2102         {
2103                 KX_MeshProxy* meshproxy = new KX_MeshProxy(m_meshes[mesh]);
2104                 return meshproxy->NewProxy(true); // XXX Todo Python own.
2105         }
2106         
2107         Py_RETURN_NONE;
2108 }
2109
2110
2111
2112
2113
2114 PyObject* KX_GameObject::PySetCollisionMargin(PyObject* value)
2115 {
2116         float collisionMargin = PyFloat_AsDouble(value);
2117         
2118         if (collisionMargin==-1 && PyErr_Occurred()) {
2119                 PyErr_SetString(PyExc_TypeError, "expected a float");
2120                 return NULL;
2121         }
2122         
2123         if (m_pPhysicsController1)
2124         {
2125                 m_pPhysicsController1->setMargin(collisionMargin);
2126                 Py_RETURN_NONE;
2127         }
2128         PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
2129         return NULL;
2130 }
2131
2132
2133
2134 PyObject* KX_GameObject::PyApplyImpulse(PyObject* args)
2135 {
2136         PyObject* pyattach;
2137         PyObject* pyimpulse;
2138         
2139         if (!m_pPhysicsController1)     {
2140                 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
2141                 return NULL;
2142         }
2143         
2144         if (PyArg_ParseTuple(args, "OO:applyImpulse", &pyattach, &pyimpulse))
2145         {
2146                 MT_Point3  attach;
2147                 MT_Vector3 impulse;
2148                 if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
2149                 {
2150                         m_pPhysicsController1->applyImpulse(attach, impulse);
2151                         Py_RETURN_NONE;
2152                 }
2153
2154         }
2155         
2156         return NULL;
2157 }
2158
2159
2160
2161 PyObject* KX_GameObject::PySuspendDynamics()
2162 {
2163         SuspendDynamics();
2164         Py_RETURN_NONE;
2165 }
2166
2167
2168
2169 PyObject* KX_GameObject::PyRestoreDynamics()
2170 {
2171         RestoreDynamics();
2172         Py_RETURN_NONE;
2173 }
2174
2175
2176
2177 PyObject* KX_GameObject::PyGetOrientation() //keywords
2178 {
2179         ShowDeprecationWarning("getOrientation()", "the orientation property");
2180         return PyObjectFrom(NodeGetWorldOrientation());
2181 }
2182
2183
2184
2185 PyObject* KX_GameObject::PySetOrientation(PyObject* value)
2186 {
2187         ShowDeprecationWarning("setOrientation()", "the orientation property");
2188         MT_Matrix3x3 matrix;
2189         if (PyObject_IsMT_Matrix(value, 3) && PyMatTo(value, matrix))
2190         {
2191                 NodeSetLocalOrientation(matrix);
2192                 NodeUpdateGS(0.f);
2193                 Py_RETURN_NONE;
2194         }
2195
2196         MT_Quaternion quat;
2197         if (PyVecTo(value, quat))
2198         {
2199                 matrix.setRotation(quat);
2200                 NodeSetLocalOrientation(matrix);
2201                 NodeUpdateGS(0.f);
2202                 Py_RETURN_NONE;
2203         }
2204         return NULL;
2205 }
2206
2207 PyObject* KX_GameObject::PyAlignAxisToVect(PyObject* args)
2208 {
2209         PyObject* pyvect;
2210         int axis = 2; //z axis is the default
2211         float fac = 1.0;
2212         
2213         if (PyArg_ParseTuple(args,"O|if:alignAxisToVect",&pyvect,&axis, &fac))
2214         {
2215                 MT_Vector3 vect;
2216                 if (PyVecTo(pyvect, vect))
2217                 {
2218                         if (fac<=0.0) Py_RETURN_NONE; // Nothing to do.
2219                         if (fac> 1.0) fac= 1.0;
2220                         
2221                         AlignAxisToVect(vect,axis,fac);
2222                         NodeUpdateGS(0.f);
2223                         Py_RETURN_NONE;
2224                 }
2225         }
2226         return NULL;
2227 }
2228
2229 PyObject* KX_GameObject::PyGetAxisVect(PyObject* value)
2230 {
2231         MT_Vector3 vect;
2232         if (PyVecTo(value, vect))
2233         {
2234                 return PyObjectFrom(NodeGetWorldOrientation() * vect);
2235         }
2236         return NULL;
2237 }
2238
2239 PyObject* KX_GameObject::PySetPosition(PyObject* value)
2240 {
2241         ShowDeprecationWarning("setPosition()", "the position property");
2242         MT_Point3 pos;
2243         if (PyVecTo(value, pos))
2244         {
2245                 NodeSetLocalPosition(pos);
2246                 NodeUpdateGS(0.f);
2247                 Py_RETURN_NONE;
2248         }
2249
2250         return NULL;
2251 }
2252
2253 PyObject* KX_GameObject::PySetWorldPosition(PyObject* value)
2254 {
2255         MT_Point3 pos;
2256         if (PyVecTo(value, pos))
2257         {
2258                 NodeSetWorldPosition(pos);
2259                 NodeUpdateGS(0.f);
2260                 Py_RETURN_NONE;
2261         }
2262
2263         return NULL;
2264 }
2265
2266 PyObject* KX_GameObject::PyGetPhysicsId()
2267 {
2268         KX_IPhysicsController* ctrl = GetPhysicsController();
2269         uint_ptr physid=0;
2270         if (ctrl)
2271         {
2272                 physid= (uint_ptr)ctrl->GetUserData();
2273         }
2274         return PyInt_FromLong((long)physid);
2275 }
2276
2277 PyObject* KX_GameObject::PyGetPropertyNames()
2278 {
2279         PyObject *list=  ConvertKeysToPython();
2280         
2281         if(m_attr_dict) {
2282                 PyObject *key, *value;
2283                 Py_ssize_t pos = 0;
2284
2285                 while (PyDict_Next(m_attr_dict, &pos, &key, &value)) {
2286                         PyList_Append(list, key);
2287                 }
2288         }
2289         return list;
2290 }
2291
2292 KX_PYMETHODDEF_DOC_O(KX_GameObject, getDistanceTo,
2293 "getDistanceTo(other): get distance to another point/KX_GameObject")
2294 {
2295         MT_Point3 b;
2296         if (PyVecTo(value, b))
2297         {
2298                 return PyFloat_FromDouble(NodeGetWorldPosition().distance(b));
2299         }
2300         PyErr_Clear();
2301         
2302         KX_GameObject *other;
2303         if (ConvertPythonToGameObject(value, &other, false, "gameOb.getDistanceTo(value): KX_GameObject"))
2304         {
2305                 return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition()));
2306         }
2307         
2308         return NULL;
2309 }
2310
2311 KX_PYMETHODDEF_DOC_O(KX_GameObject, getVectTo,
2312 "getVectTo(other): get vector and the distance to another point/KX_GameObject\n"
2313 "Returns a 3-tuple with (distance,worldVector,localVector)\n")
2314 {
2315         MT_Point3 toPoint, fromPoint;
2316         MT_Vector3 toDir, locToDir;
2317         MT_Scalar distance;
2318
2319         PyObject *returnValue;
2320
2321         if (!PyVecTo(value, toPoint))
2322         {
2323                 PyErr_Clear();
2324                 
2325                 KX_GameObject *other;
2326                 if (ConvertPythonToGameObject(value, &other, false, "")) /* error will be overwritten */
2327                 {
2328                         toPoint = other->NodeGetWorldPosition();
2329                 } else
2330                 {
2331                         PyErr_SetString(PyExc_TypeError, "gameOb.getVectTo(other): KX_GameObject, expected a 3D Vector or KX_GameObject type");
2332                         return NULL;
2333                 }
2334         }
2335
2336         fromPoint = NodeGetWorldPosition();
2337         toDir = toPoint-fromPoint;
2338         distance = toDir.length();
2339
2340         if (MT_fuzzyZero(distance))
2341         {
2342                 //cout << "getVectTo() Error: Null vector!\n";
2343                 locToDir = toDir = MT_Vector3(0.0,0.0,0.0);
2344                 distance = 0.0;
2345         } else {
2346                 toDir.normalize();
2347                 locToDir = toDir * NodeGetWorldOrientation();
2348         }
2349         
2350         returnValue = PyTuple_New(3);
2351         if (returnValue) { // very unlikely to fail, python sets a memory error here.
2352                 PyTuple_SET_ITEM(returnValue, 0, PyFloat_FromDouble(distance));
2353                 PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(toDir));
2354                 PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(locToDir));
2355         }
2356         return returnValue;
2357 }
2358
2359 bool KX_GameObject::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
2360 {
2361         KX_GameObject* hitKXObj = client->m_gameobject;
2362         
2363         // if X-ray option is selected, the unwnted objects were not tested, so get here only with true hit
2364         // if not, all objects were tested and the front one may not be the correct one.
2365         if (m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
2366         {
2367                 m_pHitObject = hitKXObj;
2368                 return true;
2369         }
2370         // return true to stop RayCast::RayTest from looping, the above test was decisive
2371         // We would want to loop only if we want to get more than one hit point
2372         return true;
2373 }
2374
2375 /* this function is used to pre-filter the object before casting the ray on them.
2376    This is useful for "X-Ray" option when we want to see "through" unwanted object.
2377  */
2378 bool KX_GameObject::NeedRayCast(KX_ClientObjectInfo* client)
2379 {
2380         KX_GameObject* hitKXObj = client->m_gameobject;
2381         
2382         if (client->m_type > KX_ClientObjectInfo::ACTOR)
2383         {
2384                 // Unknown type of object, skip it.
2385                 // Should not occur as the sensor objects are filtered in RayTest()
2386                 printf("Invalid client type %d found in ray casting\n", client->m_type);
2387                 return false;
2388         }
2389         
2390         // if X-Ray option is selected, skip object that don't match the criteria as we see through them
2391         // if not, test all objects because we don't know yet which one will be on front
2392         if (!m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
2393         {
2394                 return true;
2395         }
2396         // skip the object
2397         return false;
2398 }
2399
2400 KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
2401 "rayCastTo(other,dist,prop): look towards another point/KX_GameObject and return first object hit within dist that matches prop\n"
2402 " prop = property name that object must have; can be omitted => detect any object\n"
2403 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to other\n"
2404 " other = 3-tuple or object reference")
2405 {
2406         MT_Point3 toPoint;
2407         PyObject* pyarg;
2408         float dist = 0.0f;
2409         char *propName = NULL;
2410
2411         if (!PyArg_ParseTuple(args,"O|fs:rayCastTo", &pyarg, &dist, &propName)) {
2412                 return NULL; // python sets simple error
2413         }
2414
2415         if (!PyVecTo(pyarg, toPoint))
2416         {
2417                 KX_GameObject *other;
2418                 PyErr_Clear();
2419                 
2420                 if (ConvertPythonToGameObject(pyarg, &other, false, "")) /* error will be overwritten */
2421                 {
2422                         toPoint = other->NodeGetWorldPosition();
2423                 } else
2424                 {
2425                         PyErr_SetString(PyExc_TypeError, "gameOb.rayCastTo(other,dist,prop): KX_GameObject, the first argument to rayCastTo must be a vector or a KX_GameObject");
2426                         return NULL;
2427                 }
2428         }
2429         MT_Point3 fromPoint = NodeGetWorldPosition();
2430         if (dist != 0.0f)
2431         {
2432                 MT_Vector3 toDir = toPoint-fromPoint;
2433                 toDir.normalize();
2434                 toPoint = fromPoint + (dist) * toDir;
2435         }
2436
2437         PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
2438         KX_IPhysicsController *spc = GetPhysicsController();
2439         KX_GameObject *parent = GetParent();
2440         if (!spc && parent)
2441                 spc = parent->GetPhysicsController();
2442         if (parent)
2443                 parent->Release();
2444         
2445         m_pHitObject = NULL;
2446         if (propName)
2447                 m_testPropName = propName;
2448         else
2449                 m_testPropName.SetLength(0);
2450         KX_RayCast::Callback<KX_GameObject> callback(this,spc);
2451         KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
2452
2453     if (m_pHitObject)
2454                 return m_pHitObject->GetProxy();
2455         
2456         Py_RETURN_NONE;
2457 }
2458
2459 KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
2460                                    "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"
2461                                    " If no hit, return (None,None,None) or (None,None,None,None).\n"
2462 " to   = 3-tuple or object reference for destination of ray (if object, use center of object)\n"
2463 " from = 3-tuple or object reference for origin of ray (if object, use center of object)\n"
2464 "        Can be None or omitted => start from self object center\n"
2465 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to to\n"
2466 " prop = property name that object must have; can be omitted => detect any object\n"
2467 " face = normal option: 1=>return face normal; 0 or omitted => normal is oriented towards origin\n"
2468 " xray = X-ray option: 1=>skip objects that don't match prop; 0 or omitted => stop on first object\n"
2469 " poly = polygon option: 1=>return value is a 4-tuple and the 4th element is a KX_PolyProxy object\n"
2470 "                           which can be None if hit object has no mesh or if there is no hit\n"
2471 "        If 0 or omitted, return value is a 3-tuple\n"
2472 "Note: The object on which you call this method matters: the ray will ignore it.\n"
2473 "      prop and xray option interact as follow:\n"
2474 "        prop off, xray off: return closest hit or no hit if there is no object on the full extend of the ray\n"
2475 "        prop off, xray on : idem\n"
2476 "        prop on,  xray off: return closest hit if it matches prop, no hit otherwise\n"
2477 "        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")
2478 {
2479         MT_Point3 toPoint;
2480         MT_Point3 fromPoint;
2481         PyObject* pyto;
2482         PyObject* pyfrom = NULL;
2483         float dist = 0.0f;
2484         char *propName = NULL;
2485         KX_GameObject *other;
2486         int face=0, xray=0, poly=0;
2487
2488         if (!PyArg_ParseTuple(args,"O|Ofsiii:rayCast", &pyto, &pyfrom, &dist, &propName, &face, &xray, &poly)) {
2489                 return NULL; // Python sets a simple error
2490         }
2491
2492         if (!PyVecTo(pyto, toPoint))
2493         {
2494                 PyErr_Clear();
2495                 
2496                 if (ConvertPythonToGameObject(pyto, &other, false, ""))  /* error will be overwritten */
2497                 {
2498                         toPoint = other->NodeGetWorldPosition();
2499                 } else
2500                 {
2501                         PyErr_SetString(PyExc_TypeError, "the first argument to rayCast must be a vector or a KX_GameObject");
2502                         return NULL;
2503                 }
2504         }
2505         if (!pyfrom || pyfrom == Py_None)
2506         {
2507                 fromPoint = NodeGetWorldPosition();
2508         }
2509         else if (!PyVecTo(pyfrom, fromPoint))
2510         {
2511                 PyErr_Clear();
2512                 
2513                 if (ConvertPythonToGameObject(pyfrom, &other, false, "")) /* error will be overwritten */
2514                 {
2515                         fromPoint = other->NodeGetWorldPosition();
2516                 } else
2517                 {
2518                         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");
2519                         return NULL;
2520                 }
2521         }
2522         
2523         if (dist != 0.0f) {
2524                 MT_Vector3 toDir = toPoint-fromPoint;
2525                 if (MT_fuzzyZero(toDir.length2())) {
2526                         return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2527                 }
2528                 toDir.normalize();
2529                 toPoint = fromPoint + (dist) * toDir;
2530         } else if (MT_fuzzyZero((toPoint-fromPoint).length2())) {
2531                 return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2532         }
2533         
2534         PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
2535         KX_IPhysicsController *spc = GetPhysicsController();
2536         KX_GameObject *parent = GetParent();
2537         if (!spc && parent)
2538                 spc = parent->GetPhysicsController();
2539         if (parent)
2540                 parent->Release();
2541         
2542         m_pHitObject = NULL;
2543         if (propName)
2544                 m_testPropName = propName;
2545         else
2546                 m_testPropName.SetLength(0);
2547         m_xray = xray;
2548         // to get the hit results
2549         KX_RayCast::Callback<KX_GameObject> callback(this,spc,NULL,face);
2550         KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
2551
2552         if (m_pHitObject)
2553         {
2554                 PyObject* returnValue = (poly) ? PyTuple_New(4) : PyTuple_New(3);
2555                 if (returnValue) { // unlikely this would ever fail, if it does python sets an error
2556                         PyTuple_SET_ITEM(returnValue, 0, m_pHitObject->GetProxy());
2557                         PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(callback.m_hitPoint));
2558                         PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(callback.m_hitNormal));
2559                         if (poly)
2560                         {
2561                                 if (callback.m_hitMesh)
2562                                 {
2563                                         // if this field is set, then we can trust that m_hitPolygon is a valid polygon
2564                                         RAS_Polygon* polygon = callback.m_hitMesh->GetPolygon(callback.m_hitPolygon);
2565                                         KX_PolyProxy* polyproxy = new KX_PolyProxy(callback.m_hitMesh, polygon);
2566                                         PyTuple_SET_ITEM(returnValue, 3, polyproxy->NewProxy(true));
2567                                 }
2568                                 else
2569                                 {
2570                                         Py_INCREF(Py_None);
2571                                         PyTuple_SET_ITEM(returnValue, 3, Py_None);
2572                                 }
2573                         }
2574                 }
2575                 return returnValue;
2576         }
2577         // no hit
2578         if (poly)
2579                 return Py_BuildValue("OOOO", Py_None, Py_None, Py_None, Py_None);
2580         else
2581                 return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2582 }
2583
2584 KX_PYMETHODDEF_DOC_VARARGS(KX_GameObject, sendMessage, 
2585                                                    "sendMessage(subject, [body, to])\n"
2586 "sends a message in same manner as a message actuator"
2587 "subject = Subject of the message (string)"
2588 "body = Message body (string)"
2589 "to = Name of object to send the message to")
2590 {
2591         char* subject;
2592         char* body = (char *)"";
2593         char* to = (char *)"";
2594         const STR_String& from = GetName();
2595
2596         if (!PyArg_ParseTuple(args, "s|sss:sendMessage", &subject, &body, &to))
2597                 return NULL;
2598
2599         KX_GetActiveScene()->GetNetworkScene()->SendMessage(to, from, subject, body);
2600
2601         Py_RETURN_NONE;
2602 }
2603
2604 /* --------------------------------------------------------------------- 
2605  * Some stuff taken from the header
2606  * --------------------------------------------------------------------- */
2607 void KX_GameObject::Relink(GEN_Map<GEN_HashedPtr, void*> *map_parameter)        
2608 {
2609         // we will relink the sensors and actuators that use object references
2610         // if the object is part of the replicated hierarchy, use the new
2611         // object reference instead
2612         SCA_SensorList& sensorlist = GetSensors();
2613         SCA_SensorList::iterator sit;
2614         for (sit=sensorlist.begin(); sit != sensorlist.end(); sit++)
2615         {
2616                 (*sit)->Relink(map_parameter);
2617         }
2618         SCA_ActuatorList& actuatorlist = GetActuators();
2619         SCA_ActuatorList::iterator ait;
2620         for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++)
2621         {
2622                 (*ait)->Relink(map_parameter);
2623         }
2624 }
2625
2626 bool ConvertPythonToGameObject(PyObject * value, KX_GameObject **object, bool py_none_ok, const char *error_prefix)
2627 {
2628         if (value==NULL) {
2629                 PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix);
2630                 *object = NULL;
2631                 return false;
2632         }
2633                 
2634         if (value==Py_None) {
2635                 *object = NULL;
2636                 
2637                 if (py_none_ok) {
2638                         return true;
2639                 } else {
2640                         PyErr_Format(PyExc_TypeError, "%s, expected KX_GameObject or a KX_GameObject name, None is invalid", error_prefix);
2641                         return false;
2642                 }
2643         }
2644         
2645         if (PyString_Check(value)) {
2646                 *object = (KX_GameObject*)SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String( PyString_AsString(value) ));
2647                 
2648                 if (*object) {
2649                         return true;
2650                 } else {
2651                         PyErr_Format(PyExc_ValueError, "%s, requested name \"%s\" did not match any KX_GameObject in this scene", error_prefix, PyString_AsString(value));
2652                         return false;
2653                 }
2654         }
2655         
2656         if (PyObject_TypeCheck(value, &KX_GameObject::Type)) {
2657                 *object = static_cast<KX_GameObject*>BGE_PROXY_REF(value);
2658                 
2659                 /* sets the error */
2660                 if (*object==NULL) {
2661                         PyErr_Format(PyExc_RuntimeError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix);
2662                         return false;
2663                 }
2664                 
2665                 return true;
2666         }
2667         
2668         *object = NULL;
2669         
2670         if (py_none_ok) {
2671                 PyErr_Format(PyExc_TypeError, "%s, expect a KX_GameObject, a string or None", error_prefix);
2672         } else {
2673                 PyErr_Format(PyExc_TypeError, "%s, expect a KX_GameObject or a string", error_prefix);
2674         }
2675         
2676         return false;
2677 }