Accidentally did a commit when I wanted to revert... (ignore my last revision)
[blender-staging.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) && !defined(FREE_WINDOWS64)
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); /* in case 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]) < (MT_Scalar)FLT_EPSILON ||
265                         fabs(scale2[1]) < (MT_Scalar)FLT_EPSILON ||
266                         fabs(scale2[2]) < (MT_Scalar)FLT_EPSILON ||
267                         fabs(scale1[0]) < (MT_Scalar)FLT_EPSILON ||
268                         fabs(scale1[1]) < (MT_Scalar)FLT_EPSILON ||
269                         fabs(scale1[2]) < (MT_Scalar)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.0f) {
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.0f) {
948                                 x = vect;
949                         } else {
950                                 x = (vect * fac) + ((orimat * MT_Vector3(1.0, 0.0, 0.0)) * (1.0f - 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.0f) {
963                                 y = vect;
964                         } else {
965                                 y = (vect * fac) + ((orimat * MT_Vector3(0.0, 1.0, 0.0)) * (1.0f - 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.0f) {
978                                 z = vect;
979                         } else {
980                                 z = (vect * fac) + ((orimat * MT_Vector3(0.0, 0.0, 1.0)) * (1.0f - 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]) < (MT_Scalar)FLT_EPSILON ||
1166                         fabs(p_scale[1]) < (MT_Scalar)FLT_EPSILON ||
1167                         fabs(p_scale[2]) < (MT_Scalar)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]) < (MT_Scalar)FLT_EPSILON ||
1194                         fabs(scale[1]) < (MT_Scalar)FLT_EPSILON ||
1195                         fabs(scale[2]) < (MT_Scalar)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) && (!m_suspended)) {
1295                 SCA_IObject::Suspend();
1296                 if (GetPhysicsController())
1297                         GetPhysicsController()->SuspendDynamics();
1298                 m_suspended = true;
1299         }
1300 }
1301
1302 static void walk_children(SG_Node* node, CListValue* list, bool recursive)
1303 {
1304         if (!node)
1305                 return;
1306         NodeList& children = node->GetSGChildren();
1307
1308         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
1309         {
1310                 SG_Node* childnode = (*childit);
1311                 CValue* childobj = (CValue*)childnode->GetSGClientObject();
1312                 if (childobj != NULL) // This is a GameObject
1313                 {
1314                         // add to the list
1315                         list->Add(childobj->AddRef());
1316                 }
1317                 
1318                 // if the childobj is NULL then this may be an inverse parent link
1319                 // so a non recursive search should still look down this node.
1320                 if (recursive || childobj==NULL) {
1321                         walk_children(childnode, list, recursive);
1322                 }
1323         }
1324 }
1325
1326 CListValue* KX_GameObject::GetChildren()
1327 {
1328         CListValue* list = new CListValue();
1329         walk_children(GetSGNode(), list, 0); /* GetSGNode() is always valid or it would have raised an exception before this */
1330         return list;
1331 }
1332
1333 CListValue* KX_GameObject::GetChildrenRecursive()
1334 {
1335         CListValue* list = new CListValue();
1336         walk_children(GetSGNode(), list, 1);
1337         return list;
1338 }
1339
1340 /* ---------------------------------------------------------------------
1341  * Some stuff taken from the header
1342  * --------------------------------------------------------------------- */
1343 void KX_GameObject::Relink(CTR_Map<CTR_HashedPtr, void*> *map_parameter)
1344 {
1345         // we will relink the sensors and actuators that use object references
1346         // if the object is part of the replicated hierarchy, use the new
1347         // object reference instead
1348         SCA_SensorList& sensorlist = GetSensors();
1349         SCA_SensorList::iterator sit;
1350         for (sit=sensorlist.begin(); sit != sensorlist.end(); sit++)
1351         {
1352                 (*sit)->Relink(map_parameter);
1353         }
1354         SCA_ActuatorList& actuatorlist = GetActuators();
1355         SCA_ActuatorList::iterator ait;
1356         for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++)
1357         {
1358                 (*ait)->Relink(map_parameter);
1359         }
1360 }
1361
1362 #ifdef USE_MATHUTILS
1363
1364 /* These require an SGNode */
1365 #define MATHUTILS_VEC_CB_POS_LOCAL 1
1366 #define MATHUTILS_VEC_CB_POS_GLOBAL 2
1367 #define MATHUTILS_VEC_CB_SCALE_LOCAL 3
1368 #define MATHUTILS_VEC_CB_SCALE_GLOBAL 4
1369 #define MATHUTILS_VEC_CB_INERTIA_LOCAL 5
1370 #define MATHUTILS_VEC_CB_OBJECT_COLOR 6
1371 #define MATHUTILS_VEC_CB_LINVEL_LOCAL 7
1372 #define MATHUTILS_VEC_CB_LINVEL_GLOBAL 8
1373 #define MATHUTILS_VEC_CB_ANGVEL_LOCAL 9
1374 #define MATHUTILS_VEC_CB_ANGVEL_GLOBAL 10
1375
1376 static unsigned char mathutils_kxgameob_vector_cb_index= -1; /* index for our callbacks */
1377
1378 static int mathutils_kxgameob_generic_check(BaseMathObject *bmo)
1379 {
1380         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1381         if (self==NULL)
1382                 return -1;
1383         
1384         return 0;
1385 }
1386
1387 static int mathutils_kxgameob_vector_get(BaseMathObject *bmo, int subtype)
1388 {
1389         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1390         if (self==NULL)
1391                 return -1;
1392
1393 #define PHYS_ERR(attr) PyErr_SetString(PyExc_AttributeError, "KX_GameObject." attr ", is missing a physics controller")
1394
1395         switch(subtype) {
1396                 case MATHUTILS_VEC_CB_POS_LOCAL:
1397                         self->NodeGetLocalPosition().getValue(bmo->data);
1398                         break;
1399                 case MATHUTILS_VEC_CB_POS_GLOBAL:
1400                         self->NodeGetWorldPosition().getValue(bmo->data);
1401                         break;
1402                 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1403                         self->NodeGetLocalScaling().getValue(bmo->data);
1404                         break;
1405                 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1406                         self->NodeGetWorldScaling().getValue(bmo->data);
1407                         break;
1408                 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1409                         if (!self->GetPhysicsController()) return PHYS_ERR("localInertia"), -1;
1410                         self->GetPhysicsController()->GetLocalInertia().getValue(bmo->data);
1411                         break;
1412                 case MATHUTILS_VEC_CB_OBJECT_COLOR:
1413                         self->GetObjectColor().getValue(bmo->data);
1414                         break;
1415                 case MATHUTILS_VEC_CB_LINVEL_LOCAL:
1416                         if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1;
1417                         self->GetLinearVelocity(true).getValue(bmo->data);
1418                         break;
1419                 case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
1420                         if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1;
1421                         self->GetLinearVelocity(false).getValue(bmo->data);
1422                         break;
1423                 case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
1424                         if (!self->GetPhysicsController()) return PHYS_ERR("localLinearVelocity"), -1;
1425                         self->GetAngularVelocity(true).getValue(bmo->data);
1426                         break;
1427                 case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
1428                         if (!self->GetPhysicsController()) return PHYS_ERR("worldLinearVelocity"), -1;
1429                         self->GetAngularVelocity(false).getValue(bmo->data);
1430                         break;
1431                         
1432         }
1433         
1434 #undef PHYS_ERR
1435         
1436         return 0;
1437 }
1438
1439 static int mathutils_kxgameob_vector_set(BaseMathObject *bmo, int subtype)
1440 {
1441         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1442         if (self==NULL)
1443                 return -1;
1444         
1445         switch(subtype) {
1446                 case MATHUTILS_VEC_CB_POS_LOCAL:
1447                         self->NodeSetLocalPosition(MT_Point3(bmo->data));
1448                         self->NodeUpdateGS(0.f);
1449                         break;
1450                 case MATHUTILS_VEC_CB_POS_GLOBAL:
1451                         self->NodeSetWorldPosition(MT_Point3(bmo->data));
1452                         self->NodeUpdateGS(0.f);
1453                         break;
1454                 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1455                         self->NodeSetLocalScale(MT_Point3(bmo->data));
1456                         self->NodeUpdateGS(0.f);
1457                         break;
1458                 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1459                         PyErr_SetString(PyExc_AttributeError, "KX_GameObject.worldScale is read-only");
1460                         return -1;
1461                 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1462                         /* read only */
1463                         break;
1464                 case MATHUTILS_VEC_CB_OBJECT_COLOR:
1465                         self->SetObjectColor(MT_Vector4(bmo->data));
1466                         break;
1467                 case MATHUTILS_VEC_CB_LINVEL_LOCAL:
1468                         self->setLinearVelocity(MT_Point3(bmo->data),true);
1469                         break;
1470                 case MATHUTILS_VEC_CB_LINVEL_GLOBAL:
1471                         self->setLinearVelocity(MT_Point3(bmo->data),false);
1472                         break;
1473                 case MATHUTILS_VEC_CB_ANGVEL_LOCAL:
1474                         self->setAngularVelocity(MT_Point3(bmo->data),true);
1475                         break;
1476                 case MATHUTILS_VEC_CB_ANGVEL_GLOBAL:
1477                         self->setAngularVelocity(MT_Point3(bmo->data),false);
1478                         break;
1479         }
1480         
1481         return 0;
1482 }
1483
1484 static int mathutils_kxgameob_vector_get_index(BaseMathObject *bmo, int subtype, int index)
1485 {
1486         /* lazy, avoid repeteing the case statement */
1487         if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
1488                 return -1;
1489         return 0;
1490 }
1491
1492 static int mathutils_kxgameob_vector_set_index(BaseMathObject *bmo, int subtype, int index)
1493 {
1494         float f= bmo->data[index];
1495         
1496         /* lazy, avoid repeteing the case statement */
1497         if (mathutils_kxgameob_vector_get(bmo, subtype) == -1)
1498                 return -1;
1499         
1500         bmo->data[index]= f;
1501         return mathutils_kxgameob_vector_set(bmo, subtype);
1502 }
1503
1504 Mathutils_Callback mathutils_kxgameob_vector_cb = {
1505         mathutils_kxgameob_generic_check,
1506         mathutils_kxgameob_vector_get,
1507         mathutils_kxgameob_vector_set,
1508         mathutils_kxgameob_vector_get_index,
1509         mathutils_kxgameob_vector_set_index
1510 };
1511
1512 /* Matrix */
1513 #define MATHUTILS_MAT_CB_ORI_LOCAL 1
1514 #define MATHUTILS_MAT_CB_ORI_GLOBAL 2
1515
1516 static unsigned char mathutils_kxgameob_matrix_cb_index= -1; /* index for our callbacks */
1517
1518 static int mathutils_kxgameob_matrix_get(BaseMathObject *bmo, int subtype)
1519 {
1520         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1521         if (self==NULL)
1522                 return -1;
1523
1524         switch(subtype) {
1525                 case MATHUTILS_MAT_CB_ORI_LOCAL:
1526                         self->NodeGetLocalOrientation().getValue3x3(bmo->data);
1527                         break;
1528                 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1529                         self->NodeGetWorldOrientation().getValue3x3(bmo->data);
1530                         break;
1531         }
1532         
1533         return 0;
1534 }
1535
1536
1537 static int mathutils_kxgameob_matrix_set(BaseMathObject *bmo, int subtype)
1538 {
1539         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(bmo->cb_user);
1540         if (self==NULL)
1541                 return -1;
1542         
1543         MT_Matrix3x3 mat3x3;
1544         switch(subtype) {
1545                 case MATHUTILS_MAT_CB_ORI_LOCAL:
1546                         mat3x3.setValue3x3(bmo->data);
1547                         self->NodeSetLocalOrientation(mat3x3);
1548                         self->NodeUpdateGS(0.f);
1549                         break;
1550                 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1551                         mat3x3.setValue3x3(bmo->data);
1552                         self->NodeSetLocalOrientation(mat3x3);
1553                         self->NodeUpdateGS(0.f);
1554                         break;
1555         }
1556         
1557         return 0;
1558 }
1559
1560 Mathutils_Callback mathutils_kxgameob_matrix_cb = {
1561         mathutils_kxgameob_generic_check,
1562         mathutils_kxgameob_matrix_get,
1563         mathutils_kxgameob_matrix_set,
1564         NULL,
1565         NULL
1566 };
1567
1568
1569 void KX_GameObject_Mathutils_Callback_Init(void)
1570 {
1571         // register mathutils callbacks, ok to run more then once.
1572         mathutils_kxgameob_vector_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_vector_cb);
1573         mathutils_kxgameob_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_matrix_cb);
1574 }
1575
1576 #endif // USE_MATHUTILS
1577
1578 #ifdef WITH_PYTHON
1579 /* ------- python stuff ---------------------------------------------------*/
1580 PyMethodDef KX_GameObject::Methods[] = {
1581         {"applyForce", (PyCFunction)    KX_GameObject::sPyApplyForce, METH_VARARGS},
1582         {"applyTorque", (PyCFunction)   KX_GameObject::sPyApplyTorque, METH_VARARGS},
1583         {"applyRotation", (PyCFunction) KX_GameObject::sPyApplyRotation, METH_VARARGS},
1584         {"applyMovement", (PyCFunction) KX_GameObject::sPyApplyMovement, METH_VARARGS},
1585         {"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS},
1586         {"setLinearVelocity", (PyCFunction) KX_GameObject::sPySetLinearVelocity, METH_VARARGS},
1587         {"getAngularVelocity", (PyCFunction) KX_GameObject::sPyGetAngularVelocity, METH_VARARGS},
1588         {"setAngularVelocity", (PyCFunction) KX_GameObject::sPySetAngularVelocity, METH_VARARGS},
1589         {"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS},
1590         {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS},
1591         {"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS},
1592         {"getAxisVect",(PyCFunction) KX_GameObject::sPyGetAxisVect, METH_O},
1593         {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics,METH_NOARGS},
1594         {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_NOARGS},
1595         {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_NOARGS},
1596         {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_NOARGS},
1597         {"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS},
1598         {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_O},
1599         {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_VARARGS},
1600         {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},
1601         {"setOcclusion",(PyCFunction) KX_GameObject::sPySetOcclusion, METH_VARARGS},
1602         {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_NOARGS},
1603
1604
1605         {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS},
1606         {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS},
1607         {"replaceMesh",(PyCFunction) KX_GameObject::sPyReplaceMesh, METH_VARARGS},
1608         {"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS},
1609         {"reinstancePhysicsMesh", (PyCFunction)KX_GameObject::sPyReinstancePhysicsMesh,METH_VARARGS},
1610         
1611         KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
1612         KX_PYMETHODTABLE(KX_GameObject, rayCast),
1613         KX_PYMETHODTABLE_O(KX_GameObject, getDistanceTo),
1614         KX_PYMETHODTABLE_O(KX_GameObject, getVectTo),
1615         KX_PYMETHODTABLE(KX_GameObject, sendMessage),
1616
1617         KX_PYMETHODTABLE_KEYWORDS(KX_GameObject, playAction),
1618         KX_PYMETHODTABLE(KX_GameObject, stopAction),
1619         KX_PYMETHODTABLE(KX_GameObject, getActionFrame),
1620         KX_PYMETHODTABLE(KX_GameObject, setActionFrame),
1621         KX_PYMETHODTABLE(KX_GameObject, isPlayingAction),
1622         
1623         // dict style access for props
1624         {"get",(PyCFunction) KX_GameObject::sPyget, METH_VARARGS},
1625         
1626         {NULL,NULL} //Sentinel
1627 };
1628
1629 PyAttributeDef KX_GameObject::Attributes[] = {
1630         KX_PYATTRIBUTE_RO_FUNCTION("name",              KX_GameObject, pyattr_get_name),
1631         KX_PYATTRIBUTE_RO_FUNCTION("parent",    KX_GameObject, pyattr_get_parent),
1632         KX_PYATTRIBUTE_RO_FUNCTION("life",              KX_GameObject, pyattr_get_life),
1633         KX_PYATTRIBUTE_RW_FUNCTION("mass",              KX_GameObject, pyattr_get_mass,         pyattr_set_mass),
1634         KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMin",            KX_GameObject, pyattr_get_lin_vel_min, pyattr_set_lin_vel_min),
1635         KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMax",            KX_GameObject, pyattr_get_lin_vel_max, pyattr_set_lin_vel_max),
1636         KX_PYATTRIBUTE_RW_FUNCTION("visible",   KX_GameObject, pyattr_get_visible,      pyattr_set_visible),
1637         KX_PYATTRIBUTE_BOOL_RW    ("occlusion", KX_GameObject, m_bOccluder),
1638         KX_PYATTRIBUTE_RW_FUNCTION("position",  KX_GameObject, pyattr_get_worldPosition,        pyattr_set_localPosition),
1639         KX_PYATTRIBUTE_RO_FUNCTION("localInertia",      KX_GameObject, pyattr_get_localInertia),
1640         KX_PYATTRIBUTE_RW_FUNCTION("orientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_localOrientation),
1641         KX_PYATTRIBUTE_RW_FUNCTION("scaling",   KX_GameObject, pyattr_get_worldScaling, pyattr_set_localScaling),
1642         KX_PYATTRIBUTE_RW_FUNCTION("timeOffset",KX_GameObject, pyattr_get_timeOffset,pyattr_set_timeOffset),
1643         KX_PYATTRIBUTE_RW_FUNCTION("state",             KX_GameObject, pyattr_get_state,        pyattr_set_state),
1644         KX_PYATTRIBUTE_RO_FUNCTION("meshes",    KX_GameObject, pyattr_get_meshes),
1645         KX_PYATTRIBUTE_RW_FUNCTION("localOrientation",KX_GameObject,pyattr_get_localOrientation,pyattr_set_localOrientation),
1646         KX_PYATTRIBUTE_RW_FUNCTION("worldOrientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_worldOrientation),
1647         KX_PYATTRIBUTE_RW_FUNCTION("localPosition",     KX_GameObject, pyattr_get_localPosition,        pyattr_set_localPosition),
1648         KX_PYATTRIBUTE_RW_FUNCTION("worldPosition",     KX_GameObject, pyattr_get_worldPosition,    pyattr_set_worldPosition),
1649         KX_PYATTRIBUTE_RW_FUNCTION("localScale",        KX_GameObject, pyattr_get_localScaling, pyattr_set_localScaling),
1650         KX_PYATTRIBUTE_RW_FUNCTION("worldScale",        KX_GameObject, pyattr_get_worldScaling, pyattr_set_worldScaling),
1651         KX_PYATTRIBUTE_RW_FUNCTION("localTransform",            KX_GameObject, pyattr_get_localTransform, pyattr_set_localTransform),
1652         KX_PYATTRIBUTE_RW_FUNCTION("worldTransform",            KX_GameObject, pyattr_get_worldTransform, pyattr_set_worldTransform),
1653         KX_PYATTRIBUTE_RW_FUNCTION("linearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_worldLinearVelocity),
1654         KX_PYATTRIBUTE_RW_FUNCTION("localLinearVelocity", KX_GameObject, pyattr_get_localLinearVelocity, pyattr_set_localLinearVelocity),
1655         KX_PYATTRIBUTE_RW_FUNCTION("worldLinearVelocity", KX_GameObject, pyattr_get_worldLinearVelocity, pyattr_set_worldLinearVelocity),
1656         KX_PYATTRIBUTE_RW_FUNCTION("angularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_worldAngularVelocity),
1657         KX_PYATTRIBUTE_RW_FUNCTION("localAngularVelocity", KX_GameObject, pyattr_get_localAngularVelocity, pyattr_set_localAngularVelocity),
1658         KX_PYATTRIBUTE_RW_FUNCTION("worldAngularVelocity", KX_GameObject, pyattr_get_worldAngularVelocity, pyattr_set_worldAngularVelocity),
1659         KX_PYATTRIBUTE_RO_FUNCTION("children",  KX_GameObject, pyattr_get_children),
1660         KX_PYATTRIBUTE_RO_FUNCTION("childrenRecursive", KX_GameObject, pyattr_get_children_recursive),
1661         KX_PYATTRIBUTE_RO_FUNCTION("attrDict",  KX_GameObject, pyattr_get_attrDict),
1662         KX_PYATTRIBUTE_RW_FUNCTION("color", KX_GameObject, pyattr_get_obcolor, pyattr_set_obcolor),
1663         
1664         /* experimental, don't rely on these yet */
1665         KX_PYATTRIBUTE_RO_FUNCTION("sensors",           KX_GameObject, pyattr_get_sensors),
1666         KX_PYATTRIBUTE_RO_FUNCTION("controllers",       KX_GameObject, pyattr_get_controllers),
1667         KX_PYATTRIBUTE_RO_FUNCTION("actuators",         KX_GameObject, pyattr_get_actuators),
1668         {NULL} //Sentinel
1669 };
1670
1671 PyObject* KX_GameObject::PyReplaceMesh(PyObject* args)
1672 {
1673         KX_Scene *scene = KX_GetActiveScene();
1674         
1675         PyObject *value;
1676         int use_gfx= 1, use_phys= 0;
1677         RAS_MeshObject *new_mesh;
1678         
1679         if (!PyArg_ParseTuple(args,"O|ii:replaceMesh", &value, &use_gfx, &use_phys))
1680                 return NULL;
1681         
1682         if (!ConvertPythonToMesh(value, &new_mesh, false, "gameOb.replaceMesh(value): KX_GameObject"))
1683                 return NULL;
1684         
1685         scene->ReplaceMesh(this, new_mesh, (bool)use_gfx, (bool)use_phys);
1686         Py_RETURN_NONE;
1687 }
1688
1689 PyObject* KX_GameObject::PyEndObject()
1690 {
1691         KX_Scene *scene = KX_GetActiveScene();
1692         
1693         scene->DelayedRemoveObject(this);
1694         
1695         Py_RETURN_NONE;
1696
1697 }
1698
1699 PyObject* KX_GameObject::PyReinstancePhysicsMesh(PyObject* args)
1700 {
1701         KX_GameObject *gameobj= NULL;
1702         RAS_MeshObject *mesh= NULL;
1703         
1704         PyObject *gameobj_py= NULL;
1705         PyObject *mesh_py= NULL;
1706
1707         if (    !PyArg_ParseTuple(args,"|OO:reinstancePhysicsMesh",&gameobj_py, &mesh_py) ||
1708                         (gameobj_py && !ConvertPythonToGameObject(gameobj_py, &gameobj, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject")) || 
1709                         (mesh_py && !ConvertPythonToMesh(mesh_py, &mesh, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject"))
1710                 ) {
1711                 return NULL;
1712         }
1713 #ifdef USE_BULLET
1714         /* gameobj and mesh can be NULL */
1715         if (KX_ReInstanceBulletShapeFromMesh(this, gameobj, mesh))
1716                 Py_RETURN_TRUE;
1717 #endif
1718         Py_RETURN_FALSE;
1719 }
1720
1721 static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
1722 {
1723         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1724         const char *attr_str= _PyUnicode_AsString(item);
1725         CValue* resultattr;
1726         PyObject* pyconvert;
1727         
1728         if (self==NULL) {
1729                 PyErr_SetString(PyExc_SystemError, "val = gameOb[key]: KX_GameObject, "BGE_PROXY_ERROR_MSG);
1730                 return NULL;
1731         }
1732         
1733         /* first see if the attributes a string and try get the cvalue attribute */
1734         if (attr_str && (resultattr=self->GetProperty(attr_str))) {
1735                 pyconvert = resultattr->ConvertValueToPython();                 
1736                 return pyconvert ? pyconvert:resultattr->GetProxy();
1737         }
1738         /* no CValue attribute, try get the python only m_attr_dict attribute */
1739         else if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
1740                 
1741                 if (attr_str)
1742                         PyErr_Clear();
1743                 Py_INCREF(pyconvert);
1744                 return pyconvert;
1745         }
1746         else {
1747                 if (attr_str)   PyErr_Format(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key \"%s\" does not exist", attr_str);
1748                 else                    PyErr_SetString(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key does not exist");
1749                 return NULL;
1750         }
1751                 
1752 }
1753
1754
1755 static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
1756 {
1757         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1758         const char *attr_str= _PyUnicode_AsString(key);
1759         if (attr_str==NULL)
1760                 PyErr_Clear();
1761         
1762         if (self==NULL) {
1763                 PyErr_SetString(PyExc_SystemError, "gameOb[key] = value: KX_GameObject, "BGE_PROXY_ERROR_MSG);
1764                 return -1;
1765         }
1766         
1767         if (val==NULL) { /* del ob["key"] */
1768                 int del= 0;
1769                 
1770                 /* try remove both just in case */
1771                 if (attr_str)
1772                         del |= (self->RemoveProperty(attr_str)==true) ? 1:0;
1773                 
1774                 if (self->m_attr_dict)
1775                         del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
1776                 
1777                 if (del==0) {
1778                         if (attr_str)   PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" could not be set", attr_str);
1779                         else                    PyErr_SetString(PyExc_KeyError, "del gameOb[key]: KX_GameObject, key could not be deleted");
1780                         return -1;
1781                 }
1782                 else if (self->m_attr_dict) {
1783                         PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
1784                 }
1785         }
1786         else { /* ob["key"] = value */
1787                 int set= 0;
1788                 
1789                 /* as CValue */
1790                 if (attr_str && PyObject_TypeCheck(val, &PyObjectPlus::Type)==0) /* don't allow GameObjects for eg to be assigned to CValue props */
1791                 {
1792                         CValue* vallie = self->ConvertPythonToValue(val, ""); /* error unused */
1793                         
1794                         if (vallie)
1795                         {
1796                                 CValue* oldprop = self->GetProperty(attr_str);
1797                                 
1798                                 if (oldprop)
1799                                         oldprop->SetValue(vallie);
1800                                 else
1801                                         self->SetProperty(attr_str, vallie);
1802                                 
1803                                 vallie->Release();
1804                                 set= 1;
1805                                 
1806                                 /* try remove dict value to avoid double ups */
1807                                 if (self->m_attr_dict) {
1808                                         if (PyDict_DelItem(self->m_attr_dict, key) != 0)
1809                                                 PyErr_Clear();
1810                                 }
1811                         }
1812                         else {
1813                                 PyErr_Clear();
1814                         }
1815                 }
1816                 
1817                 if (set==0)
1818                 {
1819                         if (self->m_attr_dict==NULL) /* lazy init */
1820                                 self->m_attr_dict= PyDict_New();
1821                         
1822                         
1823                         if (PyDict_SetItem(self->m_attr_dict, key, val)==0)
1824                         {
1825                                 if (attr_str)
1826                                         self->RemoveProperty(attr_str); /* overwrite the CValue if it exists */
1827                                 set= 1;
1828                         }
1829                         else {
1830                                 if (attr_str)   PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" not be added to internal dictionary", attr_str);
1831                                 else                    PyErr_SetString(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key not be added to internal dictionary");
1832                         }
1833                 }
1834                 
1835                 if (set==0)
1836                         return -1; /* pythons error value */
1837                 
1838         }
1839         
1840         return 0; /* success */
1841 }
1842
1843 static int Seq_Contains(PyObject *self_v, PyObject *value)
1844 {
1845         KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1846         
1847         if (self==NULL) {
1848                 PyErr_SetString(PyExc_SystemError, "val in gameOb: KX_GameObject, "BGE_PROXY_ERROR_MSG);
1849                 return -1;
1850         }
1851         
1852         if (PyUnicode_Check(value) && self->GetProperty(_PyUnicode_AsString(value)))
1853                 return 1;
1854         
1855         if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
1856                 return 1;
1857         
1858         return 0;
1859 }
1860
1861
1862 PyMappingMethods KX_GameObject::Mapping = {
1863         (lenfunc)NULL                                   ,                       /*inquiry mp_length */
1864         (binaryfunc)Map_GetItem,                /*binaryfunc mp_subscript */
1865         (objobjargproc)Map_SetItem,     /*objobjargproc mp_ass_subscript */
1866 };
1867
1868 PySequenceMethods KX_GameObject::Sequence = {
1869         NULL,           /* Cant set the len otherwise it can evaluate as false */
1870         NULL,           /* sq_concat */
1871         NULL,           /* sq_repeat */
1872         NULL,           /* sq_item */
1873         NULL,           /* sq_slice */
1874         NULL,           /* sq_ass_item */
1875         NULL,           /* sq_ass_slice */
1876         (objobjproc)Seq_Contains,       /* sq_contains */
1877         (binaryfunc) NULL, /* sq_inplace_concat */
1878         (ssizeargfunc) NULL, /* sq_inplace_repeat */
1879 };
1880
1881 PyTypeObject KX_GameObject::Type = {
1882         PyVarObject_HEAD_INIT(NULL, 0)
1883         "KX_GameObject",
1884         sizeof(PyObjectPlus_Proxy),
1885         0,
1886         py_base_dealloc,
1887         0,
1888         0,
1889         0,
1890         0,
1891         py_base_repr,
1892         0,
1893         &Sequence,
1894         &Mapping,
1895         0,0,0,
1896         NULL,
1897         NULL,
1898         0,
1899         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
1900         0,0,0,0,0,0,0,
1901         Methods,
1902         0,
1903         0,
1904         &SCA_IObject::Type,
1905         0,0,0,0,0,0,
1906         py_base_new
1907 };
1908
1909 PyObject* KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1910 {
1911         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1912         return PyUnicode_From_STR_String(self->GetName());
1913 }
1914
1915 PyObject* KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1916 {
1917         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1918         KX_GameObject* parent = self->GetParent();
1919         if (parent) {
1920                 parent->Release(); /* self->GetParent() AddRef's */
1921                 return parent->GetProxy();
1922         }
1923         Py_RETURN_NONE;
1924 }
1925
1926 PyObject* KX_GameObject::pyattr_get_life(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1927 {
1928         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1929
1930         CValue *life = self->GetProperty("::timebomb");
1931         if (life)
1932                 // this convert the timebomb seconds to frames, hard coded 50.0 (assuming 50fps)
1933                 // value hardcoded in KX_Scene::AddReplicaObject()
1934                 return PyFloat_FromDouble(life->GetNumber() * 50.0);
1935         else
1936                 Py_RETURN_NONE;
1937 }
1938
1939 PyObject* KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1940 {
1941         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1942         KX_IPhysicsController *spc = self->GetPhysicsController();
1943         return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0);
1944 }
1945
1946 int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1947 {
1948         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1949         KX_IPhysicsController *spc = self->GetPhysicsController();
1950         MT_Scalar val = PyFloat_AsDouble(value);
1951         if (val < 0.0) { /* also accounts for non float */
1952                 PyErr_SetString(PyExc_AttributeError, "gameOb.mass = float: KX_GameObject, expected a float zero or above");
1953                 return PY_SET_ATTR_FAIL;
1954         }
1955
1956         if (spc)
1957                 spc->SetMass(val);
1958
1959         return PY_SET_ATTR_SUCCESS;
1960 }
1961
1962 PyObject* KX_GameObject::pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1963 {
1964         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1965         KX_IPhysicsController *spc = self->GetPhysicsController();
1966         return PyFloat_FromDouble(spc ? spc->GetLinVelocityMin() : 0.0f);
1967 }
1968
1969 int KX_GameObject::pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1970 {
1971         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1972         KX_IPhysicsController *spc = self->GetPhysicsController();
1973         MT_Scalar val = PyFloat_AsDouble(value);
1974         if (val < 0.0) { /* also accounts for non float */
1975                 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMin = float: KX_GameObject, expected a float zero or above");
1976                 return PY_SET_ATTR_FAIL;
1977         }
1978
1979         if (spc)
1980                 spc->SetLinVelocityMin(val);
1981
1982         return PY_SET_ATTR_SUCCESS;
1983 }
1984
1985 PyObject* KX_GameObject::pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1986 {
1987         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1988         KX_IPhysicsController *spc = self->GetPhysicsController();
1989         return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
1990 }
1991
1992 int KX_GameObject::pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1993 {
1994         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1995         KX_IPhysicsController *spc = self->GetPhysicsController();
1996         MT_Scalar val = PyFloat_AsDouble(value);
1997         if (val < 0.0) { /* also accounts for non float */
1998                 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMax = float: KX_GameObject, expected a float zero or above");
1999                 return PY_SET_ATTR_FAIL;
2000         }
2001
2002         if (spc)
2003                 spc->SetLinVelocityMax(val);
2004
2005         return PY_SET_ATTR_SUCCESS;
2006 }
2007
2008
2009 PyObject* KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2010 {
2011         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2012         return PyBool_FromLong(self->GetVisible());
2013 }
2014
2015 int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2016 {
2017         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2018         int param = PyObject_IsTrue( value );
2019         if (param == -1) {
2020                 PyErr_SetString(PyExc_AttributeError, "gameOb.visible = bool: KX_GameObject, expected True or False");
2021                 return PY_SET_ATTR_FAIL;
2022         }
2023
2024         self->SetVisible(param, false);
2025         self->UpdateBuckets(false);
2026         return PY_SET_ATTR_SUCCESS;
2027 }
2028
2029 PyObject* KX_GameObject::pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2030 {
2031 #ifdef USE_MATHUTILS
2032         return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_GLOBAL);
2033 #else
2034         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2035         return PyObjectFrom(self->NodeGetWorldPosition());
2036 #endif
2037 }
2038
2039 int KX_GameObject::pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2040 {
2041         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2042         MT_Point3 pos;
2043         if (!PyVecTo(value, pos))
2044                 return PY_SET_ATTR_FAIL;
2045         
2046         self->NodeSetWorldPosition(pos);
2047         self->NodeUpdateGS(0.f);
2048         return PY_SET_ATTR_SUCCESS;
2049 }
2050
2051 PyObject* KX_GameObject::pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2052 {
2053 #ifdef USE_MATHUTILS    
2054         return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_LOCAL);
2055 #else   
2056         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2057         return PyObjectFrom(self->NodeGetLocalPosition());
2058 #endif
2059 }
2060
2061 int KX_GameObject::pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2062 {
2063         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2064         MT_Point3 pos;
2065         if (!PyVecTo(value, pos))
2066                 return PY_SET_ATTR_FAIL;
2067         
2068         self->NodeSetLocalPosition(pos);
2069         self->NodeUpdateGS(0.f);
2070         return PY_SET_ATTR_SUCCESS;
2071 }
2072
2073 PyObject* KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2074 {
2075 #ifdef USE_MATHUTILS
2076         return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_INERTIA_LOCAL);
2077 #else
2078         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2079         if (self->GetPhysicsController())
2080                 return PyObjectFrom(self->GetPhysicsController()->GetLocalInertia());
2081         return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
2082 #endif
2083 }
2084
2085 PyObject* KX_GameObject::pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2086 {
2087 #ifdef USE_MATHUTILS
2088         return Matrix_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, 3, mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_GLOBAL);
2089 #else
2090         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2091         return PyObjectFrom(self->NodeGetWorldOrientation());
2092 #endif
2093 }
2094
2095 int KX_GameObject::pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2096 {
2097         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2098         
2099         /* if value is not a sequence PyOrientationTo makes an error */
2100         MT_Matrix3x3 rot;
2101         if (!PyOrientationTo(value, rot, "gameOb.worldOrientation = sequence: KX_GameObject, "))
2102                 return PY_SET_ATTR_FAIL;
2103
2104         self->NodeSetGlobalOrientation(rot);
2105         
2106         self->NodeUpdateGS(0.f);
2107         return PY_SET_ATTR_SUCCESS;
2108 }
2109
2110 PyObject* KX_GameObject::pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2111 {
2112 #ifdef USE_MATHUTILS
2113         return Matrix_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, 3, mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_LOCAL);
2114 #else
2115         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2116         return PyObjectFrom(self->NodeGetLocalOrientation());
2117 #endif
2118 }
2119
2120 int KX_GameObject::pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2121 {
2122         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2123         
2124         /* if value is not a sequence PyOrientationTo makes an error */
2125         MT_Matrix3x3 rot;
2126         if (!PyOrientationTo(value, rot, "gameOb.localOrientation = sequence: KX_GameObject, "))
2127                 return PY_SET_ATTR_FAIL;
2128
2129         self->NodeSetLocalOrientation(rot);
2130         self->NodeUpdateGS(0.f);
2131         return PY_SET_ATTR_SUCCESS;
2132 }
2133
2134 PyObject* KX_GameObject::pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2135 {
2136 #ifdef USE_MATHUTILS
2137         return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_GLOBAL);
2138 #else
2139         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2140         return PyObjectFrom(self->NodeGetWorldScaling());
2141 #endif
2142 }
2143
2144 int KX_GameObject::pyattr_set_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2145 {
2146         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2147         MT_Vector3 scale;
2148         if (!PyVecTo(value, scale))
2149                 return PY_SET_ATTR_FAIL;
2150
2151         self->NodeSetWorldScale(scale);
2152         self->NodeUpdateGS(0.f);
2153         return PY_SET_ATTR_SUCCESS;
2154 }
2155
2156 PyObject* KX_GameObject::pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2157 {
2158 #ifdef USE_MATHUTILS
2159         return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_LOCAL);
2160 #else
2161         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2162         return PyObjectFrom(self->NodeGetLocalScaling());
2163 #endif
2164 }
2165
2166 int KX_GameObject::pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2167 {
2168         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2169         MT_Vector3 scale;
2170         if (!PyVecTo(value, scale))
2171                 return PY_SET_ATTR_FAIL;
2172
2173         self->NodeSetLocalScale(scale);
2174         self->NodeUpdateGS(0.f);
2175         return PY_SET_ATTR_SUCCESS;
2176 }
2177
2178 PyObject* KX_GameObject::pyattr_get_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2179 {
2180         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2181
2182         double *mat = MT_CmMatrix4x4().getPointer();
2183
2184         MT_Transform trans;
2185         
2186         trans.setOrigin(self->GetSGNode()->GetLocalPosition());
2187         trans.setBasis(self->GetSGNode()->GetLocalOrientation());
2188         
2189         MT_Vector3 scaling = self->GetSGNode()->GetLocalScale();
2190         trans.scale(scaling[0], scaling[1], scaling[2]);
2191
2192         trans.getValue(mat);
2193
2194         return PyObjectFrom(MT_Matrix4x4(mat));
2195 }
2196
2197 int KX_GameObject::pyattr_set_localTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2198 {
2199         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2200         MT_Matrix4x4 temp;
2201         if (!PyMatTo(value, temp))
2202                 return PY_SET_ATTR_FAIL;
2203
2204         float transform[4][4];
2205         float loc[3], size[3];
2206         float rot[3][3];
2207         MT_Matrix3x3 orientation;
2208
2209         temp.getValue(*transform);
2210         mat4_to_loc_rot_size(loc, rot, size, transform);
2211
2212         self->NodeSetLocalPosition(MT_Point3(loc));
2213
2214         //MT_Matrix3x3's constructor expects a 4x4 matrix
2215         orientation = MT_Matrix3x3();
2216         orientation.setValue3x3(*rot);
2217         self->NodeSetLocalOrientation(orientation);
2218
2219         self->NodeSetLocalScale(MT_Vector3(size));
2220
2221         return PY_SET_ATTR_SUCCESS;
2222 }
2223
2224 PyObject* KX_GameObject::pyattr_get_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2225 {
2226         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2227
2228         return PyObjectFrom(MT_Matrix4x4(self->GetOpenGLMatrix()));
2229 }
2230
2231 int KX_GameObject::pyattr_set_worldTransform(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2232 {
2233         KX_GameObject* self = static_cast<KX_GameObject*>(self_v);
2234         MT_Matrix4x4 temp;
2235         if (!PyMatTo(value, temp))
2236                 return PY_SET_ATTR_FAIL;
2237
2238         float transform[4][4];
2239         float loc[3], size[3];
2240         float rot[3][3];
2241         MT_Matrix3x3 orientation;
2242
2243         temp.getValue(*transform);
2244         mat4_to_loc_rot_size(loc, rot, size, transform);
2245
2246         self->NodeSetWorldPosition(MT_Point3(loc));
2247
2248         //MT_Matrix3x3's constructor expects a 4x4 matrix
2249         orientation = MT_Matrix3x3();
2250         orientation.setValue3x3(*rot);
2251         self->NodeSetGlobalOrientation(orientation);
2252
2253         self->NodeSetWorldScale(MT_Vector3(size));
2254
2255         return PY_SET_ATTR_SUCCESS;
2256 }
2257
2258 PyObject* KX_GameObject::pyattr_get_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2259 {
2260 #ifdef USE_MATHUTILS
2261         return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_GLOBAL);
2262 #else
2263         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2264         return PyObjectFrom(GetLinearVelocity(false));
2265 #endif
2266 }
2267
2268 int KX_GameObject::pyattr_set_worldLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2269 {
2270         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2271         MT_Vector3 velocity;
2272         if (!PyVecTo(value, velocity))
2273                 return PY_SET_ATTR_FAIL;
2274
2275         self->setLinearVelocity(velocity, false);
2276
2277         return PY_SET_ATTR_SUCCESS;
2278 }
2279
2280 PyObject* KX_GameObject::pyattr_get_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2281 {
2282 #ifdef USE_MATHUTILS
2283         return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_LINVEL_LOCAL);
2284 #else
2285         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2286         return PyObjectFrom(GetLinearVelocity(true));
2287 #endif
2288 }
2289
2290 int KX_GameObject::pyattr_set_localLinearVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2291 {
2292         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2293         MT_Vector3 velocity;
2294         if (!PyVecTo(value, velocity))
2295                 return PY_SET_ATTR_FAIL;
2296
2297         self->setLinearVelocity(velocity, true);
2298
2299         return PY_SET_ATTR_SUCCESS;
2300 }
2301
2302 PyObject* KX_GameObject::pyattr_get_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2303 {
2304 #ifdef USE_MATHUTILS
2305         return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_GLOBAL);
2306 #else
2307         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2308         return PyObjectFrom(GetAngularVelocity(false));
2309 #endif
2310 }
2311
2312 int KX_GameObject::pyattr_set_worldAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2313 {
2314         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2315         MT_Vector3 velocity;
2316         if (!PyVecTo(value, velocity))
2317                 return PY_SET_ATTR_FAIL;
2318
2319         self->setAngularVelocity(velocity, false);
2320
2321         return PY_SET_ATTR_SUCCESS;
2322 }
2323
2324 PyObject* KX_GameObject::pyattr_get_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2325 {
2326 #ifdef USE_MATHUTILS
2327         return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_ANGVEL_LOCAL);
2328 #else
2329         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2330         return PyObjectFrom(GetAngularVelocity(true));
2331 #endif
2332 }
2333
2334 int KX_GameObject::pyattr_set_localAngularVelocity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2335 {
2336         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2337         MT_Vector3 velocity;
2338         if (!PyVecTo(value, velocity))
2339                 return PY_SET_ATTR_FAIL;
2340
2341         self->setAngularVelocity(velocity, true);
2342
2343         return PY_SET_ATTR_SUCCESS;
2344 }
2345
2346
2347 PyObject* KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2348 {
2349         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2350         SG_Node* sg_parent;
2351         if (self->GetSGNode() && (sg_parent = self->GetSGNode()->GetSGParent()) != NULL && sg_parent->IsSlowParent()) {
2352                 return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->GetTimeOffset());
2353         } else {
2354                 return PyFloat_FromDouble(0.0);
2355         }
2356 }
2357
2358 int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2359 {
2360         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2361         if (self->GetSGNode()) {
2362                 MT_Scalar val = PyFloat_AsDouble(value);
2363                 SG_Node *sg_parent= self->GetSGNode()->GetSGParent();
2364                 if (val < 0.0) { /* also accounts for non float */
2365                         PyErr_SetString(PyExc_AttributeError, "gameOb.timeOffset = float: KX_GameObject, expected a float zero or above");
2366                         return PY_SET_ATTR_FAIL;
2367                 }
2368                 if (sg_parent && sg_parent->IsSlowParent())
2369                         static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->SetTimeOffset(val);
2370         }
2371         return PY_SET_ATTR_SUCCESS;
2372 }
2373
2374 PyObject* KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2375 {
2376         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2377         int state = 0;
2378         state |= self->GetState();
2379         return PyLong_FromSsize_t(state);
2380 }
2381
2382 int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2383 {
2384         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2385         int state_i = PyLong_AsSsize_t(value);
2386         unsigned int state = 0;
2387         
2388         if (state_i == -1 && PyErr_Occurred()) {
2389                 PyErr_SetString(PyExc_TypeError, "gameOb.state = int: KX_GameObject, expected an int bit field");
2390                 return PY_SET_ATTR_FAIL;
2391         }
2392         
2393         state |= state_i;
2394         if ((state & ((1<<30)-1)) == 0) {
2395                 PyErr_SetString(PyExc_AttributeError, "gameOb.state = int: KX_GameObject, state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
2396                 return PY_SET_ATTR_FAIL;
2397         }
2398         self->SetState(state);
2399         return PY_SET_ATTR_SUCCESS;
2400 }
2401
2402 PyObject* KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2403 {
2404         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2405         PyObject *meshes= PyList_New(self->m_meshes.size());
2406         int i;
2407         
2408         for (i=0; i < (int)self->m_meshes.size(); i++)
2409         {
2410                 KX_MeshProxy* meshproxy = new KX_MeshProxy(self->m_meshes[i]);
2411                 PyList_SET_ITEM(meshes, i, meshproxy->NewProxy(true));
2412         }
2413         
2414         return meshes;
2415 }
2416
2417 PyObject* KX_GameObject::pyattr_get_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2418 {
2419 #ifdef USE_MATHUTILS
2420         return Vector_CreatePyObject_cb(BGE_PROXY_FROM_REF(self_v), 4, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_OBJECT_COLOR);
2421 #else
2422         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2423         return PyObjectFrom(self->GetObjectColor());
2424 #endif
2425 }
2426
2427 int KX_GameObject::pyattr_set_obcolor(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2428 {
2429         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2430         MT_Vector4 obcolor;
2431         if (!PyVecTo(value, obcolor))
2432                 return PY_SET_ATTR_FAIL;
2433
2434         self->SetObjectColor(obcolor);
2435         return PY_SET_ATTR_SUCCESS;
2436 }
2437
2438 /* These are experimental! */
2439 PyObject* KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2440 {
2441         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_SENSORS);
2442 }
2443
2444 PyObject* KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2445 {
2446         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_CONTROLLERS);
2447 }
2448
2449 PyObject* KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2450 {
2451         return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_ACTUATORS);
2452 }
2453 /* End experimental */
2454
2455 PyObject* KX_GameObject::pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2456 {
2457         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2458         return self->GetChildren()->NewProxy(true);
2459 }
2460
2461 PyObject* KX_GameObject::pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2462 {
2463         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2464         return self->GetChildrenRecursive()->NewProxy(true);
2465 }
2466
2467 PyObject* KX_GameObject::pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2468 {
2469         KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2470         
2471         if (self->m_attr_dict==NULL)
2472                 self->m_attr_dict= PyDict_New();
2473         
2474         Py_INCREF(self->m_attr_dict);
2475         return self->m_attr_dict;
2476 }
2477
2478 PyObject* KX_GameObject::PyApplyForce(PyObject* args)
2479 {
2480         int local = 0;
2481         PyObject* pyvect;
2482
2483         if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) {
2484                 MT_Vector3 force;
2485                 if (PyVecTo(pyvect, force)) {
2486                         ApplyForce(force, (local!=0));
2487                         Py_RETURN_NONE;
2488                 }
2489         }
2490         return NULL;
2491 }
2492
2493 PyObject* KX_GameObject::PyApplyTorque(PyObject* args)
2494 {
2495         int local = 0;
2496         PyObject* pyvect;
2497
2498         if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) {
2499                 MT_Vector3 torque;
2500                 if (PyVecTo(pyvect, torque)) {
2501                         ApplyTorque(torque, (local!=0));
2502                         Py_RETURN_NONE;
2503                 }
2504         }
2505         return NULL;
2506 }
2507
2508 PyObject* KX_GameObject::PyApplyRotation(PyObject* args)
2509 {
2510         int local = 0;
2511         PyObject* pyvect;
2512
2513         if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) {
2514                 MT_Vector3 rotation;
2515                 if (PyVecTo(pyvect, rotation)) {
2516                         ApplyRotation(rotation, (local!=0));
2517                         Py_RETURN_NONE;
2518                 }
2519         }
2520         return NULL;
2521 }
2522
2523 PyObject* KX_GameObject::PyApplyMovement(PyObject* args)
2524 {
2525         int local = 0;
2526         PyObject* pyvect;
2527
2528         if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) {
2529                 MT_Vector3 movement;
2530                 if (PyVecTo(pyvect, movement)) {
2531                         ApplyMovement(movement, (local!=0));
2532                         Py_RETURN_NONE;
2533                 }
2534         }
2535         return NULL;
2536 }
2537
2538 PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* args)
2539 {
2540         // only can get the velocity if we have a physics object connected to us...
2541         int local = 0;
2542         if (PyArg_ParseTuple(args,"|i:getLinearVelocity",&local))
2543         {
2544                 return PyObjectFrom(GetLinearVelocity((local!=0)));
2545         }
2546         else
2547         {
2548                 return NULL;
2549         }
2550 }
2551
2552 PyObject* KX_GameObject::PySetLinearVelocity(PyObject* args)
2553 {
2554         int local = 0;
2555         PyObject* pyvect;
2556         
2557         if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) {
2558                 MT_Vector3 velocity;
2559                 if (PyVecTo(pyvect, velocity)) {
2560                         setLinearVelocity(velocity, (local!=0));
2561                         Py_RETURN_NONE;
2562                 }
2563         }
2564         return NULL;
2565 }
2566
2567 PyObject* KX_GameObject::PyGetAngularVelocity(PyObject* args)
2568 {
2569         // only can get the velocity if we have a physics object connected to us...
2570         int local = 0;
2571         if (PyArg_ParseTuple(args,"|i:getAngularVelocity",&local))
2572         {
2573                 return PyObjectFrom(GetAngularVelocity((local!=0)));
2574         }
2575         else
2576         {
2577                 return NULL;
2578         }
2579 }
2580
2581 PyObject* KX_GameObject::PySetAngularVelocity(PyObject* args)
2582 {
2583         int local = 0;
2584         PyObject* pyvect;
2585         
2586         if (PyArg_ParseTuple(args,"O|i:setAngularVelocity",&pyvect,&local)) {
2587                 MT_Vector3 velocity;
2588                 if (PyVecTo(pyvect, velocity)) {
2589                         setAngularVelocity(velocity, (local!=0));
2590                         Py_RETURN_NONE;
2591                 }
2592         }
2593         return NULL;
2594 }
2595
2596 PyObject* KX_GameObject::PySetVisible(PyObject* args)
2597 {
2598         int visible, recursive = 0;
2599         if (!PyArg_ParseTuple(args,"i|i:setVisible",&visible, &recursive))
2600                 return NULL;
2601         
2602         SetVisible(visible ? true:false, recursive ? true:false);
2603         UpdateBuckets(recursive ? true:false);
2604         Py_RETURN_NONE;
2605         
2606 }
2607
2608 PyObject* KX_GameObject::PySetOcclusion(PyObject* args)
2609 {
2610         int occlusion, recursive = 0;
2611         if (!PyArg_ParseTuple(args,"i|i:setOcclusion",&occlusion, &recursive))
2612                 return NULL;
2613         
2614         SetOccluder(occlusion ? true:false, recursive ? true:false);
2615         Py_RETURN_NONE;
2616 }
2617
2618 PyObject* KX_GameObject::PyGetVelocity(PyObject* args)
2619 {
2620         // only can get the velocity if we have a physics object connected to us...
2621         MT_Point3 point(0.0,0.0,0.0);
2622         PyObject* pypos = NULL;
2623         
2624         if (!PyArg_ParseTuple(args, "|O:getVelocity", &pypos) || (pypos && !PyVecTo(pypos, point)))
2625                 return NULL;
2626         
2627         if (m_pPhysicsController1)
2628         {
2629                 return PyObjectFrom(m_pPhysicsController1->GetVelocity(point));
2630         }
2631         else {
2632                 return PyObjectFrom(MT_Vector3(0.0,0.0,0.0));
2633         }
2634 }
2635
2636 PyObject* KX_GameObject::PyGetReactionForce()
2637 {
2638         // only can get the velocity if we have a physics object connected to us...
2639         
2640         // XXX - Currently not working with bullet intergration, see KX_BulletPhysicsController.cpp's getReactionForce
2641         /*
2642         if (GetPhysicsController())
2643                 return PyObjectFrom(GetPhysicsController()->getReactionForce());
2644         return PyObjectFrom(dummy_point);
2645         */
2646         
2647         return Py_BuildValue("fff", 0.0, 0.0, 0.0);
2648         
2649 }
2650
2651
2652
2653 PyObject* KX_GameObject::PyEnableRigidBody()
2654 {
2655         if (GetPhysicsController())
2656                 GetPhysicsController()->setRigidBody(true);
2657
2658         Py_RETURN_NONE;
2659 }
2660
2661
2662
2663 PyObject* KX_GameObject::PyDisableRigidBody()
2664 {
2665         if (GetPhysicsController())
2666                 GetPhysicsController()->setRigidBody(false);
2667
2668         Py_RETURN_NONE;
2669 }
2670
2671
2672 PyObject* KX_GameObject::PySetParent(PyObject* args)
2673 {
2674         KX_Scene *scene = KX_GetActiveScene();
2675         PyObject* pyobj;
2676         KX_GameObject *obj;
2677         int addToCompound=1, ghost=1;
2678         
2679         if (!PyArg_ParseTuple(args,"O|ii:setParent", &pyobj, &addToCompound, &ghost)) {
2680                 return NULL; // Python sets a simple error
2681         }
2682         if (!ConvertPythonToGameObject(pyobj, &obj, true, "gameOb.setParent(obj): KX_GameObject"))
2683                 return NULL;
2684         if (obj)
2685                 this->SetParent(scene, obj, addToCompound, ghost);
2686         Py_RETURN_NONE;
2687 }
2688
2689 PyObject* KX_GameObject::PyRemoveParent()
2690 {
2691         KX_Scene *scene = KX_GetActiveScene();
2692         
2693         this->RemoveParent(scene);
2694         Py_RETURN_NONE;
2695 }
2696
2697
2698 PyObject* KX_GameObject::PySetCollisionMargin(PyObject* value)
2699 {
2700         float collisionMargin = PyFloat_AsDouble(value);
2701         
2702         if (collisionMargin==-1 && PyErr_Occurred()) {
2703                 PyErr_SetString(PyExc_TypeError, "expected a float");
2704                 return NULL;
2705         }
2706         
2707         if (m_pPhysicsController1)
2708         {
2709                 m_pPhysicsController1->setMargin(collisionMargin);
2710                 Py_RETURN_NONE;
2711         }
2712         PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
2713         return NULL;
2714 }
2715
2716
2717
2718 PyObject* KX_GameObject::PyApplyImpulse(PyObject* args)
2719 {
2720         PyObject* pyattach;
2721         PyObject* pyimpulse;
2722         
2723         if (!m_pPhysicsController1)     {
2724                 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
2725                 return NULL;
2726         }
2727         
2728         if (PyArg_ParseTuple(args, "OO:applyImpulse", &pyattach, &pyimpulse))
2729         {
2730                 MT_Point3  attach;
2731                 MT_Vector3 impulse;
2732                 if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
2733                 {
2734                         m_pPhysicsController1->applyImpulse(attach, impulse);
2735                         Py_RETURN_NONE;
2736                 }
2737
2738         }
2739         
2740         return NULL;
2741 }
2742
2743
2744
2745 PyObject* KX_GameObject::PySuspendDynamics()
2746 {
2747         SuspendDynamics();
2748         Py_RETURN_NONE;
2749 }
2750
2751
2752
2753 PyObject* KX_GameObject::PyRestoreDynamics()
2754 {
2755         RestoreDynamics();
2756         Py_RETURN_NONE;
2757 }
2758
2759
2760 PyObject* KX_GameObject::PyAlignAxisToVect(PyObject* args)
2761 {
2762         PyObject* pyvect;
2763         int axis = 2; //z axis is the default
2764         float fac = 1.0f;
2765         
2766         if (PyArg_ParseTuple(args,"O|if:alignAxisToVect",&pyvect,&axis, &fac))
2767         {
2768                 MT_Vector3 vect;
2769                 if (PyVecTo(pyvect, vect)) {
2770                         if (fac > 0.0f) {
2771                                 if (fac> 1.0f) fac = 1.0f;
2772
2773                                 AlignAxisToVect(vect, axis, fac);
2774                                 NodeUpdateGS(0.f);
2775                         }
2776                         Py_RETURN_NONE;
2777                 }
2778         }
2779         return NULL;
2780 }
2781
2782 PyObject* KX_GameObject::PyGetAxisVect(PyObject* value)
2783 {
2784         MT_Vector3 vect;
2785         if (PyVecTo(value, vect))
2786         {
2787                 return PyObjectFrom(NodeGetWorldOrientation() * vect);
2788         }
2789         return NULL;
2790 }
2791
2792
2793 PyObject* KX_GameObject::PyGetPhysicsId()
2794 {
2795         KX_IPhysicsController* ctrl = GetPhysicsController();
2796         uint_ptr physid=0;
2797         if (ctrl)
2798         {
2799                 physid= (uint_ptr)ctrl->GetUserData();
2800         }
2801         return PyLong_FromSsize_t((long)physid);
2802 }
2803
2804 PyObject* KX_GameObject::PyGetPropertyNames()
2805 {
2806         PyObject *list= ConvertKeysToPython();
2807         
2808         if (m_attr_dict) {
2809                 PyObject *key, *value;
2810                 Py_ssize_t pos = 0;
2811
2812                 while (PyDict_Next(m_attr_dict, &pos, &key, &value)) {
2813                         PyList_Append(list, key);
2814                 }
2815         }
2816         return list;
2817 }
2818
2819 KX_PYMETHODDEF_DOC_O(KX_GameObject, getDistanceTo,
2820 "getDistanceTo(other): get distance to another point/KX_GameObject")
2821 {
2822         MT_Point3 b;
2823         if (PyVecTo(value, b))
2824         {
2825                 return PyFloat_FromDouble(NodeGetWorldPosition().distance(b));
2826         }
2827         PyErr_Clear();
2828         
2829         KX_GameObject *other;
2830         if (ConvertPythonToGameObject(value, &other, false, "gameOb.getDistanceTo(value): KX_GameObject"))
2831         {
2832                 return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition()));
2833         }
2834         
2835         return NULL;
2836 }
2837
2838 KX_PYMETHODDEF_DOC_O(KX_GameObject, getVectTo,
2839 "getVectTo(other): get vector and the distance to another point/KX_GameObject\n"
2840 "Returns a 3-tuple with (distance,worldVector,localVector)\n")
2841 {
2842         MT_Point3 toPoint, fromPoint;
2843         MT_Vector3 toDir, locToDir;
2844         MT_Scalar distance;
2845
2846         PyObject *returnValue;
2847
2848         if (!PyVecTo(value, toPoint))
2849         {
2850                 PyErr_Clear();
2851                 
2852                 KX_GameObject *other;
2853                 if (ConvertPythonToGameObject(value, &other, false, "")) /* error will be overwritten */
2854                 {
2855                         toPoint = other->NodeGetWorldPosition();
2856                 } else
2857                 {
2858                         PyErr_SetString(PyExc_TypeError, "gameOb.getVectTo(other): KX_GameObject, expected a 3D Vector or KX_GameObject type");
2859                         return NULL;
2860                 }
2861         }
2862
2863         fromPoint = NodeGetWorldPosition();
2864         toDir = toPoint-fromPoint;
2865         distance = toDir.length();
2866
2867         if (MT_fuzzyZero(distance))
2868         {
2869                 //cout << "getVectTo() Error: Null vector!\n";
2870                 locToDir = toDir = MT_Vector3(0.0,0.0,0.0);
2871                 distance = 0.0;
2872         } else {
2873                 toDir.normalize();
2874                 locToDir = toDir * NodeGetWorldOrientation();
2875         }
2876         
2877         returnValue = PyTuple_New(3);
2878         if (returnValue) { // very unlikely to fail, python sets a memory error here.
2879                 PyTuple_SET_ITEM(returnValue, 0, PyFloat_FromDouble(distance));
2880                 PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(toDir));
2881                 PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(locToDir));
2882         }
2883         return returnValue;
2884 }
2885
2886 bool KX_GameObject::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
2887 {
2888         KX_GameObject* hitKXObj = client->m_gameobject;
2889         
2890         // if X-ray option is selected, the unwnted objects were not tested, so get here only with true hit
2891         // if not, all objects were tested and the front one may not be the correct one.
2892         if (m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
2893         {
2894                 m_pHitObject = hitKXObj;
2895                 return true;
2896         }
2897         // return true to stop RayCast::RayTest from looping, the above test was decisive
2898         // We would want to loop only if we want to get more than one hit point
2899         return true;
2900 }
2901
2902 /* this function is used to pre-filter the object before casting the ray on them.
2903  * This is useful for "X-Ray" option when we want to see "through" unwanted object.
2904  */
2905 bool KX_GameObject::NeedRayCast(KX_ClientObjectInfo* client)
2906 {
2907         KX_GameObject* hitKXObj = client->m_gameobject;
2908         
2909         if (client->m_type > KX_ClientObjectInfo::ACTOR)
2910         {
2911                 // Unknown type of object, skip it.
2912                 // Should not occur as the sensor objects are filtered in RayTest()
2913                 printf("Invalid client type %d found in ray casting\n", client->m_type);
2914                 return false;
2915         }
2916         
2917         // if X-Ray option is selected, skip object that don't match the criteria as we see through them
2918         // if not, test all objects because we don't know yet which one will be on front
2919         if (!m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
2920         {
2921                 return true;
2922         }
2923         // skip the object
2924         return false;
2925 }
2926
2927 KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
2928 "rayCastTo(other,dist,prop): look towards another point/KX_GameObject and return first object hit within dist that matches prop\n"
2929 " prop = property name that object must have; can be omitted => detect any object\n"
2930 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to other\n"
2931 " other = 3-tuple or object reference")
2932 {
2933         MT_Point3 toPoint;
2934         PyObject* pyarg;
2935         float dist = 0.0f;
2936         char *propName = NULL;
2937
2938         if (!PyArg_ParseTuple(args,"O|fs:rayCastTo", &pyarg, &dist, &propName)) {
2939                 return NULL; // python sets simple error
2940         }
2941
2942         if (!PyVecTo(pyarg, toPoint))
2943         {
2944                 KX_GameObject *other;
2945                 PyErr_Clear();
2946                 
2947                 if (ConvertPythonToGameObject(pyarg, &other, false, "")) /* error will be overwritten */
2948                 {
2949                         toPoint = other->NodeGetWorldPosition();
2950                 } else
2951                 {
2952                         PyErr_SetString(PyExc_TypeError, "gameOb.rayCastTo(other,dist,prop): KX_GameObject, the first argument to rayCastTo must be a vector or a KX_GameObject");
2953                         return NULL;
2954                 }
2955         }
2956         MT_Point3 fromPoint = NodeGetWorldPosition();
2957         
2958         if (dist != 0.0f)
2959                 toPoint = fromPoint + dist * (toPoint-fromPoint).safe_normalized();
2960         
2961         PHY_IPhysicsEnvironment* pe = KX_GetActiveScene()->GetPhysicsEnvironment();
2962         KX_IPhysicsController *spc = GetPhysicsController();
2963         KX_GameObject *parent = GetParent();
2964         if (!spc && parent)
2965                 spc = parent->GetPhysicsController();
2966         if (parent)
2967                 parent->Release();
2968         
2969         m_pHitObject = NULL;
2970         if (propName)
2971                 m_testPropName = propName;
2972         else
2973                 m_testPropName.SetLength(0);
2974         KX_RayCast::Callback<KX_GameObject> callback(this,spc);
2975         KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
2976
2977         if (m_pHitObject)
2978                 return m_pHitObject->GetProxy();
2979         
2980         Py_RETURN_NONE;
2981 }
2982
2983 /* faster then Py_BuildValue since some scripts call raycast a lot */
2984 static PyObject *none_tuple_3()
2985 {
2986         PyObject *ret= PyTuple_New(3);
2987         PyTuple_SET_ITEM(ret, 0, Py_None);
2988         PyTuple_SET_ITEM(ret, 1, Py_None);
2989         PyTuple_SET_ITEM(ret, 2, Py_None);
2990         
2991         Py_INCREF(Py_None);
2992         Py_INCREF(Py_None);
2993         Py_INCREF(Py_None);
2994         return ret;
2995 }
2996 static PyObject *none_tuple_4()
2997 {
2998         PyObject *ret= PyTuple_New(4);
2999         PyTuple_SET_ITEM(ret, 0, Py_None);
3000         PyTuple_SET_ITEM(ret, 1, Py_None);
3001         PyTuple_SET_ITEM(ret, 2, Py_None);
3002         PyTuple_SET_ITEM(ret, 3, Py_None);
3003         
3004         Py_INCREF(Py_None);
3005         Py_INCREF(Py_None);
3006         Py_INCREF(Py_None);
3007         Py_INCREF(Py_None);
3008         return ret;
3009 }
3010
3011 static PyObject *none_tuple_5()
3012 {
3013         PyObject *ret= PyTuple_New(5);
3014         PyTuple_SET_ITEM(ret, 0, Py_None);
3015         PyTuple_SET_ITEM(ret, 1, Py_None);
3016         PyTuple_SET_ITEM(ret, 2, Py_None);
3017         PyTuple_SET_ITEM(ret, 3, Py_None);
3018         PyTuple_SET_ITEM(ret, 4, Py_None);
3019         
3020         Py_INCREF(Py_None);
3021         Py_INCREF(Py_None);
3022         Py_INCREF(Py_None);
3023         Py_INCREF(Py_None);
3024         Py_INCREF(Py_None);
3025         return ret;
3026 }
3027
3028 KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
3029                                    "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"
3030                                    " If no hit, return (None,None,None) or (None,None,None,None) or (None,None,None,None,None).\n"
3031 " to   = 3-tuple or object reference for destination of ray (if object, use center of object)\n"
3032 " from = 3-tuple or object reference for origin of ray (if object, use center of object)\n"
3033 "        Can be None or omitted => start from self object center\n"
3034 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to to\n"
3035 " prop = property name that object must have; can be omitted => detect any object\n"
3036 " face = normal option: 1=>return face normal; 0 or omitted => normal is oriented towards origin\n"
3037 " xray = X-ray option: 1=>skip objects that don't match prop; 0 or omitted => stop on first object\n"
3038 " poly = polygon option: 1=>return value is a 4-tuple and the 4th element is a KX_PolyProxy object\n"
3039 "                           which can be None if hit object has no mesh or if there is no hit\n"
3040 "                        2=>return value is a 5-tuple, the 4th element is the KX_PolyProxy object\n"
3041 "                           and the 5th element is the vector of UV coordinates at the hit point of the None if there is no UV mapping\n"
3042 "        If 0 or omitted, return value is a 3-tuple\n"
3043 "Note: The object on which you call this method matters: the ray will ignore it.\n"
3044 "      prop and xray option interact as follow:\n"
3045 "        prop off, xray off: return closest hit or no hit if there is no object on the full extend of the ray\n"
3046 "        prop off, xray on : idem\n"
3047 "        prop on,  xray off: return closest hit if it matches prop, no hit otherwise\n"
3048 "        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")
3049 {
3050         MT_Point3 toPoint;
3051         MT_Point3 fromPoint;
3052         PyObject* pyto;
3053         PyObject* pyfrom = NULL;
3054         float dist = 0.0f;
3055         char *propName = NULL;
3056         KX_GameObject *other;
3057         int face=0, xray=0, poly=0;
3058
3059         if (!PyArg_ParseTuple(args,"O|Ofsiii:rayCast", &pyto, &pyfrom, &dist, &propName, &face, &xray, &poly)) {
3060                 return NULL; // Python sets a simple error
3061         }
3062
3063         if (!PyVecTo(pyto, toPoint))
3064         {
3065                 PyErr_Clear();
3066                 
3067                 if (ConvertPythonToGameObject(pyto, &other, false, ""))  /* error will be overwritten */
3068                 {
3069                         toPoint = other->NodeGetWorldPosition();
3070                 } else
3071                 {
3072                         PyErr_SetString(PyExc_TypeError, "the first argument to rayCast must be a vector or a KX_GameObject");
3073                         return NULL;
3074                 }
3075         }
3076         if (!pyfrom || pyfrom == Py_None)
3077         {
3078                 fromPoint = NodeGetWorldPosition();
3079         }
3080         else if (!PyVecTo(pyfrom, fromPoint))
3081         {
3082                 PyErr_Clear();
3083                 
3084                 if (ConvertPythonToGameObject(pyfrom, &other, false, "")) /* error will be overwritten */
3085                 {
3086                         fromPoint = other->NodeGetWorldPosition();
3087                 } else
3088                 {
3089                         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");
3090                         return NULL;
3091                 }
3092         }
3093         
3094         if (dist != 0.0f) {
3095                 MT_Vector3 toDir = toPoint-fromPoint;
3096                 if (MT_fuzzyZero(toDir.length2())) {
3097                         //return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
3098                         return none_tuple_3();
3099                 }
3100                 toDir.normalize();
3101                 toPoint = fromPoint + (dist) * toDir;
3102         } else if (MT_fuzzyZero((toPoint-fromPoint).length2())) {
3103                 //return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
3104                 return none_tuple_3();
3105         }
3106         
3107         PHY_IPhysicsEnvironment* pe = KX_GetActiveScene()->GetPhysicsEnvironment();
3108         KX_IPhysicsController *spc = GetPhysicsController();
3109         KX_GameObject *parent = GetParent();
3110         if (!spc && parent)
3111                 spc = parent->GetPhysicsController();
3112         if (parent)
3113                 parent->Release();
3114         
3115         m_pHitObject = NULL;
3116         if (propName)
3117                 m_testPropName = propName;
3118         else
3119                 m_testPropName.SetLength(0);
3120         m_xray = xray;
3121         // to get the hit results
3122         KX_RayCast::Callback<KX_GameObject> callback(this,spc,NULL,face,(poly==2));
3123         KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
3124
3125         if (m_pHitObject)
3126         {
3127                 PyObject* returnValue = (poly==2) ? PyTuple_New(5) : (poly) ? PyTuple_New(4) : PyTuple_New(3);
3128                 if (returnValue) { // unlikely this would ever fail, if it does python sets an error
3129                         PyTuple_SET_ITEM(returnValue, 0, m_pHitObject->GetProxy());
3130                         PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(callback.m_hitPoint));
3131                         PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(callback.m_hitNormal));
3132                         if (poly)
3133                         {
3134                                 if (callback.m_hitMesh)
3135                                 {
3136                                         // if this field is set, then we can trust that m_hitPolygon is a valid polygon
3137                                         RAS_Polygon* polygon = callback.m_hitMesh->GetPolygon(callback.m_hitPolygon);
3138                                         KX_PolyProxy* polyproxy = new KX_PolyProxy(callback.m_hitMesh, polygon);
3139                                         PyTuple_SET_ITEM(returnValue, 3, polyproxy->NewProxy(true));
3140                                         if (poly == 2)
3141                                         {
3142                                                 if (callback.m_hitUVOK)
3143                                                         PyTuple_SET_ITEM(returnValue, 4, PyObjectFrom(callback.m_hitUV));
3144                                                 else {
3145                                                         Py_INCREF(Py_None);
3146                                                         PyTuple_SET_ITEM(returnValue, 4, Py_None);
3147                                                 }
3148                                         }
3149                                 }
3150                                 else
3151                                 {
3152                                         Py_INCREF(Py_None);
3153                                         PyTuple_SET_ITEM(returnValue, 3, Py_None);
3154                                         if (poly==2)
3155                                         {
3156                                                 Py_INCREF(Py_None);
3157                                                 PyTuple_SET_ITEM(returnValue, 4, Py_None);
3158                                         }
3159                                 }
3160                         }
3161                 }
3162                 return returnValue;
3163         }
3164         // no hit
3165         if (poly == 2)
3166                 return none_tuple_5();
3167         else if (poly)
3168                 return none_tuple_4();
3169         else
3170                 return none_tuple_3();
3171 }
3172
3173 KX_PYMETHODDEF_DOC_VARARGS(KX_GameObject, sendMessage, 
3174                                                    "sendMessage(subject, [body, to])\n"
3175 "sends a message in same manner as a message actuator"
3176 "subject = Subject of the message (string)"
3177 "body = Message body (string)"
3178 "to = Name of object to send the message to")
3179 {
3180         KX_Scene *scene = KX_GetActiveScene();
3181         char* subject;
3182         char* body = (char *)"";
3183         char* to = (char *)"";
3184         const STR_String& from = GetName();
3185
3186         if (!PyArg_ParseTuple(args, "s|ss:sendMessage", &subject, &body, &to))
3187                 return NULL;
3188         
3189         scene->GetNetworkScene()->SendMessage(to, from, subject, body);
3190         Py_RETURN_NONE;
3191 }
3192
3193 static void layer_check(short &layer, const char *method_name)
3194 {
3195         if (layer < 0 || layer >= MAX_ACTION_LAYERS)
3196         {
3197                 printf("KX_GameObject.%s(): given layer (%d) is out of range (0 - %d), setting to 0.\n", method_name, layer, MAX_ACTION_LAYERS-1);
3198                 layer = 0;
3199         }
3200 }
3201
3202 KX_PYMETHODDEF_DOC(KX_GameObject, playAction,
3203         "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"
3204         "Plays an action\n")
3205 {
3206         const char* name;
3207         float start, end, blendin=0.f, speed=1.f, layer_weight=0.f;
3208         short layer=0, priority=0;
3209         short ipo_flags=0;
3210         short play_mode=0;
3211
3212         static const char *kwlist[] = {"name", "start_frame", "end_frame", "layer", "priority", "blendin", "play_mode", "layer_weight", "ipo_flags", "speed", NULL};
3213
3214         if (!PyArg_ParseTupleAndKeywords(args, kwds, "sff|hhfhfhf:playAction", const_cast<char**>(kwlist),
3215                                                                         &name, &start, &end, &layer, &priority, &blendin, &play_mode, &layer_weight, &ipo_flags, &speed))
3216                 return NULL;
3217
3218         layer_check(layer, "playAction");
3219
3220         if (play_mode < 0 || play_mode > BL_Action::ACT_MODE_MAX)
3221         {
3222                 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);
3223                 play_mode = BL_Action::ACT_MODE_MAX;
3224         }
3225
3226         if (layer_weight < 0.f || layer_weight > 1.f)
3227         {
3228                 printf("KX_GameObject.playAction(): given layer_weight (%f) is out of range (0.0 - 1.0), setting to 0.0", layer_weight);
3229                 layer_weight = 0.f;
3230         }
3231
3232         PlayAction(name, start, end, layer, priority, blendin, play_mode, layer_weight, ipo_flags, speed);
3233
3234         Py_RETURN_NONE;
3235 }
3236
3237 KX_PYMETHODDEF_DOC(KX_GameObject, stopAction,
3238         "stopAction(layer=0)\n"
3239         "Stop playing the action on the given layer\n")
3240 {
3241         short layer=0;
3242
3243         if (!PyArg_ParseTuple(args, "|h:stopAction", &layer))
3244                 return NULL;
3245
3246         layer_check(layer, "stopAction");
3247
3248         StopAction(layer);
3249
3250         Py_RETURN_NONE;
3251 }
3252
3253 KX_PYMETHODDEF_DOC(KX_GameObject, getActionFrame,
3254         "getActionFrame(layer=0)\n"
3255         "Gets the current frame of the action playing in the supplied layer\n")
3256 {
3257         short layer=0;
3258
3259         if (!PyArg_ParseTuple(args, "|h:getActionFrame", &layer))
3260                 return NULL;
3261
3262         layer_check(layer, "getActionFrame");
3263
3264         return PyFloat_FromDouble(GetActionFrame(layer));
3265 }
3266
3267 KX_PYMETHODDEF_DOC(KX_GameObject, setActionFrame,
3268         "setActionFrame(frame, layer=0)\n"
3269         "Set the current frame of the action playing in the supplied layer\n")
3270 {
3271         short layer=0;
3272         float frame;
3273
3274         if (!PyArg_ParseTuple(args, "f|h:setActionFrame", &frame, &layer))
3275                 return NULL;
3276
3277         layer_check(layer, "setActionFrame");
3278
3279         SetActionFrame(layer, frame);
3280
3281         Py_RETURN_NONE;
3282 }