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