4 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
20 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21 * All rights reserved.
23 * The Original Code is: all of this file.
25 * Contributor(s): none yet.
27 * ***** END GPL LICENSE BLOCK *****
36 typedef unsigned __int64 uint_ptr;
38 typedef unsigned long uint_ptr;
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 )
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"
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()
75 #include "PyObjectPlus.h" /* python stuff */
77 // This file defines relationships between parents and children
78 // in the game engine.
80 #include "KX_SG_NodeRelationships.h"
82 static MT_Point3 dummy_point= MT_Point3(0.0, 0.0, 0.0);
83 static MT_Vector3 dummy_scaling = MT_Vector3(1.0, 1.0, 1.0);
84 static MT_Matrix3x3 dummy_orientation = MT_Matrix3x3( 1.0, 0.0, 0.0,
88 KX_GameObject::KX_GameObject(
89 void* sgReplicationInfo,
90 SG_Callbacks callbacks)
94 m_pBlenderObject(NULL),
95 m_pBlenderGroupObject(NULL),
96 m_bSuspendDynamics(false),
97 m_bUseObjectColor(false),
98 m_bIsNegativeScaling(false),
102 m_pPhysicsController1(NULL),
103 m_pGraphicController(NULL),
106 m_isDeformable(false),
109 m_ignore_activity_culling = false;
110 m_pClient_info = new KX_ClientObjectInfo(this, KX_ClientObjectInfo::ACTOR);
111 m_pSGNode = new SG_Node(this,sgReplicationInfo,callbacks);
113 // define the relationship between this node and it's parent.
115 KX_NormalParentRelation * parent_relation =
116 KX_NormalParentRelation::New();
117 m_pSGNode->SetParentRelation(parent_relation);
122 KX_GameObject::~KX_GameObject()
126 // is this delete somewhere ?
129 delete m_pClient_info;
134 // must go through controllers and make sure they will not use us anymore
135 // This is important for KX_BulletPhysicsControllers that unregister themselves
136 // from the object when they are deleted.
137 SGControllerList::iterator contit;
138 SGControllerList& controllers = m_pSGNode->GetSGControllerList();
139 for (contit = controllers.begin();contit!=controllers.end();++contit)
141 (*contit)->ClearObject();
143 m_pSGNode->SetSGClientObject(NULL);
145 if (m_pGraphicController)
147 delete m_pGraphicController;
151 PyDict_Clear(m_attr_dict); /* incase of circular refs or other weired cases */
152 Py_DECREF(m_attr_dict);
156 KX_GameObject* KX_GameObject::GetClientObject(KX_ClientObjectInfo* info)
160 return info->m_gameobject;
163 CValue* KX_GameObject:: Calc(VALUE_OPERATOR op, CValue *val)
170 CValue* KX_GameObject::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
177 const STR_String & KX_GameObject::GetText()
184 double KX_GameObject::GetNumber()
191 STR_String& KX_GameObject::GetName()
198 void KX_GameObject::SetName(const char *name)
201 }; // Set the name of the value
203 KX_IPhysicsController* KX_GameObject::GetPhysicsController()
205 return m_pPhysicsController1;
208 KX_GameObject* KX_GameObject::GetParent()
210 KX_GameObject* result = NULL;
211 SG_Node* node = m_pSGNode;
213 while (node && !result)
215 node = node->GetSGParent();
217 result = (KX_GameObject*)node->GetSGClientObject();
227 void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj, bool addToCompound, bool ghost)
229 // check on valid node in case a python controller holds a reference to a deleted object
230 if (obj && GetSGNode() && obj->GetSGNode() && GetSGNode()->GetSGParent() != obj->GetSGNode())
232 // Make sure the objects have some scale
233 MT_Vector3 scale1 = NodeGetWorldScaling();
234 MT_Vector3 scale2 = obj->NodeGetWorldScaling();
235 if (fabs(scale2[0]) < FLT_EPSILON ||
236 fabs(scale2[1]) < FLT_EPSILON ||
237 fabs(scale2[2]) < FLT_EPSILON ||
238 fabs(scale1[0]) < FLT_EPSILON ||
239 fabs(scale1[1]) < FLT_EPSILON ||
240 fabs(scale1[2]) < FLT_EPSILON) { return; }
242 // Remove us from our old parent and set our new parent
244 obj->GetSGNode()->AddChild(GetSGNode());
246 if (m_pPhysicsController1)
248 m_pPhysicsController1->SuspendDynamics(ghost);
250 // Set us to our new scale, position, and orientation
251 scale2[0] = 1.0/scale2[0];
252 scale2[1] = 1.0/scale2[1];
253 scale2[2] = 1.0/scale2[2];
254 scale1 = scale1 * scale2;
255 MT_Matrix3x3 invori = obj->NodeGetWorldOrientation().inverse();
256 MT_Vector3 newpos = invori*(NodeGetWorldPosition()-obj->NodeGetWorldPosition())*scale2;
258 NodeSetLocalScale(scale1);
259 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
260 NodeSetLocalOrientation(invori*NodeGetWorldOrientation());
262 // object will now be a child, it must be removed from the parent list
263 CListValue* rootlist = scene->GetRootParentList();
264 if (rootlist->RemoveValue(this))
265 // the object was in parent list, decrement ref count as it's now removed
267 // if the new parent is a compound object, add this object shape to the compound shape.
268 // step 0: verify this object has physical controller
269 if (m_pPhysicsController1 && addToCompound)
271 // step 1: find the top parent (not necessarily obj)
272 KX_GameObject* rootobj = (KX_GameObject*)obj->GetSGNode()->GetRootSGParent()->GetSGClientObject();
273 // step 2: verify it has a physical controller and compound shape
274 if (rootobj != NULL &&
275 rootobj->m_pPhysicsController1 != NULL &&
276 rootobj->m_pPhysicsController1->IsCompound())
278 rootobj->m_pPhysicsController1->AddCompoundChild(m_pPhysicsController1);
281 // graphically, the object hasn't change place, no need to update m_pGraphicController
285 void KX_GameObject::RemoveParent(KX_Scene *scene)
287 // check on valid node in case a python controller holds a reference to a deleted object
288 if (GetSGNode() && GetSGNode()->GetSGParent())
290 // get the root object to remove us from compound object if needed
291 KX_GameObject* rootobj = (KX_GameObject*)GetSGNode()->GetRootSGParent()->GetSGClientObject();
292 // Set us to the right spot
293 GetSGNode()->SetLocalScale(GetSGNode()->GetWorldScaling());
294 GetSGNode()->SetLocalOrientation(GetSGNode()->GetWorldOrientation());
295 GetSGNode()->SetLocalPosition(GetSGNode()->GetWorldPosition());
297 // Remove us from our parent
298 GetSGNode()->DisconnectFromParent();
300 // the object is now a root object, add it to the parentlist
301 CListValue* rootlist = scene->GetRootParentList();
302 if (!rootlist->SearchValue(this))
303 // object was not in root list, add it now and increment ref count
304 rootlist->Add(AddRef());
305 if (m_pPhysicsController1)
307 // in case this controller was added as a child shape to the parent
308 if (rootobj != NULL &&
309 rootobj->m_pPhysicsController1 != NULL &&
310 rootobj->m_pPhysicsController1->IsCompound())
312 rootobj->m_pPhysicsController1->RemoveCompoundChild(m_pPhysicsController1);
314 m_pPhysicsController1->RestoreDynamics();
315 if (m_pPhysicsController1->IsDyna() && rootobj->m_pPhysicsController1)
317 // dynamic object should remember the velocity they had while being parented
318 MT_Point3 childPoint = GetSGNode()->GetWorldPosition();
319 MT_Point3 rootPoint = rootobj->GetSGNode()->GetWorldPosition();
321 relPoint = (childPoint-rootPoint);
322 MT_Vector3 linVel = rootobj->m_pPhysicsController1->GetVelocity(relPoint);
323 MT_Vector3 angVel = rootobj->m_pPhysicsController1->GetAngularVelocity();
324 m_pPhysicsController1->SetLinearVelocity(linVel, false);
325 m_pPhysicsController1->SetAngularVelocity(angVel, false);
328 // graphically, the object hasn't change place, no need to update m_pGraphicController
332 void KX_GameObject::ProcessReplica()
334 SCA_IObject::ProcessReplica();
336 m_pPhysicsController1 = NULL;
337 m_pGraphicController = NULL;
339 m_pClient_info = new KX_ClientObjectInfo(*m_pClient_info);
340 m_pClient_info->m_gameobject = this;
343 m_attr_dict= PyDict_Copy(m_attr_dict);
347 static void setGraphicController_recursive(SG_Node* node)
349 NodeList& children = node->GetSGChildren();
351 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
353 SG_Node* childnode = (*childit);
354 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
355 if (clientgameobj != NULL) // This is a GameObject
356 clientgameobj->ActivateGraphicController(false);
358 // if the childobj is NULL then this may be an inverse parent link
359 // so a non recursive search should still look down this node.
360 setGraphicController_recursive(childnode);
365 void KX_GameObject::ActivateGraphicController(bool recurse)
367 if (m_pGraphicController)
369 m_pGraphicController->Activate(m_bVisible);
373 setGraphicController_recursive(GetSGNode());
378 CValue* KX_GameObject::GetReplica()
380 KX_GameObject* replica = new KX_GameObject(*this);
382 // this will copy properties and so on...
383 replica->ProcessReplica();
390 void KX_GameObject::ApplyForce(const MT_Vector3& force,bool local)
392 if (m_pPhysicsController1)
393 m_pPhysicsController1->ApplyForce(force,local);
398 void KX_GameObject::ApplyTorque(const MT_Vector3& torque,bool local)
400 if (m_pPhysicsController1)
401 m_pPhysicsController1->ApplyTorque(torque,local);
406 void KX_GameObject::ApplyMovement(const MT_Vector3& dloc,bool local)
410 if (m_pPhysicsController1) // (IsDynamic())
412 m_pPhysicsController1->RelativeTranslate(dloc,local);
414 GetSGNode()->RelativeTranslate(dloc,GetSGNode()->GetSGParent(),local);
420 void KX_GameObject::ApplyRotation(const MT_Vector3& drot,bool local)
422 MT_Matrix3x3 rotmat(drot);
425 GetSGNode()->RelativeRotate(rotmat,local);
427 if (m_pPhysicsController1) { // (IsDynamic())
428 m_pPhysicsController1->RelativeRotate(rotmat,local);
436 GetOpenGL Matrix, returns an OpenGL 'compatible' matrix
438 double* KX_GameObject::GetOpenGLMatrix()
440 // todo: optimize and only update if necessary
441 double* fl = m_OpenGL_4x4Matrix.getPointer();
445 trans.setOrigin(GetSGNode()->GetWorldPosition());
446 trans.setBasis(GetSGNode()->GetWorldOrientation());
448 MT_Vector3 scaling = GetSGNode()->GetWorldScaling();
449 m_bIsNegativeScaling = ((scaling[0] < 0.0) ^ (scaling[1] < 0.0) ^ (scaling[2] < 0.0)) ? true : false;
450 trans.scale(scaling[0], scaling[1], scaling[2]);
452 GetSGNode()->ClearDirty();
457 void KX_GameObject::AddMeshUser()
459 for (size_t i=0;i<m_meshes.size();i++)
461 m_meshes[i]->AddMeshUser(this, &m_meshSlots, GetDeformer());
463 // set the part of the mesh slot that never change
464 double* fl = GetOpenGLMatrixPtr()->getPointer();
466 SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
468 for(mit.begin(); !mit.end(); ++mit)
470 (*mit)->m_OpenGLMatrix = fl;
472 UpdateBuckets(false);
475 static void UpdateBuckets_recursive(SG_Node* node)
477 NodeList& children = node->GetSGChildren();
479 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
481 SG_Node* childnode = (*childit);
482 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
483 if (clientgameobj != NULL) // This is a GameObject
484 clientgameobj->UpdateBuckets(0);
486 // if the childobj is NULL then this may be an inverse parent link
487 // so a non recursive search should still look down this node.
488 UpdateBuckets_recursive(childnode);
492 void KX_GameObject::UpdateBuckets( bool recursive )
497 if (GetSGNode()->IsDirty())
500 SG_QList::iterator<RAS_MeshSlot> mit(m_meshSlots);
501 for(mit.begin(); !mit.end(); ++mit)
504 ms->m_bObjectColor = m_bUseObjectColor;
505 ms->m_RGBAcolor = m_objectColor;
506 ms->m_bVisible = m_bVisible;
507 ms->m_bCulled = m_bCulled || !m_bVisible;
509 ms->m_bucket->ActivateMesh(ms);
511 /* split if necessary */
518 UpdateBuckets_recursive(GetSGNode());
523 void KX_GameObject::RemoveMeshes()
525 for (size_t i=0;i<m_meshes.size();i++)
526 m_meshes[i]->RemoveFromBuckets(this);
528 //note: meshes can be shared, and are deleted by KX_BlenderSceneConverter
533 void KX_GameObject::UpdateTransform()
535 // HACK: saves function call for dynamic object, they are handled differently
536 if (m_pPhysicsController1 && !m_pPhysicsController1->IsDyna())
537 // Note that for Bullet, this does not even update the transform of static object
538 // but merely sets there collision flag to "kinematic" because the synchronization is
539 // done during physics simulation
540 m_pPhysicsController1->SetSumoTransform(true);
541 if (m_pGraphicController)
542 // update the culling tree
543 m_pGraphicController->SetGraphicTransform();
547 void KX_GameObject::UpdateTransformFunc(SG_IObject* node, void* gameobj, void* scene)
549 ((KX_GameObject*)gameobj)->UpdateTransform();
552 void KX_GameObject::SynchronizeTransform()
554 // only used for sensor object, do full synchronization as bullet doesn't do it
555 if (m_pPhysicsController1)
556 m_pPhysicsController1->SetTransform();
557 if (m_pGraphicController)
558 m_pGraphicController->SetGraphicTransform();
561 void KX_GameObject::SynchronizeTransformFunc(SG_IObject* node, void* gameobj, void* scene)
563 ((KX_GameObject*)gameobj)->SynchronizeTransform();
567 void KX_GameObject::SetDebugColor(unsigned int bgra)
569 for (size_t i=0;i<m_meshes.size();i++)
570 m_meshes[i]->DebugColor(bgra);
575 void KX_GameObject::ResetDebugColor()
577 SetDebugColor(0xff000000);
580 void KX_GameObject::InitIPO(bool ipo_as_force,
584 SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin();
586 while (it != GetSGNode()->GetSGControllerList().end()) {
587 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true);
588 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, ipo_as_force);
589 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, ipo_add);
590 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, ipo_local);
595 void KX_GameObject::UpdateIPO(float curframetime,
598 // just the 'normal' update procedure.
599 GetSGNode()->SetSimulatedTime(curframetime,recurse);
600 GetSGNode()->UpdateWorldData(curframetime);
606 KX_GameObject::UpdateMaterialData(
619 if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) {
620 list<RAS_MeshMaterial>::iterator mit = m_meshes[mesh]->GetFirstMaterial();
622 for(; mit != m_meshes[mesh]->GetLastMaterial(); ++mit)
624 RAS_IPolyMaterial* poly = mit->m_bucket->GetPolyMaterial();
626 if(poly->GetFlag() & RAS_BLENDERMAT )
628 KX_BlenderMaterial *m = static_cast<KX_BlenderMaterial*>(poly);
630 if (matname_hash == 0)
632 m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
633 // if mesh has only one material attached to it then use original hack with no need to edit vertices (better performance)
634 SetObjectColor(rgba);
638 if (matname_hash == poly->GetMaterialNameHash())
640 m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
641 m_meshes[mesh]->SetVertexColor(poly,rgba);
643 // no break here, because one blender material can be split into several game engine materials
644 // (e.g. one uvsphere material is split into one material at poles with ras_mode TRIANGLE and one material for the body
645 // if here was a break then would miss some vertices if material was split
653 KX_GameObject::GetVisible(
660 static void setVisible_recursive(SG_Node* node, bool v)
662 NodeList& children = node->GetSGChildren();
664 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
666 SG_Node* childnode = (*childit);
667 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
668 if (clientgameobj != NULL) // This is a GameObject
669 clientgameobj->SetVisible(v, 0);
671 // if the childobj is NULL then this may be an inverse parent link
672 // so a non recursive search should still look down this node.
673 setVisible_recursive(childnode, v);
679 KX_GameObject::SetVisible(
686 if (m_pGraphicController)
687 m_pGraphicController->Activate(m_bVisible);
689 setVisible_recursive(GetSGNode(), v);
693 static void setOccluder_recursive(SG_Node* node, bool v)
695 NodeList& children = node->GetSGChildren();
697 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
699 SG_Node* childnode = (*childit);
700 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
701 if (clientgameobj != NULL) // This is a GameObject
702 clientgameobj->SetOccluder(v, false);
704 // if the childobj is NULL then this may be an inverse parent link
705 // so a non recursive search should still look down this node.
706 setOccluder_recursive(childnode, v);
711 KX_GameObject::SetOccluder(
719 setOccluder_recursive(GetSGNode(), v);
724 KX_GameObject::SetLayer(
732 KX_GameObject::GetLayer(
739 void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local)
741 if (m_pPhysicsController1)
743 MT_Vector3 lv = local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
744 m_pPhysicsController1->SetLinearVelocity(lv + m_pPhysicsController1->GetLinearVelocity(), 0);
750 void KX_GameObject::setLinearVelocity(const MT_Vector3& lin_vel,bool local)
752 if (m_pPhysicsController1)
753 m_pPhysicsController1->SetLinearVelocity(lin_vel,local);
758 void KX_GameObject::setAngularVelocity(const MT_Vector3& ang_vel,bool local)
760 if (m_pPhysicsController1)
761 m_pPhysicsController1->SetAngularVelocity(ang_vel,local);
765 void KX_GameObject::ResolveCombinedVelocities(
766 const MT_Vector3 & lin_vel,
767 const MT_Vector3 & ang_vel,
771 if (m_pPhysicsController1)
774 MT_Vector3 lv = lin_vel_local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
775 MT_Vector3 av = ang_vel_local ? NodeGetWorldOrientation() * ang_vel : ang_vel;
776 m_pPhysicsController1->resolveCombinedVelocities(
777 lv.x(),lv.y(),lv.z(),av.x(),av.y(),av.z());
782 void KX_GameObject::SetObjectColor(const MT_Vector4& rgbavec)
784 m_bUseObjectColor = true;
785 m_objectColor = rgbavec;
788 void KX_GameObject::AlignAxisToVect(const MT_Vector3& dir, int axis, float fac)
791 MT_Vector3 vect,ori,z,x,y;
794 // check on valid node in case a python controller holds a reference to a deleted object
800 if (MT_fuzzyZero(len))
802 cout << "alignAxisToVect() Error: Null vector!\n";
812 orimat = GetSGNode()->GetWorldOrientation();
816 ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]); //pivot axis
817 if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON) //is the vector paralell to the pivot?
818 ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]); //change the pivot!
822 x = (vect * fac) + ((orimat * MT_Vector3(1.0, 0.0, 0.0)) * (1-fac));
824 if (MT_fuzzyZero(len)) x = vect;
831 ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
832 if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
833 ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]);
837 y = (vect * fac) + ((orimat * MT_Vector3(0.0, 1.0, 0.0)) * (1-fac));
839 if (MT_fuzzyZero(len)) y = vect;
846 ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]);
847 if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
848 ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
852 z = (vect * fac) + ((orimat * MT_Vector3(0.0, 0.0, 1.0)) * (1-fac));
854 if (MT_fuzzyZero(len)) z = vect;
860 default: //wrong input?
861 cout << "alignAxisToVect(): Wrong axis '" << axis <<"'\n";
864 x.normalize(); //normalize the vectors
867 orimat.setValue( x[0],y[0],z[0],
870 if (GetSGNode()->GetSGParent() != NULL)
872 // the object is a child, adapt its local orientation so that
873 // the global orientation is aligned as we want.
874 MT_Matrix3x3 invori = GetSGNode()->GetSGParent()->GetWorldOrientation().inverse();
875 NodeSetLocalOrientation(invori*orimat);
878 NodeSetLocalOrientation(orimat);
881 MT_Scalar KX_GameObject::GetMass()
883 if (m_pPhysicsController1)
885 return m_pPhysicsController1->GetMass();
890 MT_Vector3 KX_GameObject::GetLocalInertia()
892 MT_Vector3 local_inertia(0.0,0.0,0.0);
893 if (m_pPhysicsController1)
895 local_inertia = m_pPhysicsController1->GetLocalInertia();
897 return local_inertia;
900 MT_Vector3 KX_GameObject::GetLinearVelocity(bool local)
902 MT_Vector3 velocity(0.0,0.0,0.0), locvel;
904 if (m_pPhysicsController1)
906 velocity = m_pPhysicsController1->GetLinearVelocity();
910 ori = GetSGNode()->GetWorldOrientation();
912 locvel = velocity * ori;
919 MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
921 MT_Vector3 velocity(0.0,0.0,0.0), locvel;
923 if (m_pPhysicsController1)
925 velocity = m_pPhysicsController1->GetAngularVelocity();
929 ori = GetSGNode()->GetWorldOrientation();
931 locvel = velocity * ori;
938 MT_Vector3 KX_GameObject::GetVelocity(const MT_Point3& point)
940 if (m_pPhysicsController1)
942 return m_pPhysicsController1->GetVelocity(point);
944 return MT_Vector3(0.0,0.0,0.0);
947 // scenegraph node stuff
949 void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans)
951 // check on valid node in case a python controller holds a reference to a deleted object
955 if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
957 // don't update physic controller if the object is a child:
958 // 1) the transformation will not be right
959 // 2) in this case, the physic controller is necessarily a static object
960 // that is updated from the normal kinematic synchronization
961 m_pPhysicsController1->setPosition(trans);
964 GetSGNode()->SetLocalPosition(trans);
970 void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3& rot)
972 // check on valid node in case a python controller holds a reference to a deleted object
976 if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
979 m_pPhysicsController1->setOrientation(rot);
981 GetSGNode()->SetLocalOrientation(rot);
984 void KX_GameObject::NodeSetGlobalOrientation(const MT_Matrix3x3& rot)
986 // check on valid node in case a python controller holds a reference to a deleted object
990 if (GetSGNode()->GetSGParent())
991 GetSGNode()->SetLocalOrientation(GetSGNode()->GetSGParent()->GetWorldOrientation().inverse()*rot);
993 GetSGNode()->SetLocalOrientation(rot);
996 void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale)
998 // check on valid node in case a python controller holds a reference to a deleted object
1002 if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
1005 m_pPhysicsController1->setScaling(scale);
1007 GetSGNode()->SetLocalScale(scale);
1012 void KX_GameObject::NodeSetRelativeScale(const MT_Vector3& scale)
1016 GetSGNode()->RelativeScale(scale);
1017 if (m_pPhysicsController1 && (!GetSGNode()->GetSGParent()))
1020 // we can use the local scale: it's the same thing for a root object
1021 // and the world scale is not yet updated
1022 MT_Vector3 newscale = GetSGNode()->GetLocalScale();
1023 m_pPhysicsController1->setScaling(newscale);
1028 void KX_GameObject::NodeSetWorldPosition(const MT_Point3& trans)
1032 SG_Node* parent = GetSGNode()->GetSGParent();
1035 // Make sure the objects have some scale
1036 MT_Vector3 scale = parent->GetWorldScaling();
1037 if (fabs(scale[0]) < FLT_EPSILON ||
1038 fabs(scale[1]) < FLT_EPSILON ||
1039 fabs(scale[2]) < FLT_EPSILON)
1043 scale[0] = 1.0/scale[0];
1044 scale[1] = 1.0/scale[1];
1045 scale[2] = 1.0/scale[2];
1046 MT_Matrix3x3 invori = parent->GetWorldOrientation().inverse();
1047 MT_Vector3 newpos = invori*(trans-parent->GetWorldPosition())*scale;
1048 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
1052 NodeSetLocalPosition(trans);
1057 void KX_GameObject::NodeUpdateGS(double time)
1060 GetSGNode()->UpdateWorldData(time);
1065 const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
1067 // check on valid node in case a python controller holds a reference to a deleted object
1069 return dummy_orientation;
1070 return GetSGNode()->GetWorldOrientation();
1073 const MT_Matrix3x3& KX_GameObject::NodeGetLocalOrientation() const
1075 // check on valid node in case a python controller holds a reference to a deleted object
1077 return dummy_orientation;
1078 return GetSGNode()->GetLocalOrientation();
1081 const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const
1083 // check on valid node in case a python controller holds a reference to a deleted object
1085 return dummy_scaling;
1087 return GetSGNode()->GetWorldScaling();
1090 const MT_Vector3& KX_GameObject::NodeGetLocalScaling() const
1092 // check on valid node in case a python controller holds a reference to a deleted object
1094 return dummy_scaling;
1096 return GetSGNode()->GetLocalScale();
1099 const MT_Point3& KX_GameObject::NodeGetWorldPosition() const
1101 // check on valid node in case a python controller holds a reference to a deleted object
1103 return GetSGNode()->GetWorldPosition();
1108 const MT_Point3& KX_GameObject::NodeGetLocalPosition() const
1110 // check on valid node in case a python controller holds a reference to a deleted object
1112 return GetSGNode()->GetLocalPosition();
1118 /* Suspend/ resume: for the dynamic behaviour, there is a simple
1119 * method. For the residual motion, there is not. I wonder what the
1120 * correct solution is for Sumo. Remove from the motion-update tree?
1122 * So far, only switch the physics and logic.
1125 void KX_GameObject::Resume(void)
1128 SCA_IObject::Resume();
1129 if(GetPhysicsController())
1130 GetPhysicsController()->RestoreDynamics();
1132 m_suspended = false;
1136 void KX_GameObject::Suspend()
1138 if ((!m_ignore_activity_culling)
1139 && (!m_suspended)) {
1140 SCA_IObject::Suspend();
1141 if(GetPhysicsController())
1142 GetPhysicsController()->SuspendDynamics();
1147 static void walk_children(SG_Node* node, CListValue* list, bool recursive)
1151 NodeList& children = node->GetSGChildren();
1153 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
1155 SG_Node* childnode = (*childit);
1156 CValue* childobj = (CValue*)childnode->GetSGClientObject();
1157 if (childobj != NULL) // This is a GameObject
1160 list->Add(childobj->AddRef());
1163 // if the childobj is NULL then this may be an inverse parent link
1164 // so a non recursive search should still look down this node.
1165 if (recursive || childobj==NULL) {
1166 walk_children(childnode, list, recursive);
1171 CListValue* KX_GameObject::GetChildren()
1173 CListValue* list = new CListValue();
1174 walk_children(GetSGNode(), list, 0); /* GetSGNode() is always valid or it would have raised an exception before this */
1178 CListValue* KX_GameObject::GetChildrenRecursive()
1180 CListValue* list = new CListValue();
1181 walk_children(GetSGNode(), list, 1);
1185 #ifdef USE_MATHUTILS
1187 /* These require an SGNode */
1188 #define MATHUTILS_VEC_CB_POS_LOCAL 1
1189 #define MATHUTILS_VEC_CB_POS_GLOBAL 2
1190 #define MATHUTILS_VEC_CB_SCALE_LOCAL 3
1191 #define MATHUTILS_VEC_CB_SCALE_GLOBAL 4
1192 #define MATHUTILS_VEC_CB_INERTIA_LOCAL 5
1194 static int mathutils_kxgameob_vector_cb_index= -1; /* index for our callbacks */
1196 static int mathutils_kxgameob_generic_check(PyObject *self_v)
1198 KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1205 static int mathutils_kxgameob_vector_get(PyObject *self_v, int subtype, float *vec_from)
1207 KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1212 case MATHUTILS_VEC_CB_POS_LOCAL:
1213 self->NodeGetLocalPosition().getValue(vec_from);
1215 case MATHUTILS_VEC_CB_POS_GLOBAL:
1216 self->NodeGetWorldPosition().getValue(vec_from);
1218 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1219 self->NodeGetLocalScaling().getValue(vec_from);
1221 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1222 self->NodeGetWorldScaling().getValue(vec_from);
1224 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1225 if(!self->GetPhysicsController()) return 0;
1226 self->GetPhysicsController()->GetLocalInertia().getValue(vec_from);
1233 static int mathutils_kxgameob_vector_set(PyObject *self_v, int subtype, float *vec_to)
1235 KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1240 case MATHUTILS_VEC_CB_POS_LOCAL:
1241 self->NodeSetLocalPosition(MT_Point3(vec_to));
1242 self->NodeUpdateGS(0.f);
1244 case MATHUTILS_VEC_CB_POS_GLOBAL:
1245 self->NodeSetWorldPosition(MT_Point3(vec_to));
1246 self->NodeUpdateGS(0.f);
1248 case MATHUTILS_VEC_CB_SCALE_LOCAL:
1249 self->NodeSetLocalScale(MT_Point3(vec_to));
1250 self->NodeUpdateGS(0.f);
1252 case MATHUTILS_VEC_CB_SCALE_GLOBAL:
1254 case MATHUTILS_VEC_CB_INERTIA_LOCAL:
1262 static int mathutils_kxgameob_vector_get_index(PyObject *self_v, int subtype, float *vec_from, int index)
1265 /* lazy, avoid repeteing the case statement */
1266 if(!mathutils_kxgameob_vector_get(self_v, subtype, f))
1269 vec_from[index]= f[index];
1273 static int mathutils_kxgameob_vector_set_index(PyObject *self_v, int subtype, float *vec_to, int index)
1275 float f= vec_to[index];
1277 /* lazy, avoid repeteing the case statement */
1278 if(!mathutils_kxgameob_vector_get(self_v, subtype, vec_to))
1282 mathutils_kxgameob_vector_set(self_v, subtype, vec_to);
1287 Mathutils_Callback mathutils_kxgameob_vector_cb = {
1288 mathutils_kxgameob_generic_check,
1289 mathutils_kxgameob_vector_get,
1290 mathutils_kxgameob_vector_set,
1291 mathutils_kxgameob_vector_get_index,
1292 mathutils_kxgameob_vector_set_index
1296 #define MATHUTILS_MAT_CB_ORI_LOCAL 1
1297 #define MATHUTILS_MAT_CB_ORI_GLOBAL 2
1299 static int mathutils_kxgameob_matrix_cb_index= -1; /* index for our callbacks */
1301 static int mathutils_kxgameob_matrix_get(PyObject *self_v, int subtype, float *mat_from)
1303 KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1308 case MATHUTILS_MAT_CB_ORI_LOCAL:
1309 self->NodeGetLocalOrientation().getValue3x3(mat_from);
1311 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1312 self->NodeGetWorldOrientation().getValue3x3(mat_from);
1320 static int mathutils_kxgameob_matrix_set(PyObject *self_v, int subtype, float *mat_to)
1322 KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1326 MT_Matrix3x3 mat3x3;
1328 case MATHUTILS_MAT_CB_ORI_LOCAL:
1329 mat3x3.setValue3x3(mat_to);
1330 self->NodeSetLocalOrientation(mat3x3);
1331 self->NodeUpdateGS(0.f);
1333 case MATHUTILS_MAT_CB_ORI_GLOBAL:
1334 mat3x3.setValue3x3(mat_to);
1335 self->NodeSetLocalOrientation(mat3x3);
1336 self->NodeUpdateGS(0.f);
1343 Mathutils_Callback mathutils_kxgameob_matrix_cb = {
1344 mathutils_kxgameob_generic_check,
1345 mathutils_kxgameob_matrix_get,
1346 mathutils_kxgameob_matrix_set,
1352 void KX_GameObject_Mathutils_Callback_Init(void)
1354 // register mathutils callbacks, ok to run more then once.
1355 mathutils_kxgameob_vector_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_vector_cb);
1356 mathutils_kxgameob_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_kxgameob_matrix_cb);
1359 #endif // USE_MATHUTILS
1361 /* ------- python stuff ---------------------------------------------------*/
1363 PyMethodDef KX_GameObject::Methods[] = {
1364 {"applyForce", (PyCFunction) KX_GameObject::sPyApplyForce, METH_VARARGS},
1365 {"applyTorque", (PyCFunction) KX_GameObject::sPyApplyTorque, METH_VARARGS},
1366 {"applyRotation", (PyCFunction) KX_GameObject::sPyApplyRotation, METH_VARARGS},
1367 {"applyMovement", (PyCFunction) KX_GameObject::sPyApplyMovement, METH_VARARGS},
1368 {"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS},
1369 {"setLinearVelocity", (PyCFunction) KX_GameObject::sPySetLinearVelocity, METH_VARARGS},
1370 {"getAngularVelocity", (PyCFunction) KX_GameObject::sPyGetAngularVelocity, METH_VARARGS},
1371 {"setAngularVelocity", (PyCFunction) KX_GameObject::sPySetAngularVelocity, METH_VARARGS},
1372 {"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS},
1373 {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS},
1374 {"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS},
1375 {"getAxisVect",(PyCFunction) KX_GameObject::sPyGetAxisVect, METH_O},
1376 {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics,METH_NOARGS},
1377 {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_NOARGS},
1378 {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_NOARGS},
1379 {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_NOARGS},
1380 {"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS},
1381 {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_O},
1382 {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_VARARGS},
1383 {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},
1384 {"setOcclusion",(PyCFunction) KX_GameObject::sPySetOcclusion, METH_VARARGS},
1385 {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_NOARGS},
1386 {"getChildren", (PyCFunction)KX_GameObject::sPyGetChildren,METH_NOARGS},
1387 {"getChildrenRecursive", (PyCFunction)KX_GameObject::sPyGetChildrenRecursive,METH_NOARGS},
1388 {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS},
1389 {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS},
1390 {"replaceMesh",(PyCFunction) KX_GameObject::sPyReplaceMesh, METH_VARARGS},
1391 {"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS},
1392 {"reinstancePhysicsMesh", (PyCFunction)KX_GameObject::sPyReinstancePhysicsMesh,METH_VARARGS},
1394 KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
1395 KX_PYMETHODTABLE(KX_GameObject, rayCast),
1396 KX_PYMETHODTABLE_O(KX_GameObject, getDistanceTo),
1397 KX_PYMETHODTABLE_O(KX_GameObject, getVectTo),
1398 KX_PYMETHODTABLE(KX_GameObject, sendMessage),
1400 // dict style access for props
1401 {"has_key",(PyCFunction) KX_GameObject::sPyhas_key, METH_O},
1402 {"get",(PyCFunction) KX_GameObject::sPyget, METH_VARARGS},
1405 {"getPosition", (PyCFunction) KX_GameObject::sPyGetPosition, METH_NOARGS},
1406 {"setPosition", (PyCFunction) KX_GameObject::sPySetPosition, METH_O},
1407 {"setWorldPosition", (PyCFunction) KX_GameObject::sPySetWorldPosition, METH_O},
1408 {"getOrientation", (PyCFunction) KX_GameObject::sPyGetOrientation, METH_NOARGS},
1409 {"setOrientation", (PyCFunction) KX_GameObject::sPySetOrientation, METH_O},
1410 {"getState",(PyCFunction) KX_GameObject::sPyGetState, METH_NOARGS},
1411 {"setState",(PyCFunction) KX_GameObject::sPySetState, METH_O},
1412 {"getParent", (PyCFunction)KX_GameObject::sPyGetParent,METH_NOARGS},
1413 {"getVisible",(PyCFunction) KX_GameObject::sPyGetVisible, METH_NOARGS},
1414 {"getMass", (PyCFunction) KX_GameObject::sPyGetMass, METH_NOARGS},
1415 {"getMesh", (PyCFunction)KX_GameObject::sPyGetMesh,METH_VARARGS},
1416 {NULL,NULL} //Sentinel
1419 PyAttributeDef KX_GameObject::Attributes[] = {
1420 KX_PYATTRIBUTE_RO_FUNCTION("name", KX_GameObject, pyattr_get_name),
1421 KX_PYATTRIBUTE_RO_FUNCTION("parent", KX_GameObject, pyattr_get_parent),
1422 KX_PYATTRIBUTE_RW_FUNCTION("mass", KX_GameObject, pyattr_get_mass, pyattr_set_mass),
1423 KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMin", KX_GameObject, pyattr_get_lin_vel_min, pyattr_set_lin_vel_min),
1424 KX_PYATTRIBUTE_RW_FUNCTION("linVelocityMax", KX_GameObject, pyattr_get_lin_vel_max, pyattr_set_lin_vel_max),
1425 KX_PYATTRIBUTE_RW_FUNCTION("visible", KX_GameObject, pyattr_get_visible, pyattr_set_visible),
1426 KX_PYATTRIBUTE_BOOL_RW ("occlusion", KX_GameObject, m_bOccluder),
1427 KX_PYATTRIBUTE_RW_FUNCTION("position", KX_GameObject, pyattr_get_worldPosition, pyattr_set_localPosition),
1428 KX_PYATTRIBUTE_RO_FUNCTION("localInertia", KX_GameObject, pyattr_get_localInertia),
1429 KX_PYATTRIBUTE_RW_FUNCTION("orientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_localOrientation),
1430 KX_PYATTRIBUTE_RW_FUNCTION("scaling", KX_GameObject, pyattr_get_worldScaling, pyattr_set_localScaling),
1431 KX_PYATTRIBUTE_RW_FUNCTION("timeOffset",KX_GameObject, pyattr_get_timeOffset,pyattr_set_timeOffset),
1432 KX_PYATTRIBUTE_RW_FUNCTION("state", KX_GameObject, pyattr_get_state, pyattr_set_state),
1433 KX_PYATTRIBUTE_RO_FUNCTION("meshes", KX_GameObject, pyattr_get_meshes),
1434 KX_PYATTRIBUTE_RW_FUNCTION("localOrientation",KX_GameObject,pyattr_get_localOrientation,pyattr_set_localOrientation),
1435 KX_PYATTRIBUTE_RW_FUNCTION("worldOrientation",KX_GameObject,pyattr_get_worldOrientation,pyattr_set_worldOrientation),
1436 KX_PYATTRIBUTE_RW_FUNCTION("localPosition", KX_GameObject, pyattr_get_localPosition, pyattr_set_localPosition),
1437 KX_PYATTRIBUTE_RW_FUNCTION("worldPosition", KX_GameObject, pyattr_get_worldPosition, pyattr_set_worldPosition),
1438 KX_PYATTRIBUTE_RW_FUNCTION("localScale", KX_GameObject, pyattr_get_localScaling, pyattr_set_localScaling),
1439 KX_PYATTRIBUTE_RO_FUNCTION("worldScale", KX_GameObject, pyattr_get_worldScaling),
1440 KX_PYATTRIBUTE_RO_FUNCTION("children", KX_GameObject, pyattr_get_children),
1441 KX_PYATTRIBUTE_RO_FUNCTION("childrenRecursive", KX_GameObject, pyattr_get_children_recursive),
1442 KX_PYATTRIBUTE_RO_FUNCTION("attrDict", KX_GameObject, pyattr_get_attrDict),
1444 /* Experemental, dont rely on these yet */
1445 KX_PYATTRIBUTE_RO_FUNCTION("sensors", KX_GameObject, pyattr_get_sensors),
1446 KX_PYATTRIBUTE_RO_FUNCTION("controllers", KX_GameObject, pyattr_get_controllers),
1447 KX_PYATTRIBUTE_RO_FUNCTION("actuators", KX_GameObject, pyattr_get_actuators),
1453 bool KX_GameObject::ConvertPythonVectorArgs(PyObject* args,
1459 bool error = (PyArg_ParseTuple(args,"OO",&pylist,&pylist2)) != 0;
1461 pos = ConvertPythonPylist(pylist);
1462 pos2 = ConvertPythonPylist(pylist2);
1468 PyObject* KX_GameObject::PyReplaceMesh(PyObject* args)
1470 KX_Scene *scene = KX_GetActiveScene();
1473 int use_gfx= 1, use_phys= 0;
1474 RAS_MeshObject *new_mesh;
1476 if (!PyArg_ParseTuple(args,"O|ii:replaceMesh", &value, &use_gfx, &use_phys))
1479 if (!ConvertPythonToMesh(value, &new_mesh, false, "gameOb.replaceMesh(value): KX_GameObject"))
1482 scene->ReplaceMesh(this, new_mesh, (bool)use_gfx, (bool)use_phys);
1486 PyObject* KX_GameObject::PyEndObject()
1488 KX_Scene *scene = KX_GetActiveScene();
1490 scene->DelayedRemoveObject(this);
1496 PyObject* KX_GameObject::PyReinstancePhysicsMesh(PyObject* args)
1498 KX_GameObject *gameobj= NULL;
1499 RAS_MeshObject *mesh= NULL;
1501 PyObject *gameobj_py= NULL;
1502 PyObject *mesh_py= NULL;
1504 if ( !PyArg_ParseTuple(args,"|OO:reinstancePhysicsMesh",&gameobj_py, &mesh_py) ||
1505 (gameobj_py && !ConvertPythonToGameObject(gameobj_py, &gameobj, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject")) ||
1506 (mesh_py && !ConvertPythonToMesh(mesh_py, &mesh, true, "gameOb.reinstancePhysicsMesh(obj, mesh): KX_GameObject"))
1511 /* gameobj and mesh can be NULL */
1512 if(KX_ReInstanceBulletShapeFromMesh(this, gameobj, mesh))
1519 PyObject* KX_GameObject::PyGetPosition()
1521 ShowDeprecationWarning("getPosition()", "the position property");
1522 return PyObjectFrom(NodeGetWorldPosition());
1525 static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
1527 KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1528 const char *attr_str= _PyUnicode_AsString(item);
1530 PyObject* pyconvert;
1533 PyErr_SetString(PyExc_SystemError, "val = gameOb[key]: KX_GameObject, "BGE_PROXY_ERROR_MSG);
1537 /* first see if the attributes a string and try get the cvalue attribute */
1538 if(attr_str && (resultattr=self->GetProperty(attr_str))) {
1539 pyconvert = resultattr->ConvertValueToPython();
1540 return pyconvert ? pyconvert:resultattr->GetProxy();
1542 /* no CValue attribute, try get the python only m_attr_dict attribute */
1543 else if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
1547 Py_INCREF(pyconvert);
1551 if(attr_str) PyErr_Format(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key \"%s\" does not exist", attr_str);
1552 else PyErr_SetString(PyExc_KeyError, "value = gameOb[key]: KX_GameObject, key does not exist");
1559 static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
1561 KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1562 const char *attr_str= _PyUnicode_AsString(key);
1567 PyErr_SetString(PyExc_SystemError, "gameOb[key] = value: KX_GameObject, "BGE_PROXY_ERROR_MSG);
1571 if (val==NULL) { /* del ob["key"] */
1574 /* try remove both just incase */
1576 del |= (self->RemoveProperty(attr_str)==true) ? 1:0;
1578 if(self->m_attr_dict)
1579 del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
1582 if(attr_str) PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" could not be set", attr_str);
1583 else PyErr_SetString(PyExc_KeyError, "del gameOb[key]: KX_GameObject, key could not be deleted");
1586 else if (self->m_attr_dict) {
1587 PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
1590 else { /* ob["key"] = value */
1594 if(attr_str && PyObject_TypeCheck(val, &PyObjectPlus::Type)==0) /* dont allow GameObjects for eg to be assigned to CValue props */
1596 CValue* vallie = self->ConvertPythonToValue(val, ""); /* error unused */
1600 CValue* oldprop = self->GetProperty(attr_str);
1603 oldprop->SetValue(vallie);
1605 self->SetProperty(attr_str, vallie);
1610 /* try remove dict value to avoid double ups */
1611 if (self->m_attr_dict){
1612 if (PyDict_DelItem(self->m_attr_dict, key) != 0)
1623 if (self->m_attr_dict==NULL) /* lazy init */
1624 self->m_attr_dict= PyDict_New();
1627 if(PyDict_SetItem(self->m_attr_dict, key, val)==0)
1630 self->RemoveProperty(attr_str); /* overwrite the CValue if it exists */
1634 if(attr_str) PyErr_Format(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key \"%s\" not be added to internal dictionary", attr_str);
1635 else PyErr_SetString(PyExc_KeyError, "gameOb[key] = value: KX_GameObject, key not be added to internal dictionary");
1640 return -1; /* pythons error value */
1644 return 0; /* success */
1647 static int Seq_Contains(PyObject *self_v, PyObject *value)
1649 KX_GameObject* self= static_cast<KX_GameObject*>BGE_PROXY_REF(self_v);
1652 PyErr_SetString(PyExc_SystemError, "val in gameOb: KX_GameObject, "BGE_PROXY_ERROR_MSG);
1656 if(PyUnicode_Check(value) && self->GetProperty(_PyUnicode_AsString(value)))
1659 if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
1666 PyMappingMethods KX_GameObject::Mapping = {
1667 (lenfunc)NULL , /*inquiry mp_length */
1668 (binaryfunc)Map_GetItem, /*binaryfunc mp_subscript */
1669 (objobjargproc)Map_SetItem, /*objobjargproc mp_ass_subscript */
1672 PySequenceMethods KX_GameObject::Sequence = {
1673 NULL, /* Cant set the len otherwise it can evaluate as false */
1674 NULL, /* sq_concat */
1675 NULL, /* sq_repeat */
1677 NULL, /* sq_slice */
1678 NULL, /* sq_ass_item */
1679 NULL, /* sq_ass_slice */
1680 (objobjproc)Seq_Contains, /* sq_contains */
1683 PyTypeObject KX_GameObject::Type = {
1684 PyVarObject_HEAD_INIT(NULL, 0)
1686 sizeof(PyObjectPlus_Proxy),
1701 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
1711 PyObject* KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1713 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1714 return PyUnicode_FromString(self->GetName().ReadPtr());
1717 PyObject* KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1719 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1720 KX_GameObject* parent = self->GetParent();
1722 parent->Release(); /* self->GetParent() AddRef's */
1723 return parent->GetProxy();
1728 PyObject* KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1730 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1731 KX_IPhysicsController *spc = self->GetPhysicsController();
1732 return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0f);
1735 int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1737 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1738 KX_IPhysicsController *spc = self->GetPhysicsController();
1739 MT_Scalar val = PyFloat_AsDouble(value);
1740 if (val < 0.0f) { /* also accounts for non float */
1741 PyErr_SetString(PyExc_AttributeError, "gameOb.mass = float: KX_GameObject, expected a float zero or above");
1742 return PY_SET_ATTR_FAIL;
1748 return PY_SET_ATTR_SUCCESS;
1751 PyObject* KX_GameObject::pyattr_get_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1753 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1754 KX_IPhysicsController *spc = self->GetPhysicsController();
1755 return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
1758 int KX_GameObject::pyattr_set_lin_vel_min(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1760 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1761 KX_IPhysicsController *spc = self->GetPhysicsController();
1762 MT_Scalar val = PyFloat_AsDouble(value);
1763 if (val < 0.0f) { /* also accounts for non float */
1764 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMin = float: KX_GameObject, expected a float zero or above");
1765 return PY_SET_ATTR_FAIL;
1769 spc->SetLinVelocityMin(val);
1771 return PY_SET_ATTR_SUCCESS;
1774 PyObject* KX_GameObject::pyattr_get_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1776 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1777 KX_IPhysicsController *spc = self->GetPhysicsController();
1778 return PyFloat_FromDouble(spc ? spc->GetLinVelocityMax() : 0.0f);
1781 int KX_GameObject::pyattr_set_lin_vel_max(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1783 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1784 KX_IPhysicsController *spc = self->GetPhysicsController();
1785 MT_Scalar val = PyFloat_AsDouble(value);
1786 if (val < 0.0f) { /* also accounts for non float */
1787 PyErr_SetString(PyExc_AttributeError, "gameOb.linVelocityMax = float: KX_GameObject, expected a float zero or above");
1788 return PY_SET_ATTR_FAIL;
1792 spc->SetLinVelocityMax(val);
1794 return PY_SET_ATTR_SUCCESS;
1798 PyObject* KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1800 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1801 return PyBool_FromLong(self->GetVisible());
1804 int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1806 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1807 int param = PyObject_IsTrue( value );
1809 PyErr_SetString(PyExc_AttributeError, "gameOb.visible = bool: KX_GameObject, expected True or False");
1810 return PY_SET_ATTR_FAIL;
1813 self->SetVisible(param, false);
1814 self->UpdateBuckets(false);
1815 return PY_SET_ATTR_SUCCESS;
1818 PyObject* KX_GameObject::pyattr_get_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1820 #ifdef USE_MATHUTILS
1821 return newVectorObject_cb((PyObject *)self_v, 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_GLOBAL);
1823 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1824 return PyObjectFrom(self->NodeGetWorldPosition());
1828 int KX_GameObject::pyattr_set_worldPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1830 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1832 if (!PyVecTo(value, pos))
1833 return PY_SET_ATTR_FAIL;
1835 self->NodeSetWorldPosition(pos);
1836 self->NodeUpdateGS(0.f);
1837 return PY_SET_ATTR_SUCCESS;
1840 PyObject* KX_GameObject::pyattr_get_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1842 #ifdef USE_MATHUTILS
1843 return newVectorObject_cb((PyObject *)self_v, 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_POS_LOCAL);
1845 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1846 return PyObjectFrom(self->NodeGetLocalPosition());
1850 int KX_GameObject::pyattr_set_localPosition(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1852 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1854 if (!PyVecTo(value, pos))
1855 return PY_SET_ATTR_FAIL;
1857 self->NodeSetLocalPosition(pos);
1858 self->NodeUpdateGS(0.f);
1859 return PY_SET_ATTR_SUCCESS;
1862 PyObject* KX_GameObject::pyattr_get_localInertia(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1864 #ifdef USE_MATHUTILS
1865 return newVectorObject_cb((PyObject *)self_v, 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_INERTIA_LOCAL);
1867 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1868 if (self->GetPhysicsController())
1869 return PyObjectFrom(self->GetPhysicsController()->GetLocalInertia());
1870 return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
1874 PyObject* KX_GameObject::pyattr_get_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1876 #ifdef USE_MATHUTILS
1877 return newMatrixObject_cb((PyObject *)self_v, 3, 3, mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_GLOBAL);
1879 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1880 return PyObjectFrom(self->NodeGetWorldOrientation());
1884 int KX_GameObject::pyattr_set_worldOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1886 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1888 /* if value is not a sequence PyOrientationTo makes an error */
1890 if (!PyOrientationTo(value, rot, "gameOb.worldOrientation = sequence: KX_GameObject, "))
1891 return PY_SET_ATTR_FAIL;
1893 self->NodeSetGlobalOrientation(rot);
1895 self->NodeUpdateGS(0.f);
1896 return PY_SET_ATTR_SUCCESS;
1899 PyObject* KX_GameObject::pyattr_get_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1901 #ifdef USE_MATHUTILS
1902 return newMatrixObject_cb((PyObject *)self_v, 3, 3, mathutils_kxgameob_matrix_cb_index, MATHUTILS_MAT_CB_ORI_LOCAL);
1904 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1905 return PyObjectFrom(self->NodeGetLocalOrientation());
1909 int KX_GameObject::pyattr_set_localOrientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1911 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1913 /* if value is not a sequence PyOrientationTo makes an error */
1915 if (!PyOrientationTo(value, rot, "gameOb.localOrientation = sequence: KX_GameObject, "))
1916 return PY_SET_ATTR_FAIL;
1918 self->NodeSetLocalOrientation(rot);
1919 self->NodeUpdateGS(0.f);
1920 return PY_SET_ATTR_SUCCESS;
1923 PyObject* KX_GameObject::pyattr_get_worldScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1925 #ifdef USE_MATHUTILS
1926 return newVectorObject_cb((PyObject *)self_v, 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_GLOBAL);
1928 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1929 return PyObjectFrom(self->NodeGetWorldScaling());
1933 PyObject* KX_GameObject::pyattr_get_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1935 #ifdef USE_MATHUTILS
1936 return newVectorObject_cb((PyObject *)self_v, 3, mathutils_kxgameob_vector_cb_index, MATHUTILS_VEC_CB_SCALE_LOCAL);
1938 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1939 return PyObjectFrom(self->NodeGetLocalScaling());
1943 int KX_GameObject::pyattr_set_localScaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1945 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1947 if (!PyVecTo(value, scale))
1948 return PY_SET_ATTR_FAIL;
1950 self->NodeSetLocalScale(scale);
1951 self->NodeUpdateGS(0.f);
1952 return PY_SET_ATTR_SUCCESS;
1955 PyObject* KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1957 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1959 if (self->GetSGNode() && (sg_parent = self->GetSGNode()->GetSGParent()) != NULL && sg_parent->IsSlowParent()) {
1960 return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->GetTimeOffset());
1962 return PyFloat_FromDouble(0.0);
1966 int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1968 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1969 if (self->GetSGNode()) {
1970 MT_Scalar val = PyFloat_AsDouble(value);
1971 SG_Node* sg_parent= self->GetSGNode()->GetSGParent();
1972 if (val < 0.0f) { /* also accounts for non float */
1973 PyErr_SetString(PyExc_AttributeError, "gameOb.timeOffset = float: KX_GameObject, expected a float zero or above");
1974 return PY_SET_ATTR_FAIL;
1976 if (sg_parent && sg_parent->IsSlowParent())
1977 static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->SetTimeOffset(val);
1979 return PY_SET_ATTR_SUCCESS;
1982 PyObject* KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1984 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1986 state |= self->GetState();
1987 return PyLong_FromSsize_t(state);
1990 int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1992 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1993 int state_i = PyLong_AsSsize_t(value);
1994 unsigned int state = 0;
1996 if (state_i == -1 && PyErr_Occurred()) {
1997 PyErr_SetString(PyExc_TypeError, "gameOb.state = int: KX_GameObject, expected an int bit field");
1998 return PY_SET_ATTR_FAIL;
2002 if ((state & ((1<<30)-1)) == 0) {
2003 PyErr_SetString(PyExc_AttributeError, "gameOb.state = int: KX_GameObject, state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
2004 return PY_SET_ATTR_FAIL;
2006 self->SetState(state);
2007 return PY_SET_ATTR_SUCCESS;
2010 PyObject* KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2012 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2013 PyObject *meshes= PyList_New(self->m_meshes.size());
2016 for(i=0; i < (int)self->m_meshes.size(); i++)
2018 KX_MeshProxy* meshproxy = new KX_MeshProxy(self->m_meshes[i]);
2019 PyList_SET_ITEM(meshes, i, meshproxy->NewProxy(true));
2026 PyObject* KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2028 return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_SENSORS);
2031 PyObject* KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2033 return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_CONTROLLERS);
2036 PyObject* KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2038 return KX_PythonSeq_CreatePyObject((static_cast<KX_GameObject*>(self_v))->m_proxy, KX_PYGENSEQ_OB_TYPE_ACTUATORS);
2041 PyObject* KX_GameObject::pyattr_get_children(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2043 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2044 return self->GetChildren()->NewProxy(true);
2047 PyObject* KX_GameObject::pyattr_get_children_recursive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2049 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2050 return self->GetChildrenRecursive()->NewProxy(true);
2053 PyObject* KX_GameObject::pyattr_get_attrDict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2055 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
2057 if(self->m_attr_dict==NULL)
2058 self->m_attr_dict= PyDict_New();
2060 Py_INCREF(self->m_attr_dict);
2061 return self->m_attr_dict;
2064 PyObject* KX_GameObject::PyApplyForce(PyObject* args)
2069 if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) {
2071 if (PyVecTo(pyvect, force)) {
2072 ApplyForce(force, (local!=0));
2079 PyObject* KX_GameObject::PyApplyTorque(PyObject* args)
2084 if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) {
2086 if (PyVecTo(pyvect, torque)) {
2087 ApplyTorque(torque, (local!=0));
2094 PyObject* KX_GameObject::PyApplyRotation(PyObject* args)
2099 if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) {
2100 MT_Vector3 rotation;
2101 if (PyVecTo(pyvect, rotation)) {
2102 ApplyRotation(rotation, (local!=0));
2109 PyObject* KX_GameObject::PyApplyMovement(PyObject* args)
2114 if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) {
2115 MT_Vector3 movement;
2116 if (PyVecTo(pyvect, movement)) {
2117 ApplyMovement(movement, (local!=0));
2124 PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* args)
2126 // only can get the velocity if we have a physics object connected to us...
2128 if (PyArg_ParseTuple(args,"|i:getLinearVelocity",&local))
2130 return PyObjectFrom(GetLinearVelocity((local!=0)));
2138 PyObject* KX_GameObject::PySetLinearVelocity(PyObject* args)
2143 if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) {
2144 MT_Vector3 velocity;
2145 if (PyVecTo(pyvect, velocity)) {
2146 setLinearVelocity(velocity, (local!=0));
2153 PyObject* KX_GameObject::PyGetAngularVelocity(PyObject* args)
2155 // only can get the velocity if we have a physics object connected to us...
2157 if (PyArg_ParseTuple(args,"|i:getAngularVelocity",&local))
2159 return PyObjectFrom(GetAngularVelocity((local!=0)));
2167 PyObject* KX_GameObject::PySetAngularVelocity(PyObject* args)
2172 if (PyArg_ParseTuple(args,"O|i:setAngularVelocity",&pyvect,&local)) {
2173 MT_Vector3 velocity;
2174 if (PyVecTo(pyvect, velocity)) {
2175 setAngularVelocity(velocity, (local!=0));
2182 PyObject* KX_GameObject::PySetVisible(PyObject* args)
2184 int visible, recursive = 0;
2185 if (!PyArg_ParseTuple(args,"i|i:setVisible",&visible, &recursive))
2188 SetVisible(visible ? true:false, recursive ? true:false);
2189 UpdateBuckets(recursive ? true:false);
2194 PyObject* KX_GameObject::PySetOcclusion(PyObject* args)
2196 int occlusion, recursive = 0;
2197 if (!PyArg_ParseTuple(args,"i|i:setOcclusion",&occlusion, &recursive))
2200 SetOccluder(occlusion ? true:false, recursive ? true:false);
2204 PyObject* KX_GameObject::PyGetVisible()
2206 ShowDeprecationWarning("getVisible()", "the visible property");
2207 return PyLong_FromSsize_t(m_bVisible);
2210 PyObject* KX_GameObject::PyGetState()
2212 ShowDeprecationWarning("getState()", "the state property");
2214 state |= GetState();
2215 return PyLong_FromSsize_t(state);
2218 PyObject* KX_GameObject::PySetState(PyObject* value)
2220 ShowDeprecationWarning("setState()", "the state property");
2221 int state_i = PyLong_AsSsize_t(value);
2222 unsigned int state = 0;
2224 if (state_i == -1 && PyErr_Occurred()) {
2225 PyErr_SetString(PyExc_TypeError, "expected an int bit field");
2230 if ((state & ((1<<30)-1)) == 0) {
2231 PyErr_SetString(PyExc_AttributeError, "The state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
2239 PyObject* KX_GameObject::PyGetVelocity(PyObject* args)
2241 // only can get the velocity if we have a physics object connected to us...
2242 MT_Point3 point(0.0,0.0,0.0);
2243 PyObject* pypos = NULL;
2245 if (!PyArg_ParseTuple(args, "|O:getVelocity", &pypos) || (pypos && !PyVecTo(pypos, point)))
2248 if (m_pPhysicsController1)
2250 return PyObjectFrom(m_pPhysicsController1->GetVelocity(point));
2253 return PyObjectFrom(MT_Vector3(0.0,0.0,0.0));
2259 PyObject* KX_GameObject::PyGetMass()
2261 ShowDeprecationWarning("getMass()", "the mass property");
2262 return PyFloat_FromDouble((GetPhysicsController() != NULL) ? GetPhysicsController()->GetMass() : 0.0f);
2265 PyObject* KX_GameObject::PyGetReactionForce()
2267 // only can get the velocity if we have a physics object connected to us...
2269 // XXX - Currently not working with bullet intergration, see KX_BulletPhysicsController.cpp's getReactionForce
2271 if (GetPhysicsController())
2272 return PyObjectFrom(GetPhysicsController()->getReactionForce());
2273 return PyObjectFrom(dummy_point);
2276 return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
2282 PyObject* KX_GameObject::PyEnableRigidBody()
2284 if(GetPhysicsController())
2285 GetPhysicsController()->setRigidBody(true);
2292 PyObject* KX_GameObject::PyDisableRigidBody()
2294 if(GetPhysicsController())
2295 GetPhysicsController()->setRigidBody(false);
2302 PyObject* KX_GameObject::PyGetParent()
2304 ShowDeprecationWarning("getParent()", "the parent property");
2305 KX_GameObject* parent = this->GetParent();
2307 parent->Release(); /* self->GetParent() AddRef's */
2308 return parent->GetProxy();
2313 PyObject* KX_GameObject::PySetParent(PyObject* args)
2315 KX_Scene *scene = KX_GetActiveScene();
2318 int addToCompound=1, ghost=1;
2320 if (!PyArg_ParseTuple(args,"O|ii:setParent", &pyobj, &addToCompound, &ghost)) {
2321 return NULL; // Python sets a simple error
2323 if (!ConvertPythonToGameObject(pyobj, &obj, true, "gameOb.setParent(obj): KX_GameObject"))
2326 this->SetParent(scene, obj, addToCompound, ghost);
2330 PyObject* KX_GameObject::PyRemoveParent()
2332 KX_Scene *scene = KX_GetActiveScene();
2334 this->RemoveParent(scene);
2338 PyObject* KX_GameObject::PyGetChildren()
2340 ShowDeprecationWarning("getChildren()", "the children property");
2342 return GetChildren()->NewProxy(true);
2345 PyObject* KX_GameObject::PyGetChildrenRecursive()
2347 ShowDeprecationWarning("getChildrenRecursive()", "the childrenRecursive property");
2349 return GetChildrenRecursive()->NewProxy(true);
2352 PyObject* KX_GameObject::PyGetMesh(PyObject* args)
2354 ShowDeprecationWarning("getMesh()", "the meshes property (now a list of meshes)");
2358 if (!PyArg_ParseTuple(args, "|i:getMesh", &mesh))
2359 return NULL; // python sets a simple error
2361 if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0)
2363 KX_MeshProxy* meshproxy = new KX_MeshProxy(m_meshes[mesh]);
2364 return meshproxy->NewProxy(true); // XXX Todo Python own.
2374 PyObject* KX_GameObject::PySetCollisionMargin(PyObject* value)
2376 float collisionMargin = PyFloat_AsDouble(value);
2378 if (collisionMargin==-1 && PyErr_Occurred()) {
2379 PyErr_SetString(PyExc_TypeError, "expected a float");
2383 if (m_pPhysicsController1)
2385 m_pPhysicsController1->setMargin(collisionMargin);
2388 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
2394 PyObject* KX_GameObject::PyApplyImpulse(PyObject* args)
2397 PyObject* pyimpulse;
2399 if (!m_pPhysicsController1) {
2400 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
2404 if (PyArg_ParseTuple(args, "OO:applyImpulse", &pyattach, &pyimpulse))
2408 if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
2410 m_pPhysicsController1->applyImpulse(attach, impulse);
2421 PyObject* KX_GameObject::PySuspendDynamics()
2429 PyObject* KX_GameObject::PyRestoreDynamics()
2437 PyObject* KX_GameObject::PyGetOrientation() //keywords
2439 ShowDeprecationWarning("getOrientation()", "the orientation property");
2440 return PyObjectFrom(NodeGetWorldOrientation());
2445 PyObject* KX_GameObject::PySetOrientation(PyObject* value)
2447 ShowDeprecationWarning("setOrientation()", "the orientation property");
2450 /* if value is not a sequence PyOrientationTo makes an error */
2451 if (!PyOrientationTo(value, rot, "gameOb.setOrientation(sequence): KX_GameObject, "))
2454 NodeSetLocalOrientation(rot);
2459 PyObject* KX_GameObject::PyAlignAxisToVect(PyObject* args)
2462 int axis = 2; //z axis is the default
2465 if (PyArg_ParseTuple(args,"O|if:alignAxisToVect",&pyvect,&axis, &fac))
2468 if (PyVecTo(pyvect, vect))
2470 if (fac<=0.0) Py_RETURN_NONE; // Nothing to do.
2471 if (fac> 1.0) fac= 1.0;
2473 AlignAxisToVect(vect,axis,fac);
2481 PyObject* KX_GameObject::PyGetAxisVect(PyObject* value)
2484 if (PyVecTo(value, vect))
2486 return PyObjectFrom(NodeGetWorldOrientation() * vect);
2491 PyObject* KX_GameObject::PySetPosition(PyObject* value)
2493 ShowDeprecationWarning("setPosition()", "the localPosition property");
2495 if (PyVecTo(value, pos))
2497 NodeSetLocalPosition(pos);
2505 PyObject* KX_GameObject::PySetWorldPosition(PyObject* value)
2507 ShowDeprecationWarning("setWorldPosition()", "the worldPosition property");
2509 if (PyVecTo(value, pos))
2511 NodeSetWorldPosition(pos);
2519 PyObject* KX_GameObject::PyGetPhysicsId()
2521 KX_IPhysicsController* ctrl = GetPhysicsController();
2525 physid= (uint_ptr)ctrl->GetUserData();
2527 return PyLong_FromSsize_t((long)physid);
2530 PyObject* KX_GameObject::PyGetPropertyNames()
2532 PyObject *list= ConvertKeysToPython();
2535 PyObject *key, *value;
2538 while (PyDict_Next(m_attr_dict, &pos, &key, &value)) {
2539 PyList_Append(list, key);
2545 KX_PYMETHODDEF_DOC_O(KX_GameObject, getDistanceTo,
2546 "getDistanceTo(other): get distance to another point/KX_GameObject")
2549 if (PyVecTo(value, b))
2551 return PyFloat_FromDouble(NodeGetWorldPosition().distance(b));
2555 KX_GameObject *other;
2556 if (ConvertPythonToGameObject(value, &other, false, "gameOb.getDistanceTo(value): KX_GameObject"))
2558 return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition()));
2564 KX_PYMETHODDEF_DOC_O(KX_GameObject, getVectTo,
2565 "getVectTo(other): get vector and the distance to another point/KX_GameObject\n"
2566 "Returns a 3-tuple with (distance,worldVector,localVector)\n")
2568 MT_Point3 toPoint, fromPoint;
2569 MT_Vector3 toDir, locToDir;
2572 PyObject *returnValue;
2574 if (!PyVecTo(value, toPoint))
2578 KX_GameObject *other;
2579 if (ConvertPythonToGameObject(value, &other, false, "")) /* error will be overwritten */
2581 toPoint = other->NodeGetWorldPosition();
2584 PyErr_SetString(PyExc_TypeError, "gameOb.getVectTo(other): KX_GameObject, expected a 3D Vector or KX_GameObject type");
2589 fromPoint = NodeGetWorldPosition();
2590 toDir = toPoint-fromPoint;
2591 distance = toDir.length();
2593 if (MT_fuzzyZero(distance))
2595 //cout << "getVectTo() Error: Null vector!\n";
2596 locToDir = toDir = MT_Vector3(0.0,0.0,0.0);
2600 locToDir = toDir * NodeGetWorldOrientation();
2603 returnValue = PyTuple_New(3);
2604 if (returnValue) { // very unlikely to fail, python sets a memory error here.
2605 PyTuple_SET_ITEM(returnValue, 0, PyFloat_FromDouble(distance));
2606 PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(toDir));
2607 PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(locToDir));
2612 bool KX_GameObject::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
2614 KX_GameObject* hitKXObj = client->m_gameobject;
2616 // if X-ray option is selected, the unwnted objects were not tested, so get here only with true hit
2617 // if not, all objects were tested and the front one may not be the correct one.
2618 if (m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
2620 m_pHitObject = hitKXObj;
2623 // return true to stop RayCast::RayTest from looping, the above test was decisive
2624 // We would want to loop only if we want to get more than one hit point
2628 /* this function is used to pre-filter the object before casting the ray on them.
2629 This is useful for "X-Ray" option when we want to see "through" unwanted object.
2631 bool KX_GameObject::NeedRayCast(KX_ClientObjectInfo* client)
2633 KX_GameObject* hitKXObj = client->m_gameobject;
2635 if (client->m_type > KX_ClientObjectInfo::ACTOR)
2637 // Unknown type of object, skip it.
2638 // Should not occur as the sensor objects are filtered in RayTest()
2639 printf("Invalid client type %d found in ray casting\n", client->m_type);
2643 // if X-Ray option is selected, skip object that don't match the criteria as we see through them
2644 // if not, test all objects because we don't know yet which one will be on front
2645 if (!m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
2653 KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
2654 "rayCastTo(other,dist,prop): look towards another point/KX_GameObject and return first object hit within dist that matches prop\n"
2655 " prop = property name that object must have; can be omitted => detect any object\n"
2656 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to other\n"
2657 " other = 3-tuple or object reference")
2662 char *propName = NULL;
2664 if (!PyArg_ParseTuple(args,"O|fs:rayCastTo", &pyarg, &dist, &propName)) {
2665 return NULL; // python sets simple error
2668 if (!PyVecTo(pyarg, toPoint))
2670 KX_GameObject *other;
2673 if (ConvertPythonToGameObject(pyarg, &other, false, "")) /* error will be overwritten */
2675 toPoint = other->NodeGetWorldPosition();
2678 PyErr_SetString(PyExc_TypeError, "gameOb.rayCastTo(other,dist,prop): KX_GameObject, the first argument to rayCastTo must be a vector or a KX_GameObject");
2682 MT_Point3 fromPoint = NodeGetWorldPosition();
2685 MT_Vector3 toDir = toPoint-fromPoint;
2687 toPoint = fromPoint + (dist) * toDir;
2689 PHY_IPhysicsEnvironment* pe = KX_GetActiveScene()->GetPhysicsEnvironment();
2690 KX_IPhysicsController *spc = GetPhysicsController();
2691 KX_GameObject *parent = GetParent();
2693 spc = parent->GetPhysicsController();
2697 m_pHitObject = NULL;
2699 m_testPropName = propName;
2701 m_testPropName.SetLength(0);
2702 KX_RayCast::Callback<KX_GameObject> callback(this,spc);
2703 KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
2706 return m_pHitObject->GetProxy();
2711 /* faster then Py_BuildValue since some scripts call raycast a lot */
2712 static PyObject *none_tuple_3()
2714 PyObject *ret= PyTuple_New(3);
2715 PyTuple_SET_ITEM(ret, 0, Py_None);
2716 PyTuple_SET_ITEM(ret, 1, Py_None);
2717 PyTuple_SET_ITEM(ret, 2, Py_None);
2724 static PyObject *none_tuple_4()
2726 PyObject *ret= PyTuple_New(4);
2727 PyTuple_SET_ITEM(ret, 0, Py_None);
2728 PyTuple_SET_ITEM(ret, 1, Py_None);
2729 PyTuple_SET_ITEM(ret, 2, Py_None);
2730 PyTuple_SET_ITEM(ret, 3, Py_None);
2739 KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
2740 "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) of contact point with object within dist that matches prop.\n"
2741 " If no hit, return (None,None,None) or (None,None,None,None).\n"
2742 " to = 3-tuple or object reference for destination of ray (if object, use center of object)\n"
2743 " from = 3-tuple or object reference for origin of ray (if object, use center of object)\n"
2744 " Can be None or omitted => start from self object center\n"
2745 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to to\n"
2746 " prop = property name that object must have; can be omitted => detect any object\n"
2747 " face = normal option: 1=>return face normal; 0 or omitted => normal is oriented towards origin\n"
2748 " xray = X-ray option: 1=>skip objects that don't match prop; 0 or omitted => stop on first object\n"
2749 " poly = polygon option: 1=>return value is a 4-tuple and the 4th element is a KX_PolyProxy object\n"
2750 " which can be None if hit object has no mesh or if there is no hit\n"
2751 " If 0 or omitted, return value is a 3-tuple\n"
2752 "Note: The object on which you call this method matters: the ray will ignore it.\n"
2753 " prop and xray option interact as follow:\n"
2754 " prop off, xray off: return closest hit or no hit if there is no object on the full extend of the ray\n"
2755 " prop off, xray on : idem\n"
2756 " prop on, xray off: return closest hit if it matches prop, no hit otherwise\n"
2757 " 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")
2760 MT_Point3 fromPoint;
2762 PyObject* pyfrom = NULL;
2764 char *propName = NULL;
2765 KX_GameObject *other;
2766 int face=0, xray=0, poly=0;
2768 if (!PyArg_ParseTuple(args,"O|Ofsiii:rayCast", &pyto, &pyfrom, &dist, &propName, &face, &xray, &poly)) {
2769 return NULL; // Python sets a simple error
2772 if (!PyVecTo(pyto, toPoint))
2776 if (ConvertPythonToGameObject(pyto, &other, false, "")) /* error will be overwritten */
2778 toPoint = other->NodeGetWorldPosition();
2781 PyErr_SetString(PyExc_TypeError, "the first argument to rayCast must be a vector or a KX_GameObject");
2785 if (!pyfrom || pyfrom == Py_None)
2787 fromPoint = NodeGetWorldPosition();
2789 else if (!PyVecTo(pyfrom, fromPoint))
2793 if (ConvertPythonToGameObject(pyfrom, &other, false, "")) /* error will be overwritten */
2795 fromPoint = other->NodeGetWorldPosition();
2798 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");
2804 MT_Vector3 toDir = toPoint-fromPoint;
2805 if (MT_fuzzyZero(toDir.length2())) {
2806 //return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2807 return none_tuple_3();
2810 toPoint = fromPoint + (dist) * toDir;
2811 } else if (MT_fuzzyZero((toPoint-fromPoint).length2())) {
2812 //return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2813 return none_tuple_3();
2816 PHY_IPhysicsEnvironment* pe = KX_GetActiveScene()->GetPhysicsEnvironment();
2817 KX_IPhysicsController *spc = GetPhysicsController();
2818 KX_GameObject *parent = GetParent();
2820 spc = parent->GetPhysicsController();
2824 m_pHitObject = NULL;
2826 m_testPropName = propName;
2828 m_testPropName.SetLength(0);
2830 // to get the hit results
2831 KX_RayCast::Callback<KX_GameObject> callback(this,spc,NULL,face);
2832 KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
2836 PyObject* returnValue = (poly) ? PyTuple_New(4) : PyTuple_New(3);
2837 if (returnValue) { // unlikely this would ever fail, if it does python sets an error
2838 PyTuple_SET_ITEM(returnValue, 0, m_pHitObject->GetProxy());
2839 PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(callback.m_hitPoint));
2840 PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(callback.m_hitNormal));
2843 if (callback.m_hitMesh)
2845 // if this field is set, then we can trust that m_hitPolygon is a valid polygon
2846 RAS_Polygon* polygon = callback.m_hitMesh->GetPolygon(callback.m_hitPolygon);
2847 KX_PolyProxy* polyproxy = new KX_PolyProxy(callback.m_hitMesh, polygon);
2848 PyTuple_SET_ITEM(returnValue, 3, polyproxy->NewProxy(true));
2853 PyTuple_SET_ITEM(returnValue, 3, Py_None);
2861 //return Py_BuildValue("OOOO", Py_None, Py_None, Py_None, Py_None);
2862 return none_tuple_4();
2864 //return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2865 return none_tuple_3();
2868 KX_PYMETHODDEF_DOC_VARARGS(KX_GameObject, sendMessage,
2869 "sendMessage(subject, [body, to])\n"
2870 "sends a message in same manner as a message actuator"
2871 "subject = Subject of the message (string)"
2872 "body = Message body (string)"
2873 "to = Name of object to send the message to")
2875 KX_Scene *scene = KX_GetActiveScene();
2877 char* body = (char *)"";
2878 char* to = (char *)"";
2879 const STR_String& from = GetName();
2881 if (!PyArg_ParseTuple(args, "s|sss:sendMessage", &subject, &body, &to))
2884 scene->GetNetworkScene()->SendMessage(to, from, subject, body);
2888 /* dict style access */
2891 /* Matches python dict.get(key, [default]) */
2892 PyObject* KX_GameObject::Pyget(PyObject *args)
2895 PyObject* def = Py_None;
2898 if (!PyArg_ParseTuple(args, "O|O:get", &key, &def))
2902 if(PyUnicode_Check(key)) {
2903 CValue *item = GetProperty(_PyUnicode_AsString(key));
2905 ret = item->ConvertValueToPython();
2909 return item->GetProxy();
2913 if (m_attr_dict && (ret=PyDict_GetItem(m_attr_dict, key))) {
2922 /* Matches python dict.has_key() */
2923 PyObject* KX_GameObject::Pyhas_key(PyObject* value)
2925 // the ONLY error case is invalid data, this is checked by the macro'd static function
2926 // that calls this one. but make sure Seq_Contains doesnt add extra errors later on.
2927 return PyBool_FromLong(Seq_Contains((PyObject *)this, value));
2930 /* ---------------------------------------------------------------------
2931 * Some stuff taken from the header
2932 * --------------------------------------------------------------------- */
2933 void KX_GameObject::Relink(GEN_Map<GEN_HashedPtr, void*> *map_parameter)
2935 // we will relink the sensors and actuators that use object references
2936 // if the object is part of the replicated hierarchy, use the new
2937 // object reference instead
2938 SCA_SensorList& sensorlist = GetSensors();
2939 SCA_SensorList::iterator sit;
2940 for (sit=sensorlist.begin(); sit != sensorlist.end(); sit++)
2942 (*sit)->Relink(map_parameter);
2944 SCA_ActuatorList& actuatorlist = GetActuators();
2945 SCA_ActuatorList::iterator ait;
2946 for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++)
2948 (*ait)->Relink(map_parameter);
2953 bool ConvertPythonToGameObject(PyObject * value, KX_GameObject **object, bool py_none_ok, const char *error_prefix)
2956 PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix);
2961 if (value==Py_None) {
2967 PyErr_Format(PyExc_TypeError, "%s, expected KX_GameObject or a KX_GameObject name, None is invalid", error_prefix);
2972 if (PyUnicode_Check(value)) {
2973 *object = (KX_GameObject*)SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String( _PyUnicode_AsString(value) ));
2978 PyErr_Format(PyExc_ValueError, "%s, requested name \"%s\" did not match any KX_GameObject in this scene", error_prefix, _PyUnicode_AsString(value));
2983 if ( PyObject_TypeCheck(value, &KX_GameObject::Type) ||
2984 PyObject_TypeCheck(value, &KX_LightObject::Type) ||
2985 PyObject_TypeCheck(value, &KX_Camera::Type) )
2987 *object = static_cast<KX_GameObject*>BGE_PROXY_REF(value);
2989 /* sets the error */
2990 if (*object==NULL) {
2991 PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix);
3001 PyErr_Format(PyExc_TypeError, "%s, expect a KX_GameObject, a string or None", error_prefix);
3003 PyErr_Format(PyExc_TypeError, "%s, expect a KX_GameObject or a string", error_prefix);