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