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