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