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