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