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 "RAS_MeshObject.h"
53 #include "KX_MeshProxy.h"
54 #include "KX_PolyProxy.h"
55 #include <stdio.h> // printf
56 #include "SG_Controller.h"
57 #include "KX_IPhysicsController.h"
58 #include "PHY_IGraphicController.h"
60 #include "SG_Controller.h"
61 #include "KX_ClientObjectInfo.h"
62 #include "RAS_BucketManager.h"
63 #include "KX_RayCast.h"
64 #include "KX_PythonInit.h"
65 #include "KX_PyMath.h"
66 #include "SCA_IActuator.h"
67 #include "SCA_ISensor.h"
68 #include "SCA_IController.h"
70 #include "PyObjectPlus.h" /* python stuff */
72 // This file defines relationships between parents and children
73 // in the game engine.
75 #include "KX_SG_NodeRelationships.h"
77 static MT_Point3 dummy_point= MT_Point3(0.0, 0.0, 0.0);
79 KX_GameObject::KX_GameObject(
80 void* sgReplicationInfo,
81 SG_Callbacks callbacks,
87 m_pBlenderObject(NULL),
88 m_pBlenderGroupObject(NULL),
89 m_bSuspendDynamics(false),
90 m_bUseObjectColor(false),
91 m_bIsNegativeScaling(false),
94 m_pPhysicsController1(NULL),
95 m_pGraphicController(NULL),
96 m_pPhysicsEnvironment(NULL),
101 m_ignore_activity_culling = false;
102 m_pClient_info = new KX_ClientObjectInfo(this, KX_ClientObjectInfo::ACTOR);
103 m_pSGNode = new SG_Node(this,sgReplicationInfo,callbacks);
105 // define the relationship between this node and it's parent.
107 KX_NormalParentRelation * parent_relation =
108 KX_NormalParentRelation::New();
109 m_pSGNode->SetParentRelation(parent_relation);
114 KX_GameObject::~KX_GameObject()
118 // is this delete somewhere ?
121 delete m_pClient_info;
126 // must go through controllers and make sure they will not use us anymore
127 // This is important for KX_BulletPhysicsControllers that unregister themselves
128 // from the object when they are deleted.
129 SGControllerList::iterator contit;
130 SGControllerList& controllers = m_pSGNode->GetSGControllerList();
131 for (contit = controllers.begin();contit!=controllers.end();++contit)
133 (*contit)->ClearObject();
135 m_pSGNode->SetSGClientObject(NULL);
137 if (m_pGraphicController)
139 delete m_pGraphicController;
145 CValue* KX_GameObject:: Calc(VALUE_OPERATOR op, CValue *val)
152 CValue* KX_GameObject::CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val)
159 const STR_String & KX_GameObject::GetText()
166 float KX_GameObject::GetNumber()
173 STR_String KX_GameObject::GetName()
180 void KX_GameObject::SetName(STR_String name)
183 }; // Set the name of the value
187 void KX_GameObject::ReplicaSetName(STR_String name)
196 KX_IPhysicsController* KX_GameObject::GetPhysicsController()
198 return m_pPhysicsController1;
205 KX_GameObject* KX_GameObject::GetParent()
207 KX_GameObject* result = NULL;
208 SG_Node* node = m_pSGNode;
210 while (node && !result)
212 node = node->GetSGParent();
214 result = (KX_GameObject*)node->GetSGClientObject();
224 void KX_GameObject::SetParent(KX_Scene *scene, KX_GameObject* obj)
226 // check on valid node in case a python controller holds a reference to a deleted object
227 if (obj && GetSGNode() && obj->GetSGNode() && GetSGNode()->GetSGParent() != obj->GetSGNode())
229 // Make sure the objects have some scale
230 MT_Vector3 scale1 = NodeGetWorldScaling();
231 MT_Vector3 scale2 = obj->NodeGetWorldScaling();
232 if (fabs(scale2[0]) < FLT_EPSILON ||
233 fabs(scale2[1]) < FLT_EPSILON ||
234 fabs(scale2[2]) < FLT_EPSILON ||
235 fabs(scale1[0]) < FLT_EPSILON ||
236 fabs(scale1[1]) < FLT_EPSILON ||
237 fabs(scale1[2]) < FLT_EPSILON) { return; }
239 // Remove us from our old parent and set our new parent
241 obj->GetSGNode()->AddChild(GetSGNode());
243 if (m_pPhysicsController1)
245 m_pPhysicsController1->SuspendDynamics(true);
247 // Set us to our new scale, position, and orientation
248 scale2[0] = 1.0/scale2[0];
249 scale2[1] = 1.0/scale2[1];
250 scale2[2] = 1.0/scale2[2];
251 scale1 = scale1 * scale2;
252 MT_Matrix3x3 invori = obj->NodeGetWorldOrientation().inverse();
253 MT_Vector3 newpos = invori*(NodeGetWorldPosition()-obj->NodeGetWorldPosition())*scale2;
255 NodeSetLocalScale(scale1);
256 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
257 NodeSetLocalOrientation(invori*NodeGetWorldOrientation());
259 // object will now be a child, it must be removed from the parent list
260 CListValue* rootlist = scene->GetRootParentList();
261 if (rootlist->RemoveValue(this))
262 // the object was in parent list, decrement ref count as it's now removed
264 // if the new parent is a compound object, add this object shape to the compound shape.
265 // step 0: verify this object has physical controller
266 if (m_pPhysicsController1)
268 // step 1: find the top parent (not necessarily obj)
269 KX_GameObject* rootobj = (KX_GameObject*)obj->GetSGNode()->GetRootSGParent()->GetSGClientObject();
270 // step 2: verify it has a physical controller and compound shape
271 if (rootobj != NULL &&
272 rootobj->m_pPhysicsController1 != NULL &&
273 rootobj->m_pPhysicsController1->IsCompound())
275 rootobj->m_pPhysicsController1->AddCompoundChild(m_pPhysicsController1);
278 // graphically, the object hasn't change place, no need to update m_pGraphicController
282 void KX_GameObject::RemoveParent(KX_Scene *scene)
284 // check on valid node in case a python controller holds a reference to a deleted object
285 if (GetSGNode() && GetSGNode()->GetSGParent())
287 // get the root object to remove us from compound object if needed
288 KX_GameObject* rootobj = (KX_GameObject*)GetSGNode()->GetRootSGParent()->GetSGClientObject();
289 // Set us to the right spot
290 GetSGNode()->SetLocalScale(GetSGNode()->GetWorldScaling());
291 GetSGNode()->SetLocalOrientation(GetSGNode()->GetWorldOrientation());
292 GetSGNode()->SetLocalPosition(GetSGNode()->GetWorldPosition());
294 // Remove us from our parent
295 GetSGNode()->DisconnectFromParent();
297 // the object is now a root object, add it to the parentlist
298 CListValue* rootlist = scene->GetRootParentList();
299 if (!rootlist->SearchValue(this))
300 // object was not in root list, add it now and increment ref count
301 rootlist->Add(AddRef());
302 if (m_pPhysicsController1)
304 // in case this controller was added as a child shape to the parent
305 if (rootobj != NULL &&
306 rootobj->m_pPhysicsController1 != NULL &&
307 rootobj->m_pPhysicsController1->IsCompound())
309 rootobj->m_pPhysicsController1->RemoveCompoundChild(m_pPhysicsController1);
311 m_pPhysicsController1->RestoreDynamics();
313 // graphically, the object hasn't change place, no need to update m_pGraphicController
317 void KX_GameObject::ProcessReplica(KX_GameObject* replica)
319 replica->m_pPhysicsController1 = NULL;
320 replica->m_pGraphicController = NULL;
321 replica->m_pSGNode = NULL;
322 replica->m_pClient_info = new KX_ClientObjectInfo(*m_pClient_info);
323 replica->m_pClient_info->m_gameobject = replica;
324 replica->m_state = 0;
329 CValue* KX_GameObject::GetReplica()
331 KX_GameObject* replica = new KX_GameObject(*this);
333 // this will copy properties and so on...
334 CValue::AddDataToReplica(replica);
335 ProcessReplica(replica);
342 void KX_GameObject::ApplyForce(const MT_Vector3& force,bool local)
344 if (m_pPhysicsController1)
345 m_pPhysicsController1->ApplyForce(force,local);
350 void KX_GameObject::ApplyTorque(const MT_Vector3& torque,bool local)
352 if (m_pPhysicsController1)
353 m_pPhysicsController1->ApplyTorque(torque,local);
358 void KX_GameObject::ApplyMovement(const MT_Vector3& dloc,bool local)
360 if (m_pPhysicsController1) // (IsDynamic())
362 m_pPhysicsController1->RelativeTranslate(dloc,local);
364 GetSGNode()->RelativeTranslate(dloc,GetSGNode()->GetSGParent(),local);
369 void KX_GameObject::ApplyRotation(const MT_Vector3& drot,bool local)
371 MT_Matrix3x3 rotmat(drot);
373 GetSGNode()->RelativeRotate(rotmat,local);
375 if (m_pPhysicsController1) { // (IsDynamic())
376 m_pPhysicsController1->RelativeRotate(rotmat,local);
383 GetOpenGL Matrix, returns an OpenGL 'compatible' matrix
385 double* KX_GameObject::GetOpenGLMatrix()
387 // todo: optimize and only update if necessary
388 double* fl = m_OpenGL_4x4Matrix.getPointer();
391 trans.setOrigin(GetSGNode()->GetWorldPosition());
392 trans.setBasis(GetSGNode()->GetWorldOrientation());
394 MT_Vector3 scaling = GetSGNode()->GetWorldScaling();
395 m_bIsNegativeScaling = ((scaling[0] < 0.0) ^ (scaling[1] < 0.0) ^ (scaling[2] < 0.0)) ? true : false;
396 trans.scale(scaling[0], scaling[1], scaling[2]);
402 void KX_GameObject::AddMeshUser()
404 for (size_t i=0;i<m_meshes.size();i++)
405 m_meshes[i]->AddMeshUser(this);
407 UpdateBuckets(false);
410 static void UpdateBuckets_recursive(SG_Node* node)
412 NodeList& children = node->GetSGChildren();
414 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
416 SG_Node* childnode = (*childit);
417 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
418 if (clientgameobj != NULL) // This is a GameObject
419 clientgameobj->UpdateBuckets(0);
421 // if the childobj is NULL then this may be an inverse parent link
422 // so a non recursive search should still look down this node.
423 UpdateBuckets_recursive(childnode);
427 void KX_GameObject::UpdateBuckets( bool recursive )
429 double* fl = GetOpenGLMatrix();
431 for (size_t i=0;i<m_meshes.size();i++)
432 m_meshes[i]->UpdateBuckets(this, fl, m_bUseObjectColor, m_objectColor, m_bVisible, m_bCulled);
435 UpdateBuckets_recursive(m_pSGNode);
439 void KX_GameObject::RemoveMeshes()
441 for (size_t i=0;i<m_meshes.size();i++)
442 m_meshes[i]->RemoveFromBuckets(this);
444 //note: meshes can be shared, and are deleted by KX_BlenderSceneConverter
449 void KX_GameObject::UpdateTransform()
451 if (m_pPhysicsController1)
452 // only update the transform of static object, dynamic object are handled differently
453 // note that for bullet, this does not even update the transform of static object
454 // but merely sets there collision flag to "kinematic" because the synchronization is
455 // done differently during physics simulation
456 m_pPhysicsController1->SetSumoTransform(true);
457 if (m_pGraphicController)
458 // update the culling tree
459 m_pGraphicController->SetGraphicTransform();
463 void KX_GameObject::UpdateTransformFunc(SG_IObject* node, void* gameobj, void* scene)
465 ((KX_GameObject*)gameobj)->UpdateTransform();
469 void KX_GameObject::SetDebugColor(unsigned int bgra)
471 for (size_t i=0;i<m_meshes.size();i++)
472 m_meshes[i]->DebugColor(bgra);
477 void KX_GameObject::ResetDebugColor()
479 SetDebugColor(0xff000000);
482 void KX_GameObject::InitIPO(bool ipo_as_force,
486 SGControllerList::iterator it = GetSGNode()->GetSGControllerList().begin();
488 while (it != GetSGNode()->GetSGControllerList().end()) {
489 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_RESET, true);
490 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_AS_FORCE, ipo_as_force);
491 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_IPO_ADD, ipo_add);
492 (*it)->SetOption(SG_Controller::SG_CONTR_IPO_LOCAL, ipo_local);
497 void KX_GameObject::UpdateIPO(float curframetime,
500 // just the 'normal' update procedure.
501 GetSGNode()->SetSimulatedTime(curframetime,recurse);
502 GetSGNode()->UpdateWorldData(curframetime);
508 KX_GameObject::UpdateMaterialData(
521 if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) {
522 list<RAS_MeshMaterial>::iterator mit = m_meshes[mesh]->GetFirstMaterial();
524 for(; mit != m_meshes[mesh]->GetLastMaterial(); ++mit)
526 RAS_IPolyMaterial* poly = mit->m_bucket->GetPolyMaterial();
528 if(poly->GetFlag() & RAS_BLENDERMAT )
530 KX_BlenderMaterial *m = static_cast<KX_BlenderMaterial*>(poly);
532 if (matname_hash == 0)
534 m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
535 // if mesh has only one material attached to it then use original hack with no need to edit vertices (better performance)
536 SetObjectColor(rgba);
540 if (matname_hash == poly->GetMaterialNameHash())
542 m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha);
543 m_meshes[mesh]->SetVertexColor(poly,rgba);
545 // no break here, because one blender material can be split into several game engine materials
546 // (e.g. one uvsphere material is split into one material at poles with ras_mode TRIANGLE and one material for the body
547 // if here was a break then would miss some vertices if material was split
555 KX_GameObject::GetVisible(
562 static void setVisible_recursive(SG_Node* node, bool v)
564 NodeList& children = node->GetSGChildren();
566 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
568 SG_Node* childnode = (*childit);
569 KX_GameObject *clientgameobj = static_cast<KX_GameObject*>( (*childit)->GetSGClientObject());
570 if (clientgameobj != NULL) // This is a GameObject
571 clientgameobj->SetVisible(v, 0);
573 // if the childobj is NULL then this may be an inverse parent link
574 // so a non recursive search should still look down this node.
575 setVisible_recursive(childnode, v);
581 KX_GameObject::SetVisible(
588 setVisible_recursive(m_pSGNode, v);
592 KX_GameObject::GetCulled(
600 KX_GameObject::SetCulled(
609 KX_GameObject::SetLayer(
617 KX_GameObject::GetLayer(
624 void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local)
626 if (m_pPhysicsController1)
628 MT_Vector3 lv = local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
629 m_pPhysicsController1->SetLinearVelocity(lv + m_pPhysicsController1->GetLinearVelocity(), 0);
635 void KX_GameObject::setLinearVelocity(const MT_Vector3& lin_vel,bool local)
637 if (m_pPhysicsController1)
638 m_pPhysicsController1->SetLinearVelocity(lin_vel,local);
643 void KX_GameObject::setAngularVelocity(const MT_Vector3& ang_vel,bool local)
645 if (m_pPhysicsController1)
646 m_pPhysicsController1->SetAngularVelocity(ang_vel,local);
650 void KX_GameObject::ResolveCombinedVelocities(
651 const MT_Vector3 & lin_vel,
652 const MT_Vector3 & ang_vel,
656 if (m_pPhysicsController1)
659 MT_Vector3 lv = lin_vel_local ? NodeGetWorldOrientation() * lin_vel : lin_vel;
660 MT_Vector3 av = ang_vel_local ? NodeGetWorldOrientation() * ang_vel : ang_vel;
661 m_pPhysicsController1->resolveCombinedVelocities(
662 lv.x(),lv.y(),lv.z(),av.x(),av.y(),av.z());
667 void KX_GameObject::SetObjectColor(const MT_Vector4& rgbavec)
669 m_bUseObjectColor = true;
670 m_objectColor = rgbavec;
673 void KX_GameObject::AlignAxisToVect(const MT_Vector3& dir, int axis, float fac)
676 MT_Vector3 vect,ori,z,x,y;
679 // check on valid node in case a python controller holds a reference to a deleted object
685 if (MT_fuzzyZero(len))
687 cout << "alignAxisToVect() Error: Null vector!\n";
697 orimat = GetSGNode()->GetWorldOrientation();
701 ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]); //pivot axis
702 if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON) //is the vector paralell to the pivot?
703 ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]); //change the pivot!
707 x = (vect * fac) + ((orimat * MT_Vector3(1.0, 0.0, 0.0)) * (1-fac));
709 if (MT_fuzzyZero(len)) x = vect;
716 ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
717 if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
718 ori.setValue(orimat[0][2], orimat[1][2], orimat[2][2]);
722 y = (vect * fac) + ((orimat * MT_Vector3(0.0, 1.0, 0.0)) * (1-fac));
724 if (MT_fuzzyZero(len)) y = vect;
731 ori.setValue(orimat[0][1], orimat[1][1], orimat[2][1]);
732 if (MT_abs(vect.dot(ori)) > 1.0-3.0*MT_EPSILON)
733 ori.setValue(orimat[0][0], orimat[1][0], orimat[2][0]);
737 z = (vect * fac) + ((orimat * MT_Vector3(0.0, 0.0, 1.0)) * (1-fac));
739 if (MT_fuzzyZero(len)) z = vect;
745 default: //wrong input?
746 cout << "alignAxisToVect(): Wrong axis '" << axis <<"'\n";
749 x.normalize(); //normalize the vectors
752 orimat.setValue( x[0],y[0],z[0],
755 if (GetSGNode()->GetSGParent() != NULL)
757 // the object is a child, adapt its local orientation so that
758 // the global orientation is aligned as we want.
759 MT_Matrix3x3 invori = GetSGNode()->GetSGParent()->GetWorldOrientation().inverse();
760 NodeSetLocalOrientation(invori*orimat);
763 NodeSetLocalOrientation(orimat);
766 MT_Scalar KX_GameObject::GetMass()
768 if (m_pPhysicsController1)
770 return m_pPhysicsController1->GetMass();
775 MT_Vector3 KX_GameObject::GetLinearVelocity(bool local)
777 MT_Vector3 velocity(0.0,0.0,0.0), locvel;
779 if (m_pPhysicsController1)
781 velocity = m_pPhysicsController1->GetLinearVelocity();
785 ori = GetSGNode()->GetWorldOrientation();
787 locvel = velocity * ori;
794 MT_Vector3 KX_GameObject::GetAngularVelocity(bool local)
796 MT_Vector3 velocity(0.0,0.0,0.0), locvel;
798 if (m_pPhysicsController1)
800 velocity = m_pPhysicsController1->GetAngularVelocity();
804 ori = GetSGNode()->GetWorldOrientation();
806 locvel = velocity * ori;
813 MT_Vector3 KX_GameObject::GetVelocity(const MT_Point3& point)
815 if (m_pPhysicsController1)
817 return m_pPhysicsController1->GetVelocity(point);
819 return MT_Vector3(0.0,0.0,0.0);
822 // scenegraph node stuff
824 void KX_GameObject::NodeSetLocalPosition(const MT_Point3& trans)
826 // check on valid node in case a python controller holds a reference to a deleted object
830 if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
832 // don't update physic controller if the object is a child:
833 // 1) the transformation will not be right
834 // 2) in this case, the physic controller is necessarily a static object
835 // that is updated from the normal kinematic synchronization
836 m_pPhysicsController1->setPosition(trans);
839 GetSGNode()->SetLocalPosition(trans);
845 void KX_GameObject::NodeSetLocalOrientation(const MT_Matrix3x3& rot)
847 // check on valid node in case a python controller holds a reference to a deleted object
851 if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
854 m_pPhysicsController1->setOrientation(rot);
856 GetSGNode()->SetLocalOrientation(rot);
861 void KX_GameObject::NodeSetLocalScale(const MT_Vector3& scale)
863 // check on valid node in case a python controller holds a reference to a deleted object
867 if (m_pPhysicsController1 && !GetSGNode()->GetSGParent())
870 m_pPhysicsController1->setScaling(scale);
872 GetSGNode()->SetLocalScale(scale);
877 void KX_GameObject::NodeSetRelativeScale(const MT_Vector3& scale)
881 GetSGNode()->RelativeScale(scale);
882 if (m_pPhysicsController1 && (!GetSGNode()->GetSGParent()))
885 // we can use the local scale: it's the same thing for a root object
886 // and the world scale is not yet updated
887 MT_Vector3 newscale = GetSGNode()->GetLocalScale();
888 m_pPhysicsController1->setScaling(newscale);
893 void KX_GameObject::NodeSetWorldPosition(const MT_Point3& trans)
895 SG_Node* parent = m_pSGNode->GetSGParent();
898 // Make sure the objects have some scale
899 MT_Vector3 scale = parent->GetWorldScaling();
900 if (fabs(scale[0]) < FLT_EPSILON ||
901 fabs(scale[1]) < FLT_EPSILON ||
902 fabs(scale[2]) < FLT_EPSILON)
906 scale[0] = 1.0/scale[0];
907 scale[1] = 1.0/scale[1];
908 scale[2] = 1.0/scale[2];
909 MT_Matrix3x3 invori = parent->GetWorldOrientation().inverse();
910 MT_Vector3 newpos = invori*(trans-parent->GetWorldPosition())*scale;
911 NodeSetLocalPosition(MT_Point3(newpos[0],newpos[1],newpos[2]));
915 NodeSetLocalPosition(trans);
920 void KX_GameObject::NodeUpdateGS(double time)
923 GetSGNode()->UpdateWorldData(time);
928 const MT_Matrix3x3& KX_GameObject::NodeGetWorldOrientation() const
930 static MT_Matrix3x3 defaultOrientation = MT_Matrix3x3( 1.0, 0.0, 0.0,
934 // check on valid node in case a python controller holds a reference to a deleted object
936 return defaultOrientation;
937 return GetSGNode()->GetWorldOrientation();
942 const MT_Vector3& KX_GameObject::NodeGetWorldScaling() const
944 static MT_Vector3 defaultScaling = MT_Vector3(1.0, 1.0, 1.0);
946 // check on valid node in case a python controller holds a reference to a deleted object
948 return defaultScaling;
950 return GetSGNode()->GetWorldScaling();
955 const MT_Point3& KX_GameObject::NodeGetWorldPosition() const
957 // check on valid node in case a python controller holds a reference to a deleted object
959 return GetSGNode()->GetWorldPosition();
964 /* Suspend/ resume: for the dynamic behaviour, there is a simple
965 * method. For the residual motion, there is not. I wonder what the
966 * correct solution is for Sumo. Remove from the motion-update tree?
968 * So far, only switch the physics and logic.
971 void KX_GameObject::Resume(void)
974 SCA_IObject::Resume();
975 if(GetPhysicsController())
976 GetPhysicsController()->RestoreDynamics();
982 void KX_GameObject::Suspend()
984 if ((!m_ignore_activity_culling)
986 SCA_IObject::Suspend();
987 if(GetPhysicsController())
988 GetPhysicsController()->SuspendDynamics();
996 /* ------- python stuff ---------------------------------------------------*/
998 PyMethodDef KX_GameObject::Methods[] = {
999 {"setWorldPosition", (PyCFunction) KX_GameObject::sPySetWorldPosition, METH_O},
1000 {"applyForce", (PyCFunction) KX_GameObject::sPyApplyForce, METH_VARARGS},
1001 {"applyTorque", (PyCFunction) KX_GameObject::sPyApplyTorque, METH_VARARGS},
1002 {"applyRotation", (PyCFunction) KX_GameObject::sPyApplyRotation, METH_VARARGS},
1003 {"applyMovement", (PyCFunction) KX_GameObject::sPyApplyMovement, METH_VARARGS},
1004 {"getLinearVelocity", (PyCFunction) KX_GameObject::sPyGetLinearVelocity, METH_VARARGS},
1005 {"setLinearVelocity", (PyCFunction) KX_GameObject::sPySetLinearVelocity, METH_VARARGS},
1006 {"getAngularVelocity", (PyCFunction) KX_GameObject::sPyGetAngularVelocity, METH_VARARGS},
1007 {"setAngularVelocity", (PyCFunction) KX_GameObject::sPySetAngularVelocity, METH_VARARGS},
1008 {"getVelocity", (PyCFunction) KX_GameObject::sPyGetVelocity, METH_VARARGS},
1009 {"getReactionForce", (PyCFunction) KX_GameObject::sPyGetReactionForce, METH_NOARGS},
1010 {"alignAxisToVect",(PyCFunction) KX_GameObject::sPyAlignAxisToVect, METH_VARARGS},
1011 {"getAxisVect",(PyCFunction) KX_GameObject::sPyGetAxisVect, METH_O},
1012 {"suspendDynamics", (PyCFunction)KX_GameObject::sPySuspendDynamics,METH_NOARGS},
1013 {"restoreDynamics", (PyCFunction)KX_GameObject::sPyRestoreDynamics,METH_NOARGS},
1014 {"enableRigidBody", (PyCFunction)KX_GameObject::sPyEnableRigidBody,METH_NOARGS},
1015 {"disableRigidBody", (PyCFunction)KX_GameObject::sPyDisableRigidBody,METH_NOARGS},
1016 {"applyImpulse", (PyCFunction) KX_GameObject::sPyApplyImpulse, METH_VARARGS},
1017 {"setCollisionMargin", (PyCFunction) KX_GameObject::sPySetCollisionMargin, METH_O},
1018 {"setParent", (PyCFunction)KX_GameObject::sPySetParent,METH_O},
1019 {"setVisible",(PyCFunction) KX_GameObject::sPySetVisible, METH_VARARGS},
1020 {"removeParent", (PyCFunction)KX_GameObject::sPyRemoveParent,METH_NOARGS},
1021 {"getChildren", (PyCFunction)KX_GameObject::sPyGetChildren,METH_NOARGS},
1022 {"getChildrenRecursive", (PyCFunction)KX_GameObject::sPyGetChildrenRecursive,METH_NOARGS},
1023 {"getPhysicsId", (PyCFunction)KX_GameObject::sPyGetPhysicsId,METH_NOARGS},
1024 {"getPropertyNames", (PyCFunction)KX_GameObject::sPyGetPropertyNames,METH_NOARGS},
1025 {"replaceMesh",(PyCFunction) KX_GameObject::sPyReplaceMesh, METH_O},
1026 {"endObject",(PyCFunction) KX_GameObject::sPyEndObject, METH_NOARGS},
1028 KX_PYMETHODTABLE(KX_GameObject, rayCastTo),
1029 KX_PYMETHODTABLE(KX_GameObject, rayCast),
1030 KX_PYMETHODTABLE_O(KX_GameObject, getDistanceTo),
1031 KX_PYMETHODTABLE_O(KX_GameObject, getVectTo),
1034 {"getPosition", (PyCFunction) KX_GameObject::sPyGetPosition, METH_NOARGS},
1035 {"setPosition", (PyCFunction) KX_GameObject::sPySetPosition, METH_O},
1036 {"getOrientation", (PyCFunction) KX_GameObject::sPyGetOrientation, METH_NOARGS},
1037 {"setOrientation", (PyCFunction) KX_GameObject::sPySetOrientation, METH_O},
1038 {"getState",(PyCFunction) KX_GameObject::sPyGetState, METH_NOARGS},
1039 {"setState",(PyCFunction) KX_GameObject::sPySetState, METH_O},
1040 {"getParent", (PyCFunction)KX_GameObject::sPyGetParent,METH_NOARGS},
1041 {"getVisible",(PyCFunction) KX_GameObject::sPyGetVisible, METH_NOARGS},
1042 {"getMass", (PyCFunction) KX_GameObject::sPyGetMass, METH_NOARGS},
1043 {"getMesh", (PyCFunction)KX_GameObject::sPyGetMesh,METH_VARARGS},
1044 {NULL,NULL} //Sentinel
1047 PyAttributeDef KX_GameObject::Attributes[] = {
1048 KX_PYATTRIBUTE_RO_FUNCTION("name", KX_GameObject, pyattr_get_name),
1049 KX_PYATTRIBUTE_RO_FUNCTION("parent", KX_GameObject, pyattr_get_parent),
1050 KX_PYATTRIBUTE_RW_FUNCTION("mass", KX_GameObject, pyattr_get_mass, pyattr_set_mass),
1051 KX_PYATTRIBUTE_RW_FUNCTION("visible", KX_GameObject, pyattr_get_visible, pyattr_set_visible),
1052 KX_PYATTRIBUTE_RW_FUNCTION("position", KX_GameObject, pyattr_get_position, pyattr_set_position),
1053 KX_PYATTRIBUTE_RW_FUNCTION("orientation",KX_GameObject,pyattr_get_orientation,pyattr_set_orientation),
1054 KX_PYATTRIBUTE_RW_FUNCTION("scaling", KX_GameObject, pyattr_get_scaling, pyattr_set_scaling),
1055 KX_PYATTRIBUTE_RW_FUNCTION("timeOffset",KX_GameObject, pyattr_get_timeOffset,pyattr_set_timeOffset),
1056 KX_PYATTRIBUTE_RW_FUNCTION("state", KX_GameObject, pyattr_get_state, pyattr_set_state),
1057 KX_PYATTRIBUTE_RO_FUNCTION("meshes", KX_GameObject, pyattr_get_meshes),
1059 KX_PYATTRIBUTE_RO_FUNCTION("__dict__", KX_GameObject, pyattr_get_dir_dict),
1061 /* Experemental, dont rely on these yet */
1062 KX_PYATTRIBUTE_RO_FUNCTION("sensors", KX_GameObject, pyattr_get_sensors),
1063 KX_PYATTRIBUTE_RO_FUNCTION("controllers", KX_GameObject, pyattr_get_controllers),
1064 KX_PYATTRIBUTE_RO_FUNCTION("actuators", KX_GameObject, pyattr_get_actuators),
1071 bool KX_GameObject::ConvertPythonVectorArgs(PyObject* args,
1077 bool error = (PyArg_ParseTuple(args,"OO",&pylist,&pylist2)) != 0;
1079 pos = ConvertPythonPylist(pylist);
1080 pos2 = ConvertPythonPylist(pylist2);
1086 PyObject* KX_GameObject::PyReplaceMesh(PyObject* self, PyObject* value)
1088 KX_Scene *scene = KX_GetActiveScene();
1092 meshname = PyString_AsString(value);
1093 if (meshname==NULL) {
1094 PyErr_SetString(PyExc_ValueError, "Expected a mesh name");
1097 mesh_pt = SCA_ILogicBrick::m_sCurrentLogicManager->GetMeshByName(STR_String(meshname));
1099 if (mesh_pt==NULL) {
1100 PyErr_SetString(PyExc_ValueError, "The mesh name given does not exist");
1103 scene->ReplaceMesh(this, (class RAS_MeshObject*)mesh_pt);
1108 PyObject* KX_GameObject::PyEndObject(PyObject* self)
1111 KX_Scene *scene = KX_GetActiveScene();
1112 scene->DelayedRemoveObject(this);
1119 PyObject* KX_GameObject::PyGetPosition(PyObject* self)
1121 ShowDeprecationWarning("getPosition()", "the position property");
1122 return PyObjectFrom(NodeGetWorldPosition());
1126 Py_ssize_t KX_GameObject::Map_Len(PyObject* self_v)
1128 return (static_cast<KX_GameObject*>(self_v))->GetPropertyCount();
1132 PyObject *KX_GameObject::Map_GetItem(PyObject *self_v, PyObject *item)
1134 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1135 const char *attr= PyString_AsString(item);
1137 PyObject* pyconvert;
1141 PyErr_SetString(PyExc_TypeError, "KX_GameObject key but a string");
1145 resultattr = self->GetProperty(attr);
1147 if(resultattr==NULL) {
1148 PyErr_SetString(PyExc_KeyError, "KX_GameObject key does not exist");
1152 pyconvert = resultattr->ConvertValueToPython();
1154 return pyconvert ? pyconvert:resultattr;
1158 int KX_GameObject::Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
1160 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1161 const char *attr= PyString_AsString(key);
1164 PyErr_SetString(PyExc_TypeError, "KX_GameObject key but a string");
1168 if (val==NULL) { /* del ob["key"] */
1169 if (self->RemoveProperty(attr)==false) {
1170 PyErr_Format(PyExc_KeyError, "KX_GameObject key \"%s\" not found", attr);
1174 else { /* ob["key"] = value */
1175 CValue* vallie = self->ConvertPythonToValue(val);
1178 return 1; /* ConvertPythonToValue sets the error */
1180 CValue* oldprop = self->GetProperty(attr);
1183 oldprop->SetValue(vallie);
1185 self->SetProperty(attr, vallie);
1194 PyMappingMethods KX_GameObject::Mapping = {
1195 (lenfunc)KX_GameObject::Map_Len, /*inquiry mp_length */
1196 (binaryfunc)KX_GameObject::Map_GetItem, /*binaryfunc mp_subscript */
1197 (objobjargproc)KX_GameObject::Map_SetItem, /*objobjargproc mp_ass_subscript */
1201 PyTypeObject KX_GameObject::Type = {
1202 PyObject_HEAD_INIT(NULL)
1205 sizeof(KX_GameObject),
1225 PyParentObject KX_GameObject::Parents[] = {
1226 &KX_GameObject::Type,
1232 PyObject* KX_GameObject::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1234 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1235 return PyString_FromString(self->GetName().ReadPtr());
1238 PyObject* KX_GameObject::pyattr_get_parent(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1240 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1241 KX_GameObject* parent = self->GetParent();
1243 return parent->AddRef();
1247 PyObject* KX_GameObject::pyattr_get_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1249 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1250 KX_IPhysicsController *spc = self->GetPhysicsController();
1251 return PyFloat_FromDouble(spc ? spc->GetMass() : 0.0f);
1254 int KX_GameObject::pyattr_set_mass(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1256 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1257 KX_IPhysicsController *spc = self->GetPhysicsController();
1258 MT_Scalar val = PyFloat_AsDouble(value);
1259 if (val < 0.0f) { /* also accounts for non float */
1260 PyErr_SetString(PyExc_AttributeError, "expected a float zero or above");
1270 PyObject* KX_GameObject::pyattr_get_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1272 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1273 return PyBool_FromLong(self->GetVisible());
1276 int KX_GameObject::pyattr_set_visible(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1278 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1279 int param = PyObject_IsTrue( value );
1281 PyErr_SetString(PyExc_AttributeError, "expected True or False");
1285 self->SetVisible(param, false);
1286 self->UpdateBuckets(false);
1290 PyObject* KX_GameObject::pyattr_get_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1292 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1293 return PyObjectFrom(self->NodeGetWorldPosition());
1296 int KX_GameObject::pyattr_set_position(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1298 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1300 if (!PyVecTo(value, pos))
1303 self->NodeSetLocalPosition(pos);
1304 self->NodeUpdateGS(0.f);
1309 PyObject* KX_GameObject::pyattr_get_orientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1311 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1312 return PyObjectFrom(self->NodeGetWorldOrientation());
1315 int KX_GameObject::pyattr_set_orientation(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1317 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1318 if (!PySequence_Check(value)) {
1319 PyErr_SetString(PyExc_AttributeError, "'orientation' attribute needs to be a sequence");
1325 if (PyMatTo(value, rot))
1327 self->NodeSetLocalOrientation(rot);
1328 self->NodeUpdateGS(0.f);
1333 if (PySequence_Size(value) == 4)
1336 if (PyVecTo(value, qrot))
1338 rot.setRotation(qrot);
1339 self->NodeSetLocalOrientation(rot);
1340 self->NodeUpdateGS(0.f);
1346 if (PySequence_Size(value) == 3)
1349 if (PyVecTo(value, erot))
1352 self->NodeSetLocalOrientation(rot);
1353 self->NodeUpdateGS(0.f);
1359 PyErr_SetString(PyExc_AttributeError, "could not set the orientation from a 3x3 matrix, quaternion or euler sequence");
1363 PyObject* KX_GameObject::pyattr_get_scaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1365 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1366 return PyObjectFrom(self->NodeGetWorldScaling());
1369 int KX_GameObject::pyattr_set_scaling(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1371 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1373 if (!PyVecTo(value, scale))
1376 self->NodeSetLocalScale(scale);
1377 self->NodeUpdateGS(0.f);
1381 PyObject* KX_GameObject::pyattr_get_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1383 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1384 SG_Node* sg_parent= self->GetSGNode()->GetSGParent();
1385 if (sg_parent && sg_parent->IsSlowParent()) {
1386 return PyFloat_FromDouble(static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->GetTimeOffset());
1388 return PyFloat_FromDouble(0.0);
1392 int KX_GameObject::pyattr_set_timeOffset(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1394 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1395 MT_Scalar val = PyFloat_AsDouble(value);
1396 SG_Node* sg_parent= self->GetSGNode()->GetSGParent();
1397 if (val < 0.0f) { /* also accounts for non float */
1398 PyErr_SetString(PyExc_AttributeError, "expected a float zero or above");
1402 if (sg_parent && sg_parent->IsSlowParent())
1403 static_cast<KX_SlowParentRelation *>(sg_parent->GetParentRelation())->SetTimeOffset(val);
1408 PyObject* KX_GameObject::pyattr_get_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1410 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1412 state |= self->GetState();
1413 return PyInt_FromLong(state);
1416 int KX_GameObject::pyattr_set_state(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1418 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1419 int state_i = PyInt_AsLong(value);
1420 unsigned int state = 0;
1422 if (state_i == -1 && PyErr_Occurred()) {
1423 PyErr_SetString(PyExc_TypeError, "expected an int bit field");
1428 if ((state & ((1<<30)-1)) == 0) {
1429 PyErr_SetString(PyExc_AttributeError, "The state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
1432 self->SetState(state);
1436 PyObject* KX_GameObject::pyattr_get_meshes(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1438 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1439 PyObject *meshes= PyList_New(self->m_meshes.size());
1442 for(i=0; i < self->m_meshes.size(); i++)
1444 KX_MeshProxy* meshproxy = new KX_MeshProxy(self->m_meshes[i]);
1445 PyList_SET_ITEM(meshes, i, meshproxy);
1453 PyObject* KX_GameObject::pyattr_get_sensors(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1455 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1456 SCA_SensorList& sensors= self->GetSensors();
1457 PyObject* resultlist = PyList_New(sensors.size());
1459 for (unsigned int index=0;index<sensors.size();index++)
1460 PyList_SET_ITEM(resultlist, index, sensors[index]->AddRef());
1465 PyObject* KX_GameObject::pyattr_get_controllers(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1467 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1468 SCA_ControllerList& controllers= self->GetControllers();
1469 PyObject* resultlist = PyList_New(controllers.size());
1471 for (unsigned int index=0;index<controllers.size();index++)
1472 PyList_SET_ITEM(resultlist, index, controllers[index]->AddRef());
1477 PyObject* KX_GameObject::pyattr_get_actuators(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1479 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1480 SCA_ActuatorList& actuators= self->GetActuators();
1481 PyObject* resultlist = PyList_New(actuators.size());
1483 for (unsigned int index=0;index<actuators.size();index++)
1484 PyList_SET_ITEM(resultlist, index, actuators[index]->AddRef());
1490 /* __dict__ only for the purpose of giving useful dir() results */
1491 PyObject* KX_GameObject::pyattr_get_dir_dict(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1493 KX_GameObject* self= static_cast<KX_GameObject*>(self_v);
1494 PyObject *dict_str = PyString_FromString("__dict__");
1495 PyObject *dict= py_getattr_dict(self->SCA_IObject::py_getattro(dict_str), Type.tp_dict);
1496 Py_DECREF(dict_str);
1501 /* Not super fast getting as a list then making into dict keys but its only for dir() */
1502 PyObject *list= self->ConvertKeysToPython();
1506 for(i=0; i<PyList_Size(list); i++)
1507 PyDict_SetItem(dict, PyList_GET_ITEM(list, i), Py_None);
1518 PyObject* KX_GameObject::py_getattro(PyObject *attr)
1520 py_getattro_up(SCA_IObject);
1523 int KX_GameObject::py_setattro(PyObject *attr, PyObject *value) // py_setattro method
1525 py_setattro_up(SCA_IObject);
1528 PyObject* KX_GameObject::PyApplyForce(PyObject* self, PyObject* args)
1533 if (PyArg_ParseTuple(args, "O|i:applyForce", &pyvect, &local)) {
1535 if (PyVecTo(pyvect, force)) {
1536 ApplyForce(force, (local!=0));
1543 PyObject* KX_GameObject::PyApplyTorque(PyObject* self, PyObject* args)
1548 if (PyArg_ParseTuple(args, "O|i:applyTorque", &pyvect, &local)) {
1550 if (PyVecTo(pyvect, torque)) {
1551 ApplyTorque(torque, (local!=0));
1558 PyObject* KX_GameObject::PyApplyRotation(PyObject* self, PyObject* args)
1563 if (PyArg_ParseTuple(args, "O|i:applyRotation", &pyvect, &local)) {
1564 MT_Vector3 rotation;
1565 if (PyVecTo(pyvect, rotation)) {
1566 ApplyRotation(rotation, (local!=0));
1573 PyObject* KX_GameObject::PyApplyMovement(PyObject* self, PyObject* args)
1578 if (PyArg_ParseTuple(args, "O|i:applyMovement", &pyvect, &local)) {
1579 MT_Vector3 movement;
1580 if (PyVecTo(pyvect, movement)) {
1581 ApplyMovement(movement, (local!=0));
1588 PyObject* KX_GameObject::PyGetLinearVelocity(PyObject* self, PyObject* args)
1590 // only can get the velocity if we have a physics object connected to us...
1592 if (PyArg_ParseTuple(args,"|i:getLinearVelocity",&local))
1594 return PyObjectFrom(GetLinearVelocity((local!=0)));
1602 PyObject* KX_GameObject::PySetLinearVelocity(PyObject* self, PyObject* args)
1607 if (PyArg_ParseTuple(args,"O|i:setLinearVelocity",&pyvect,&local)) {
1608 MT_Vector3 velocity;
1609 if (PyVecTo(pyvect, velocity)) {
1610 setLinearVelocity(velocity, (local!=0));
1617 PyObject* KX_GameObject::PyGetAngularVelocity(PyObject* self, PyObject* args)
1619 // only can get the velocity if we have a physics object connected to us...
1621 if (PyArg_ParseTuple(args,"|i:getAngularVelocity",&local))
1623 return PyObjectFrom(GetAngularVelocity((local!=0)));
1631 PyObject* KX_GameObject::PySetAngularVelocity(PyObject* self, PyObject* args)
1636 if (PyArg_ParseTuple(args,"O|i:setAngularVelocity",&pyvect,&local)) {
1637 MT_Vector3 velocity;
1638 if (PyVecTo(pyvect, velocity)) {
1639 setAngularVelocity(velocity, (local!=0));
1646 PyObject* KX_GameObject::PySetVisible(PyObject* self, PyObject* args)
1648 int visible, recursive = 0;
1649 if (!PyArg_ParseTuple(args,"i|i:setVisible",&visible, &recursive))
1652 SetVisible(visible ? true:false, recursive ? true:false);
1653 UpdateBuckets(recursive ? true:false);
1658 PyObject* KX_GameObject::PyGetVisible(PyObject* self)
1660 ShowDeprecationWarning("getVisible()", "the visible property");
1661 return PyInt_FromLong(m_bVisible);
1664 PyObject* KX_GameObject::PyGetState(PyObject* self)
1666 ShowDeprecationWarning("getState()", "the state property");
1668 state |= GetState();
1669 return PyInt_FromLong(state);
1672 PyObject* KX_GameObject::PySetState(PyObject* self, PyObject* value)
1674 ShowDeprecationWarning("setState()", "the state property");
1675 int state_i = PyInt_AsLong(value);
1676 unsigned int state = 0;
1678 if (state_i == -1 && PyErr_Occurred()) {
1679 PyErr_SetString(PyExc_TypeError, "expected an int bit field");
1684 if ((state & ((1<<30)-1)) == 0) {
1685 PyErr_SetString(PyExc_AttributeError, "The state bitfield was not between 0 and 30 (1<<0 and 1<<29)");
1693 PyObject* KX_GameObject::PyGetVelocity(PyObject* self, PyObject* args)
1695 // only can get the velocity if we have a physics object connected to us...
1696 MT_Point3 point(0.0,0.0,0.0);
1697 PyObject* pypos = NULL;
1699 if (PyArg_ParseTuple(args, "|O:getVelocity", &pypos))
1702 PyVecTo(pypos, point);
1708 if (m_pPhysicsController1)
1710 return PyObjectFrom(m_pPhysicsController1->GetVelocity(point));
1713 return PyObjectFrom(MT_Vector3(0.0,0.0,0.0));
1719 PyObject* KX_GameObject::PyGetMass(PyObject* self)
1721 ShowDeprecationWarning("getMass()", "the mass property");
1722 return PyFloat_FromDouble((GetPhysicsController() != NULL) ? GetPhysicsController()->GetMass() : 0.0f);
1727 PyObject* KX_GameObject::PyGetReactionForce(PyObject* self)
1729 // only can get the velocity if we have a physics object connected to us...
1731 // XXX - Currently not working with bullet intergration, see KX_BulletPhysicsController.cpp's getReactionForce
1733 if (GetPhysicsController())
1734 return PyObjectFrom(GetPhysicsController()->getReactionForce());
1735 return PyObjectFrom(dummy_point);
1738 return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f);
1744 PyObject* KX_GameObject::PyEnableRigidBody(PyObject* self)
1746 if(GetPhysicsController())
1747 GetPhysicsController()->setRigidBody(true);
1754 PyObject* KX_GameObject::PyDisableRigidBody(PyObject* self)
1756 if(GetPhysicsController())
1757 GetPhysicsController()->setRigidBody(false);
1764 PyObject* KX_GameObject::PyGetParent(PyObject* self)
1766 ShowDeprecationWarning("getParent()", "the parent property");
1767 KX_GameObject* parent = this->GetParent();
1769 return parent->AddRef();
1773 PyObject* KX_GameObject::PySetParent(PyObject* self, PyObject* value)
1775 if (!PyObject_TypeCheck(value, &KX_GameObject::Type)) {
1776 PyErr_SetString(PyExc_TypeError, "expected a KX_GameObject type");
1780 PyErr_SetString(PyExc_ValueError, "cannot set the object to be its own parent!");
1784 // The object we want to set as parent
1785 CValue *m_ob = (CValue*)value;
1786 KX_GameObject *obj = ((KX_GameObject*)m_ob);
1787 KX_Scene *scene = KX_GetActiveScene();
1789 this->SetParent(scene, obj);
1794 PyObject* KX_GameObject::PyRemoveParent(PyObject* self)
1796 KX_Scene *scene = KX_GetActiveScene();
1797 this->RemoveParent(scene);
1802 static void walk_children(SG_Node* node, CListValue* list, bool recursive)
1804 NodeList& children = node->GetSGChildren();
1806 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
1808 SG_Node* childnode = (*childit);
1809 CValue* childobj = (CValue*)childnode->GetSGClientObject();
1810 if (childobj != NULL) // This is a GameObject
1813 list->Add(childobj->AddRef());
1816 // if the childobj is NULL then this may be an inverse parent link
1817 // so a non recursive search should still look down this node.
1818 if (recursive || childobj==NULL) {
1819 walk_children(childnode, list, recursive);
1824 PyObject* KX_GameObject::PyGetChildren(PyObject* self)
1826 CListValue* list = new CListValue();
1827 walk_children(m_pSGNode, list, 0);
1831 PyObject* KX_GameObject::PyGetChildrenRecursive(PyObject* self)
1833 CListValue* list = new CListValue();
1834 walk_children(m_pSGNode, list, 1);
1838 PyObject* KX_GameObject::PyGetMesh(PyObject* self, PyObject* args)
1840 ShowDeprecationWarning("getMesh()", "the meshes property");
1844 if (!PyArg_ParseTuple(args, "|i:getMesh", &mesh))
1845 return NULL; // python sets a simple error
1847 if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0)
1849 KX_MeshProxy* meshproxy = new KX_MeshProxy(m_meshes[mesh]);
1860 PyObject* KX_GameObject::PySetCollisionMargin(PyObject* self, PyObject* value)
1862 float collisionMargin = PyFloat_AsDouble(value);
1864 if (collisionMargin==-1 && PyErr_Occurred()) {
1865 PyErr_SetString(PyExc_TypeError, "expected a float");
1869 if (m_pPhysicsController1)
1871 m_pPhysicsController1->setMargin(collisionMargin);
1874 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
1880 PyObject* KX_GameObject::PyApplyImpulse(PyObject* self, PyObject* args)
1883 PyObject* pyimpulse;
1885 if (!m_pPhysicsController1) {
1886 PyErr_SetString(PyExc_RuntimeError, "This object has no physics controller");
1890 if (PyArg_ParseTuple(args, "OO:applyImpulse", &pyattach, &pyimpulse))
1894 if (PyVecTo(pyattach, attach) && PyVecTo(pyimpulse, impulse))
1896 m_pPhysicsController1->applyImpulse(attach, impulse);
1907 PyObject* KX_GameObject::PySuspendDynamics(PyObject* self)
1915 PyObject* KX_GameObject::PyRestoreDynamics(PyObject* self)
1923 PyObject* KX_GameObject::PyGetOrientation(PyObject* self) //keywords
1925 ShowDeprecationWarning("getOrientation()", "the orientation property");
1926 return PyObjectFrom(NodeGetWorldOrientation());
1931 PyObject* KX_GameObject::PySetOrientation(PyObject* self, PyObject* value)
1933 ShowDeprecationWarning("setOrientation()", "the orientation property");
1934 MT_Matrix3x3 matrix;
1935 if (PyObject_IsMT_Matrix(value, 3) && PyMatTo(value, matrix))
1937 NodeSetLocalOrientation(matrix);
1943 if (PyVecTo(value, quat))
1945 matrix.setRotation(quat);
1946 NodeSetLocalOrientation(matrix);
1953 PyObject* KX_GameObject::PyAlignAxisToVect(PyObject* self, PyObject* args)
1956 int axis = 2; //z axis is the default
1959 if (PyArg_ParseTuple(args,"O|if:alignAxisToVect",&pyvect,&axis, &fac))
1962 if (PyVecTo(pyvect, vect))
1964 if (fac<=0.0) Py_RETURN_NONE; // Nothing to do.
1965 if (fac> 1.0) fac= 1.0;
1967 AlignAxisToVect(vect,axis,fac);
1975 PyObject* KX_GameObject::PyGetAxisVect(PyObject* self, PyObject* value)
1978 if (PyVecTo(value, vect))
1980 return PyObjectFrom(NodeGetWorldOrientation() * vect);
1985 PyObject* KX_GameObject::PySetPosition(PyObject* self, PyObject* value)
1987 ShowDeprecationWarning("setPosition()", "the position property");
1989 if (PyVecTo(value, pos))
1991 NodeSetLocalPosition(pos);
1999 PyObject* KX_GameObject::PySetWorldPosition(PyObject* self, PyObject* value)
2002 if (PyVecTo(value, pos))
2004 NodeSetWorldPosition(pos);
2012 PyObject* KX_GameObject::PyGetPhysicsId(PyObject* self)
2014 KX_IPhysicsController* ctrl = GetPhysicsController();
2018 physid= (uint_ptr)ctrl->GetUserData();
2020 return PyInt_FromLong((long)physid);
2023 PyObject* KX_GameObject::PyGetPropertyNames(PyObject* self)
2025 return ConvertKeysToPython();
2028 KX_PYMETHODDEF_DOC_O(KX_GameObject, getDistanceTo,
2029 "getDistanceTo(other): get distance to another point/KX_GameObject")
2032 if (PyVecTo(value, b))
2034 return PyFloat_FromDouble(NodeGetWorldPosition().distance(b));
2038 KX_GameObject *other;
2039 if (ConvertPythonToGameObject(value, &other, false))
2041 return PyFloat_FromDouble(NodeGetWorldPosition().distance(other->NodeGetWorldPosition()));
2047 KX_PYMETHODDEF_DOC_O(KX_GameObject, getVectTo,
2048 "getVectTo(other): get vector and the distance to another point/KX_GameObject\n"
2049 "Returns a 3-tuple with (distance,worldVector,localVector)\n")
2051 MT_Point3 toPoint, fromPoint;
2052 MT_Vector3 toDir, locToDir;
2055 PyObject *returnValue;
2057 if (!PyVecTo(value, toPoint))
2061 KX_GameObject *other;
2062 if (ConvertPythonToGameObject(value, &other, false))
2064 toPoint = other->NodeGetWorldPosition();
2067 PyErr_SetString(PyExc_TypeError, "Expected a 3D Vector or GameObject type");
2072 fromPoint = NodeGetWorldPosition();
2073 toDir = toPoint-fromPoint;
2074 distance = toDir.length();
2076 if (MT_fuzzyZero(distance))
2078 //cout << "getVectTo() Error: Null vector!\n";
2079 locToDir = toDir = MT_Vector3(0.0,0.0,0.0);
2083 locToDir = toDir * NodeGetWorldOrientation();
2086 returnValue = PyTuple_New(3);
2087 if (returnValue) { // very unlikely to fail, python sets a memory error here.
2088 PyTuple_SET_ITEM(returnValue, 0, PyFloat_FromDouble(distance));
2089 PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(toDir));
2090 PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(locToDir));
2095 bool KX_GameObject::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
2097 KX_GameObject* hitKXObj = client->m_gameobject;
2099 // if X-ray option is selected, the unwnted objects were not tested, so get here only with true hit
2100 // if not, all objects were tested and the front one may not be the correct one.
2101 if (m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
2103 m_pHitObject = hitKXObj;
2106 // return true to stop RayCast::RayTest from looping, the above test was decisive
2107 // We would want to loop only if we want to get more than one hit point
2111 /* this function is used to pre-filter the object before casting the ray on them.
2112 This is useful for "X-Ray" option when we want to see "through" unwanted object.
2114 bool KX_GameObject::NeedRayCast(KX_ClientObjectInfo* client)
2116 KX_GameObject* hitKXObj = client->m_gameobject;
2118 if (client->m_type > KX_ClientObjectInfo::ACTOR)
2120 // Unknown type of object, skip it.
2121 // Should not occur as the sensor objects are filtered in RayTest()
2122 printf("Invalid client type %d found in ray casting\n", client->m_type);
2126 // if X-Ray option is selected, skip object that don't match the criteria as we see through them
2127 // if not, test all objects because we don't know yet which one will be on front
2128 if (!m_xray || m_testPropName.Length() == 0 || hitKXObj->GetProperty(m_testPropName) != NULL)
2136 KX_PYMETHODDEF_DOC(KX_GameObject, rayCastTo,
2137 "rayCastTo(other,dist,prop): look towards another point/KX_GameObject and return first object hit within dist that matches prop\n"
2138 " prop = property name that object must have; can be omitted => detect any object\n"
2139 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to other\n"
2140 " other = 3-tuple or object reference")
2145 char *propName = NULL;
2147 if (!PyArg_ParseTuple(args,"O|fs:rayCastTo", &pyarg, &dist, &propName)) {
2148 return NULL; // python sets simple error
2151 if (!PyVecTo(pyarg, toPoint))
2153 KX_GameObject *other;
2156 if (ConvertPythonToGameObject(pyarg, &other, false))
2158 toPoint = other->NodeGetWorldPosition();
2161 PyErr_SetString(PyExc_TypeError, "the first argument to rayCastTo must be a vector or a KX_GameObject");
2165 MT_Point3 fromPoint = NodeGetWorldPosition();
2168 MT_Vector3 toDir = toPoint-fromPoint;
2170 toPoint = fromPoint + (dist) * toDir;
2173 PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
2174 KX_IPhysicsController *spc = GetPhysicsController();
2175 KX_GameObject *parent = GetParent();
2177 spc = parent->GetPhysicsController();
2181 m_pHitObject = NULL;
2183 m_testPropName = propName;
2185 m_testPropName.SetLength(0);
2186 KX_RayCast::Callback<KX_GameObject> callback(this,spc);
2187 KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
2190 return m_pHitObject->AddRef();
2195 KX_PYMETHODDEF_DOC(KX_GameObject, rayCast,
2196 "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"
2197 " If no hit, return (None,None,None) or (None,None,None,None).\n"
2198 " to = 3-tuple or object reference for destination of ray (if object, use center of object)\n"
2199 " from = 3-tuple or object reference for origin of ray (if object, use center of object)\n"
2200 " Can be None or omitted => start from self object center\n"
2201 " dist = max distance to look (can be negative => look behind); 0 or omitted => detect up to to\n"
2202 " prop = property name that object must have; can be omitted => detect any object\n"
2203 " face = normal option: 1=>return face normal; 0 or omitted => normal is oriented towards origin\n"
2204 " xray = X-ray option: 1=>skip objects that don't match prop; 0 or omitted => stop on first object\n"
2205 " poly = polygon option: 1=>return value is a 4-tuple and the 4th element is a KX_PolyProxy object\n"
2206 " which can be None if hit object has no mesh or if there is no hit\n"
2207 " If 0 or omitted, return value is a 3-tuple\n"
2208 "Note: The object on which you call this method matters: the ray will ignore it.\n"
2209 " prop and xray option interact as follow:\n"
2210 " prop off, xray off: return closest hit or no hit if there is no object on the full extend of the ray\n"
2211 " prop off, xray on : idem\n"
2212 " prop on, xray off: return closest hit if it matches prop, no hit otherwise\n"
2213 " 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")
2216 MT_Point3 fromPoint;
2218 PyObject* pyfrom = NULL;
2220 char *propName = NULL;
2221 KX_GameObject *other;
2222 int face=0, xray=0, poly=0;
2224 if (!PyArg_ParseTuple(args,"O|Ofsiii:rayCast", &pyto, &pyfrom, &dist, &propName, &face, &xray, &poly)) {
2225 return NULL; // Python sets a simple error
2228 if (!PyVecTo(pyto, toPoint))
2232 if (ConvertPythonToGameObject(pyto, &other, false))
2234 toPoint = other->NodeGetWorldPosition();
2237 PyErr_SetString(PyExc_TypeError, "the first argument to rayCast must be a vector or a KX_GameObject");
2241 if (!pyfrom || pyfrom == Py_None)
2243 fromPoint = NodeGetWorldPosition();
2245 else if (!PyVecTo(pyfrom, fromPoint))
2249 if (ConvertPythonToGameObject(pyfrom, &other, false))
2251 fromPoint = other->NodeGetWorldPosition();
2254 PyErr_SetString(PyExc_TypeError, "the second optional argument to rayCast must be a vector or a KX_GameObject");
2260 MT_Vector3 toDir = toPoint-fromPoint;
2261 if (MT_fuzzyZero(toDir.length2())) {
2262 return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2265 toPoint = fromPoint + (dist) * toDir;
2266 } else if (MT_fuzzyZero((toPoint-fromPoint).length2())) {
2267 return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2270 PHY_IPhysicsEnvironment* pe = GetPhysicsEnvironment();
2271 KX_IPhysicsController *spc = GetPhysicsController();
2272 KX_GameObject *parent = GetParent();
2274 spc = parent->GetPhysicsController();
2278 m_pHitObject = NULL;
2280 m_testPropName = propName;
2282 m_testPropName.SetLength(0);
2284 // to get the hit results
2285 KX_RayCast::Callback<KX_GameObject> callback(this,spc,NULL,face);
2286 KX_RayCast::RayTest(pe, fromPoint, toPoint, callback);
2290 PyObject* returnValue = (poly) ? PyTuple_New(4) : PyTuple_New(3);
2291 if (returnValue) { // unlikely this would ever fail, if it does python sets an error
2292 PyTuple_SET_ITEM(returnValue, 0, m_pHitObject->AddRef());
2293 PyTuple_SET_ITEM(returnValue, 1, PyObjectFrom(callback.m_hitPoint));
2294 PyTuple_SET_ITEM(returnValue, 2, PyObjectFrom(callback.m_hitNormal));
2297 if (callback.m_hitMesh)
2299 // if this field is set, then we can trust that m_hitPolygon is a valid polygon
2300 RAS_Polygon* polygon = callback.m_hitMesh->GetPolygon(callback.m_hitPolygon);
2301 KX_PolyProxy* polyproxy = new KX_PolyProxy(callback.m_hitMesh, polygon);
2302 PyTuple_SET_ITEM(returnValue, 3, polyproxy);
2307 PyTuple_SET_ITEM(returnValue, 3, Py_None);
2315 return Py_BuildValue("OOOO", Py_None, Py_None, Py_None, Py_None);
2317 return Py_BuildValue("OOO", Py_None, Py_None, Py_None);
2320 /* ---------------------------------------------------------------------
2321 * Some stuff taken from the header
2322 * --------------------------------------------------------------------- */
2323 void KX_GameObject::Relink(GEN_Map<GEN_HashedPtr, void*> *map_parameter)
2325 // we will relink the sensors and actuators that use object references
2326 // if the object is part of the replicated hierarchy, use the new
2327 // object reference instead
2328 SCA_SensorList& sensorlist = GetSensors();
2329 SCA_SensorList::iterator sit;
2330 for (sit=sensorlist.begin(); sit != sensorlist.end(); sit++)
2332 (*sit)->Relink(map_parameter);
2334 SCA_ActuatorList& actuatorlist = GetActuators();
2335 SCA_ActuatorList::iterator ait;
2336 for (ait=actuatorlist.begin(); ait != actuatorlist.end(); ait++)
2338 (*ait)->Relink(map_parameter);
2342 bool ConvertPythonToGameObject(PyObject * value, KX_GameObject **object, bool py_none_ok)
2345 PyErr_SetString(PyExc_TypeError, "Error in ConvertPythonToGameObject, python pointer NULL, should never happen");
2350 if (value==Py_None) {
2356 PyErr_SetString(PyExc_TypeError, "Expected KX_GameObject or a string for a name of a KX_GameObject, None is invalid");
2361 if (PyString_Check(value)) {
2362 *object = (KX_GameObject *)SCA_ILogicBrick::m_sCurrentLogicManager->GetGameObjectByName(STR_String( PyString_AsString(value) ));
2367 PyErr_SetString(PyExc_ValueError, "Requested name did not match any KX_GameObject");
2372 if (PyObject_TypeCheck(value, &KX_GameObject::Type)) {
2373 *object = static_cast<KX_GameObject*>(value);
2380 PyErr_SetString(PyExc_TypeError, "Expect a KX_GameObject, a string or None");
2382 PyErr_SetString(PyExc_TypeError, "Expect a KX_GameObject or a string");