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