soc-2008-mxcurioni: merge with trunk - rev 15540
[blender.git] / source / gameengine / Ketsji / KX_Scene.cpp
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * Ketsji scene. Holds references to all scene data.
29  */
30
31 #ifdef WIN32
32 #pragma warning (disable : 4786)
33 #endif //WIN32
34
35
36 #include "KX_Scene.h"
37 #include "MT_assert.h"
38
39 #include "KX_KetsjiEngine.h"
40 #include "RAS_IPolygonMaterial.h"
41 #include "ListValue.h"
42 #include "SCA_LogicManager.h"
43 #include "SCA_TimeEventManager.h"
44 #include "SCA_AlwaysEventManager.h"
45 #include "SCA_RandomEventManager.h"
46 #include "KX_RayEventManager.h"
47 #include "KX_TouchEventManager.h"
48 #include "SCA_KeyboardManager.h"
49 #include "SCA_MouseManager.h"
50 #include "SCA_PropertyEventManager.h"
51 #include "SCA_ActuatorEventManager.h"
52 #include "KX_Camera.h"
53 #include "SCA_JoystickManager.h"
54
55 #include "RAS_MeshObject.h"
56 #include "BL_SkinMeshObject.h"
57
58 #include "RAS_IRasterizer.h"
59 #include "RAS_BucketManager.h"
60
61 #include "FloatValue.h"
62 #include "SCA_IController.h"
63 #include "SCA_IActuator.h"
64 #include "SG_Node.h"
65 #include "SYS_System.h"
66 #include "SG_Controller.h"
67 #include "SG_IObject.h"
68 #include "SG_Tree.h"
69
70 #include "KX_SG_NodeRelationships.h"
71
72 #include "KX_NetworkEventManager.h"
73 #include "NG_NetworkScene.h"
74 #include "PHY_IPhysicsEnvironment.h"
75 #include "KX_IPhysicsController.h"
76 #include "KX_BlenderSceneConverter.h"
77
78 #include "BL_ShapeDeformer.h"
79 #include "BL_DeformableGameObject.h"
80
81 // to get USE_BULLET!
82 #include "KX_ConvertPhysicsObject.h"
83
84 #ifdef USE_BULLET
85 #include "CcdPhysicsEnvironment.h"
86 #include "CcdPhysicsController.h"
87 #endif
88
89 void* KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
90 {
91         KX_GameObject* replica = ((KX_Scene*)scene)->AddNodeReplicaObject(node,(KX_GameObject*)gameobj);
92
93         return (void*)replica;
94 }
95
96 void* KX_SceneDestructionFunc(SG_IObject* node,void* gameobj,void* scene)
97 {
98         ((KX_Scene*)scene)->RemoveNodeDestructObject(node,(KX_GameObject*)gameobj);
99
100         return NULL;
101 };
102
103 SG_Callbacks KX_Scene::m_callbacks = SG_Callbacks(KX_SceneReplicationFunc,KX_SceneDestructionFunc,KX_GameObject::UpdateTransformFunc);
104
105 // temporarily var until there is a button in the userinterface
106 // (defined in KX_PythonInit.cpp)
107 extern bool gUseVisibilityTemp;
108
109 KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
110                                    class SCA_IInputDevice* mousedevice,
111                                    class NG_NetworkDeviceInterface *ndi,
112                                    class SND_IAudioDevice* adi,
113                                    const STR_String& sceneName): 
114         PyObjectPlus(&KX_Scene::Type),
115         m_keyboardmgr(NULL),
116         m_mousemgr(NULL),
117         m_physicsEnvironment(0),
118         m_sceneName(sceneName),
119         m_adi(adi),
120         m_networkDeviceInterface(ndi),
121         m_active_camera(NULL),
122         m_ueberExecutionPriority(0),
123         m_sceneConverter(NULL)
124 {
125         m_suspendedtime = 0.0;
126         m_suspendeddelta = 0.0;
127
128         m_activity_culling = false;
129         m_suspend = false;
130         m_isclearingZbuffer = true;
131         m_tempObjectList = new CListValue();
132         m_objectlist = new CListValue();
133         m_parentlist = new CListValue();
134         m_lightlist= new CListValue();
135         m_inactivelist = new CListValue();
136         m_euthanasyobjects = new CListValue();
137         m_delayReleaseObjects = new CListValue();
138
139         m_logicmgr = new SCA_LogicManager();
140         
141         m_timemgr = new SCA_TimeEventManager(m_logicmgr);
142         m_keyboardmgr = new SCA_KeyboardManager(m_logicmgr,keyboarddevice);
143         m_mousemgr = new SCA_MouseManager(m_logicmgr,mousedevice);
144         
145         SCA_AlwaysEventManager* alwaysmgr = new SCA_AlwaysEventManager(m_logicmgr);
146         SCA_PropertyEventManager* propmgr = new SCA_PropertyEventManager(m_logicmgr);
147         SCA_ActuatorEventManager* actmgr = new SCA_ActuatorEventManager(m_logicmgr);
148         SCA_RandomEventManager* rndmgr = new SCA_RandomEventManager(m_logicmgr);
149         KX_RayEventManager* raymgr = new KX_RayEventManager(m_logicmgr);
150
151         KX_NetworkEventManager* netmgr = new KX_NetworkEventManager(m_logicmgr, ndi);
152         
153         SCA_JoystickManager *joymgr     = new SCA_JoystickManager(m_logicmgr);
154
155         m_logicmgr->RegisterEventManager(alwaysmgr);
156         m_logicmgr->RegisterEventManager(propmgr);
157         m_logicmgr->RegisterEventManager(actmgr);
158         m_logicmgr->RegisterEventManager(m_keyboardmgr);
159         m_logicmgr->RegisterEventManager(m_mousemgr);
160         m_logicmgr->RegisterEventManager(m_timemgr);
161         m_logicmgr->RegisterEventManager(rndmgr);
162         m_logicmgr->RegisterEventManager(raymgr);
163         m_logicmgr->RegisterEventManager(netmgr);
164         m_logicmgr->RegisterEventManager(joymgr);
165
166         m_soundScene = new SND_Scene(adi);
167         MT_assert (m_networkDeviceInterface != NULL);
168         m_networkScene = new NG_NetworkScene(m_networkDeviceInterface);
169         
170         m_rootnode = NULL;
171
172         m_bucketmanager=new RAS_BucketManager();
173
174         m_canvasDesignWidth = 0;
175         m_canvasDesignHeight = 0;
176         
177         m_attrlist = PyDict_New(); /* new ref */
178 }
179
180
181
182 KX_Scene::~KX_Scene()
183 {
184         // The release of debug properties used to be in SCA_IScene::~SCA_IScene
185         // It's still there but we remove all properties here otherwise some
186         // reference might be hanging and causing late release of objects
187         RemoveAllDebugProperties();
188
189         while (GetRootParentList()->GetCount() > 0) 
190         {
191                 KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(0);
192                 this->RemoveObject(parentobj);
193         }
194
195         if(m_objectlist)
196                 m_objectlist->Release();
197
198         if (m_parentlist)
199                 m_parentlist->Release();
200         
201         if (m_inactivelist)
202                 m_inactivelist->Release();
203
204         if (m_lightlist)
205                 m_lightlist->Release();
206         
207         if (m_tempObjectList)
208                 m_tempObjectList->Release();
209
210         if (m_euthanasyobjects)
211                 m_euthanasyobjects->Release();
212         if (m_delayReleaseObjects)
213                 m_delayReleaseObjects->Release();
214
215         if (m_logicmgr)
216                 delete m_logicmgr;
217
218         if (m_physicsEnvironment)
219                 delete m_physicsEnvironment;
220
221         if (m_soundScene)
222                 delete m_soundScene;
223
224         if (m_networkScene)
225                 delete m_networkScene;
226         
227         if (m_bucketmanager)
228         {
229                 delete m_bucketmanager;
230         }
231 #ifdef USE_BULLET
232         // This is a fix for memory leaks in bullet: the collision shapes is not destroyed 
233         // when the physical controllers are destroyed. The reason is that shapes are shared
234         // between replicas of an object. There is no reference count in Bullet so the
235         // only workaround that does not involve changes in Bullet is to save in this array
236         // the list of shapes that are created when the scene is created (see KX_ConvertPhysicsObjects.cpp)
237         class btCollisionShape* shape;
238         class btTriangleMeshShape* meshShape;
239         vector<class btCollisionShape*>::iterator it = m_shapes.begin();
240         while (it != m_shapes.end()) {
241                 shape = *it;
242                 if (shape->getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE)
243                 {
244                         meshShape = static_cast<btTriangleMeshShape*>(shape);
245                         // shapes based on meshes use an interface that contains the vertices.
246                         // Again the idea is to be able to share the interface between shapes but
247                         // this is not used in Blender: each base object will have its own interface 
248                         btStridingMeshInterface* meshInterface = meshShape->getMeshInterface();
249                         if (meshInterface)
250                                 delete meshInterface;
251                 }
252                 delete shape;
253                 it++;
254         }
255 #endif
256         //Py_DECREF(m_attrlist);
257 }
258
259 void KX_Scene::AddShape(class btCollisionShape*shape)
260 {
261         m_shapes.push_back(shape);
262 }
263
264
265 void KX_Scene::SetProjectionMatrix(MT_CmMatrix4x4& pmat)
266 {
267         m_projectionmat = pmat;
268 }
269
270
271
272 RAS_BucketManager* KX_Scene::GetBucketManager()
273 {
274         return m_bucketmanager;
275 }
276
277
278
279 CListValue* KX_Scene::GetObjectList()
280 {
281         return m_objectlist;
282 }
283
284
285
286 CListValue* KX_Scene::GetRootParentList()
287 {
288         return m_parentlist;
289 }
290
291 CListValue* KX_Scene::GetInactiveList()
292 {
293         return m_inactivelist;
294 }
295
296
297
298 CListValue* KX_Scene::GetLightList()
299 {
300         return m_lightlist;
301 }
302
303 SCA_LogicManager* KX_Scene::GetLogicManager()
304 {
305         return m_logicmgr;
306 }
307
308 SCA_TimeEventManager* KX_Scene::GetTimeEventManager()
309 {
310         return m_timemgr;
311 }
312
313
314
315  
316 list<class KX_Camera*>* KX_Scene::GetCameras()
317 {
318         return &m_cameras;
319 }
320
321
322
323 void KX_Scene::SetFramingType(RAS_FrameSettings & frame_settings)
324 {
325         m_frame_settings = frame_settings;
326 };
327
328 /**
329  * Return a const reference to the framing 
330  * type set by the above call.
331  * The contents are not guarenteed to be sensible
332  * if you don't call the above function.
333  */
334 const RAS_FrameSettings& KX_Scene::GetFramingType() const 
335 {
336         return m_frame_settings;
337 };      
338
339
340
341 /**
342  * Store the current scene's viewport on the 
343  * game engine canvas.
344  */
345 void KX_Scene::SetSceneViewport(const RAS_Rect &viewport)
346 {
347         m_viewport = viewport;
348 }
349
350
351
352 const RAS_Rect& KX_Scene::GetSceneViewport() const 
353 {
354         return m_viewport;
355 }
356
357
358
359 void KX_Scene::SetWorldInfo(class KX_WorldInfo* worldinfo)
360 {
361         m_worldinfo = worldinfo;
362 }
363
364
365
366 class KX_WorldInfo* KX_Scene::GetWorldInfo()
367 {
368         return m_worldinfo;
369 }
370
371
372
373 SND_Scene* KX_Scene::GetSoundScene()
374 {
375         return m_soundScene;
376 }
377
378 const STR_String& KX_Scene::GetName()
379 {
380         return m_sceneName;
381 }
382
383
384 void KX_Scene::Suspend()
385 {
386         m_suspend = true;
387 }
388
389 void KX_Scene::Resume()
390 {
391         m_suspend = false;
392 }
393
394 void KX_Scene::SetActivityCulling(bool b)
395 {
396         m_activity_culling = b;
397 }
398
399 bool KX_Scene::IsSuspended()
400 {
401         return m_suspend;
402 }
403
404 bool KX_Scene::IsClearingZBuffer()
405 {
406         return m_isclearingZbuffer;
407 }
408
409 void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer)
410 {
411         m_isclearingZbuffer = isclearingZbuffer;
412 }
413
414 void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj)
415 {
416         KX_GameObject* orgobj = (KX_GameObject*)gameobj;        
417         if (NewRemoveObject(orgobj) != 0)
418         {
419                 // object is not yet deleted (this can happen when it hangs in an add object actuator
420                 // last object created reference. It's a bad situation, don't know how to fix it exactly
421                 // The least I can do, is remove the reference to the node in the object as the node
422                 // will in any case be deleted. This ensures that the object will not try to use the node
423                 // when it is finally deleted (see KX_GameObject destructor)
424                 orgobj->SetSGNode(NULL);
425         }
426         if (node)
427                 delete node;
428 }
429
430 KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CValue* gameobj)
431 {
432         KX_GameObject* orgobj = (KX_GameObject*)gameobj;
433         KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica();
434         m_map_gameobject_to_replica.insert(orgobj, newobj);
435
436         // also register 'timers' (time properties) of the replica
437         int numprops = newobj->GetPropertyCount();
438
439         for (int i = 0; i < numprops; i++)
440         {
441                 CValue* prop = newobj->GetProperty(i);
442
443                 if (prop->GetProperty("timer"))
444                         this->m_timemgr->AddTimeProperty(prop);
445         }
446
447         if (node)
448         {
449                 newobj->SetSGNode((SG_Node*)node);
450         }
451         else
452         {
453                 m_rootnode = new SG_Node(newobj,this,KX_Scene::m_callbacks);
454         
455                 // this fixes part of the scaling-added object bug
456                 SG_Node* orgnode = orgobj->GetSGNode();
457                 m_rootnode->SetLocalScale(orgnode->GetLocalScale());
458                 m_rootnode->SetLocalPosition(orgnode->GetLocalPosition());
459                 m_rootnode->SetLocalOrientation(orgnode->GetLocalOrientation());
460
461                 // define the relationship between this node and it's parent.
462                 KX_NormalParentRelation * parent_relation = 
463                         KX_NormalParentRelation::New();
464                 m_rootnode->SetParentRelation(parent_relation);
465
466                 newobj->SetSGNode(m_rootnode);
467         }
468         
469         SG_IObject* replicanode = newobj->GetSGNode();
470 //      SG_Node* rootnode = (replicanode == m_rootnode ? NULL : m_rootnode);
471
472         replicanode->SetSGClientObject(newobj);
473
474         // this is the list of object that are send to the graphics pipeline
475         m_objectlist->Add(newobj->AddRef());
476         newobj->Bucketize();
477
478         // logic cannot be replicated, until the whole hierarchy is replicated.
479         m_logicHierarchicalGameObjects.push_back(newobj);
480         //replicate controllers of this node
481         SGControllerList        scenegraphcontrollers = orgobj->GetSGNode()->GetSGControllerList();
482         replicanode->RemoveAllControllers();
483         SGControllerList::iterator cit;
484         //int numcont = scenegraphcontrollers.size();
485         
486         for (cit = scenegraphcontrollers.begin();!(cit==scenegraphcontrollers.end());++cit)
487         {
488                 // controller replication is quite complicated
489                 // only replicate ipo and physics controller for now
490
491                 SG_Controller* replicacontroller = (*cit)->GetReplica((SG_Node*) replicanode);
492                 if (replicacontroller)
493                 {
494                         replicacontroller->SetObject(replicanode);
495                         replicanode->AddSGController(replicacontroller);
496                 }
497         }
498         
499         return newobj;
500 }
501
502
503
504 // before calling this method KX_Scene::ReplicateLogic(), make sure to
505 // have called 'GameObject::ReParentLogic' for each object this
506 // hierarchy that's because first ALL bricks must exist in the new
507 // replica of the hierarchy in order to make cross-links work properly
508 // !
509 void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
510 {
511         // also relink the controller to sensors/actuators
512         SCA_ControllerList& controllers = newobj->GetControllers();
513         //SCA_SensorList&     sensors     = newobj->GetSensors();
514         //SCA_ActuatorList&   actuators   = newobj->GetActuators();
515
516         for (SCA_ControllerList::iterator itc = controllers.begin(); !(itc==controllers.end());itc++)
517         {
518                 SCA_IController* cont = (*itc);
519                 cont->SetUeberExecutePriority(m_ueberExecutionPriority);
520                 vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
521                 vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
522
523                 // disconnect the sensors and actuators
524                 cont->UnlinkAllSensors();
525                 cont->UnlinkAllActuators();
526                 
527                 // now relink each sensor
528                 for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++)
529                 {
530                         SCA_ISensor* oldsensor = (*its);
531                         STR_String name = oldsensor->GetName();
532                         //find this name in the list
533                         SCA_ISensor* newsensor = newobj->FindSensor(name);
534                 
535                         if (newsensor)
536                         {
537                                 // relink this newsensor to the controller
538                                 m_logicmgr->RegisterToSensor(cont,newsensor);
539                         }
540                         else
541                         {
542                                 // it can be linked somewhere in the hierarchy or...
543                                 for (vector<KX_GameObject*>::iterator git = m_logicHierarchicalGameObjects.begin();
544                                 !(git==m_logicHierarchicalGameObjects.end());++git)
545                                 {
546                                         newsensor = (*git)->FindSensor(name);
547                                         if (newsensor)
548                                                 break;
549                                 } 
550
551                                 if (newsensor)
552                                 {
553                                         // relink this newsensor to the controller somewhere else within this
554                                         // hierarchy
555                                         m_logicmgr->RegisterToSensor(cont,newsensor);
556                                 }
557                                 else
558                                 {
559                                         // must be an external sensor, so...
560                                         m_logicmgr->RegisterToSensor(cont,oldsensor);
561                                 }
562                         }
563                 }
564                 
565                 // now relink each actuator
566                 for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++)
567                 {
568                         SCA_IActuator* oldactuator = (*ita);
569                         STR_String name = oldactuator->GetName();
570                         //find this name in the list
571                         SCA_IActuator* newactuator = newobj->FindActuator(name);
572                         if (newactuator)
573                         {
574                                 // relink this newsensor to the controller
575                                 m_logicmgr->RegisterToActuator(cont,newactuator);
576                                 newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
577                         }
578                         else
579                         {
580                                 // it can be linked somewhere in the hierarchy or...
581                                 for (vector<KX_GameObject*>::iterator git = m_logicHierarchicalGameObjects.begin();
582                                 !(git==m_logicHierarchicalGameObjects.end());++git)
583                                 {
584                                         newactuator= (*git)->FindActuator(name);
585                                         if (newactuator)
586                                                 break;
587                                 } 
588
589                                 if (newactuator)
590                                 {
591                                         // relink this actuator to the controller somewhere else within this
592                                         // hierarchy
593                                         m_logicmgr->RegisterToActuator(cont,newactuator);
594                                         newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
595                                 }
596                                 else
597                                 {
598                                         // must be an external actuator, so...
599                                         m_logicmgr->RegisterToActuator(cont,oldactuator);
600                                 }
601                         }
602                 }
603         }
604         // ready to set initial state
605         newobj->ResetState();
606 }
607
608
609
610 SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
611                                                                                 class CValue* parentobject,
612                                                                                 int lifespan)
613 {
614
615         m_logicHierarchicalGameObjects.clear();
616         m_map_gameobject_to_replica.clear();
617
618         // todo: place a timebomb in the object, for temporarily objects :)
619         // lifespan of zero means 'this object lives forever'
620         KX_GameObject* originalobj = (KX_GameObject*) originalobject;
621         KX_GameObject* parentobj = (KX_GameObject*) parentobject;
622
623         m_ueberExecutionPriority++;
624
625         // lets create a replica
626         KX_GameObject* replica = (KX_GameObject*) AddNodeReplicaObject(NULL,originalobj);
627
628         if (lifespan > 0)
629         {
630                 // add a timebomb to this object
631                 // for now, convert between so called frames and realtime
632                 m_tempObjectList->Add(replica->AddRef());
633                 CValue *fval = new CFloatValue(lifespan*0.02);
634                 replica->SetProperty("::timebomb",fval);
635                 fval->Release();
636         }
637
638         // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
639         m_parentlist->Add(replica->AddRef());
640
641         // recurse replication into children nodes
642
643         NodeList& children = originalobj->GetSGNode()->GetSGChildren();
644
645         replica->GetSGNode()->ClearSGChildren();
646         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
647         {
648                 SG_Node* orgnode = (*childit);
649                 SG_Node* childreplicanode = orgnode->GetSGReplica();
650                 replica->GetSGNode()->AddChild(childreplicanode);
651         }
652
653         //      relink any pointers as necessary, sort of a temporary solution
654         vector<KX_GameObject*>::iterator git;
655         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
656         {
657                 (*git)->Relink(&m_map_gameobject_to_replica);
658                 // add the object in the layer of the parent
659                 (*git)->SetLayer(parentobj->GetLayer());
660         }
661
662         // now replicate logic
663         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
664         {
665                 (*git)->ReParentLogic();
666         }
667         
668         // replicate crosslinks etc. between logic bricks
669         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
670         {
671                 ReplicateLogic((*git));
672         }
673         
674         MT_Point3 newpos = ((KX_GameObject*) parentobject)->NodeGetWorldPosition();
675         replica->NodeSetLocalPosition(newpos);
676
677         MT_Matrix3x3 newori = ((KX_GameObject*) parentobject)->NodeGetWorldOrientation();
678         replica->NodeSetLocalOrientation(newori);
679         
680         // get the rootnode's scale
681         MT_Vector3 newscale = parentobj->GetSGNode()->GetRootSGParent()->GetLocalScale();
682
683         // set the replica's relative scale with the rootnode's scale
684         replica->NodeSetRelativeScale(newscale);
685
686         if (replica->GetPhysicsController())
687         {
688                 replica->GetPhysicsController()->setPosition(newpos);
689                 replica->GetPhysicsController()->setOrientation(newori.getRotation());
690                 replica->GetPhysicsController()->setScaling(newscale);
691         }
692
693         // here we want to set the relative scale: the rootnode's scale will override all other
694         // scalings, so lets better prepare for it
695
696
697         replica->GetSGNode()->UpdateWorldData(0);
698         replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
699         replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
700         //      don't release replica here because we are returning it, not done with it...
701         return replica;
702 }
703
704
705
706 void KX_Scene::RemoveObject(class CValue* gameobj)
707 {
708         KX_GameObject* newobj = (KX_GameObject*) gameobj;
709
710         // first disconnect child from parent
711         SG_Node* node = newobj->GetSGNode();
712
713         if (node)
714         {
715                 node->DisconnectFromParent();
716
717                 // recursively destruct
718                 node->Destruct();
719         }
720         //no need to do that: the object is destroyed and memory released 
721         //newobj->SetSGNode(0);
722 }
723
724 void KX_Scene::DelayedReleaseObject(CValue* gameobj)
725 {
726         m_delayReleaseObjects->Add(gameobj->AddRef());
727 }
728
729
730 void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
731 {
732         //KX_GameObject* newobj = (KX_GameObject*) gameobj;
733         if (!m_euthanasyobjects->SearchValue(gameobj))
734         {
735                 m_euthanasyobjects->Add(gameobj->AddRef());
736         } 
737 }
738
739
740
741 int KX_Scene::NewRemoveObject(class CValue* gameobj)
742 {
743         int ret;
744         KX_GameObject* newobj = (KX_GameObject*) gameobj;
745
746         //todo: look at this
747         //GetPhysicsEnvironment()->RemovePhysicsController(gameobj->getPhysicsController());
748
749         // remove all sensors/controllers/actuators from logicsystem...
750         
751         SCA_SensorList& sensors = newobj->GetSensors();
752         for (SCA_SensorList::iterator its = sensors.begin();
753                  !(its==sensors.end());its++)
754         {
755                 m_logicmgr->RemoveSensor(*its);
756         }
757         
758     SCA_ControllerList& controllers = newobj->GetControllers();
759         for (SCA_ControllerList::iterator itc = controllers.begin();
760                  !(itc==controllers.end());itc++)
761         {
762                 m_logicmgr->RemoveController(*itc);
763         }
764
765         SCA_ActuatorList& actuators = newobj->GetActuators();
766         for (SCA_ActuatorList::iterator ita = actuators.begin();
767                  !(ita==actuators.end());ita++)
768         {
769                 m_logicmgr->RemoveDestroyedActuator(*ita);
770         }
771         // the sensors/controllers/actuators must also be released, this is done in ~SCA_IObject
772
773         // now remove the timer properties from the time manager
774         int numprops = newobj->GetPropertyCount();
775
776         for (int i = 0; i < numprops; i++)
777         {
778                 CValue* propval = newobj->GetProperty(i);
779                 if (propval->GetProperty("timer"))
780                 {
781                         m_timemgr->RemoveTimeProperty(propval);
782                 }
783         }
784         
785         newobj->RemoveMeshes();
786         ret = 1;
787         if (m_objectlist->RemoveValue(newobj))
788                 ret = newobj->Release();
789         if (m_tempObjectList->RemoveValue(newobj))
790                 ret = newobj->Release();
791         if (m_parentlist->RemoveValue(newobj))
792                 ret = newobj->Release();
793         if (m_inactivelist->RemoveValue(newobj))
794                 ret = newobj->Release();
795         if (m_euthanasyobjects->RemoveValue(newobj))
796                 ret = newobj->Release();
797                 
798         if (newobj == m_active_camera)
799         {
800                 //no AddRef done on m_active_camera so no Release
801                 //m_active_camera->Release();
802                 m_active_camera = NULL;
803         }
804         // in case this is a camera
805         m_cameras.remove((KX_Camera*)newobj);
806
807         if (m_sceneConverter)
808                 m_sceneConverter->UnregisterGameObject(newobj);
809         // return value will be 0 if the object is actually deleted (all reference gone)
810         return ret;
811 }
812
813
814
815 void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj)
816 {
817         KX_GameObject* gameobj = static_cast<KX_GameObject*>(obj);
818         RAS_MeshObject* mesh = static_cast<RAS_MeshObject*>(meshobj);
819
820         if(!gameobj || !mesh)
821         {
822                 std::cout << "warning: invalid object, mesh will not be replaced" << std::endl;
823                 return;
824         }
825
826         gameobj->RemoveMeshes();
827         gameobj->AddMesh(mesh);
828         
829         if (gameobj->m_isDeformable)
830         {
831                 BL_DeformableGameObject* newobj = static_cast<BL_DeformableGameObject*>( gameobj );
832                 
833                 if (newobj->m_pDeformer)
834                 {
835                         delete newobj->m_pDeformer;
836                         newobj->m_pDeformer = NULL;
837                 }
838
839                 if (mesh->m_class == 1) 
840                 {
841                         // we must create a new deformer but which one?
842                         KX_GameObject* parentobj = newobj->GetParent();
843                         // this always return the original game object (also for replicate)
844                         Object* blendobj = newobj->GetBlenderObject();
845                         // object that owns the new mesh
846                         Object* oldblendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameMeshName(mesh->GetName()));
847                         Mesh* blendmesh = mesh->GetMesh();
848
849                         bool bHasShapeKey = blendmesh->key != NULL && blendmesh->key->type==KEY_RELATIVE;
850                         bool bHasDvert = blendmesh->dvert != NULL;
851                         bool bHasArmature = 
852                                 parentobj &&                                                            // current parent is armature
853                                 parentobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE &&
854                                 oldblendobj &&                                                          // needed for mesh deform
855                                 blendobj->parent &&                                                     // original object had armature (not sure this test is needed)
856                                 blendobj->parent->type == OB_ARMATURE && 
857                                 blendobj->partype==PARSKEL && 
858                                 blendmesh->dvert!=NULL;                                         // mesh has vertex group
859                         bool releaseParent = true;
860
861                         if (bHasShapeKey)
862                         {
863                                 BL_ShapeDeformer* shapeDeformer;
864                                 if (bHasArmature) 
865                                 {
866                                         shapeDeformer = new BL_ShapeDeformer(
867                                                 newobj,
868                                                 oldblendobj, blendobj,
869                                                 static_cast<BL_SkinMeshObject*>(mesh),
870                                                 true,
871                                                 static_cast<BL_ArmatureObject*>( parentobj )
872                                         );
873                                         releaseParent= false;
874                                         shapeDeformer->LoadShapeDrivers(blendobj->parent);
875                                 }
876                                 else
877                                 {
878                                         shapeDeformer = new BL_ShapeDeformer(
879                                                 newobj,
880                                                 oldblendobj, blendobj,
881                                                 static_cast<BL_SkinMeshObject*>(mesh),
882                                                 false,
883                                                 NULL
884                                         );
885                                 }
886                                 newobj->m_pDeformer = shapeDeformer;
887                         }
888                         else if (bHasArmature) 
889                         {
890                                 BL_SkinDeformer* skinDeformer = new BL_SkinDeformer(
891                                         newobj,
892                                         oldblendobj, blendobj,
893                                         static_cast<BL_SkinMeshObject*>(mesh),
894                                         true,
895                                         static_cast<BL_ArmatureObject*>( parentobj )
896                                 );
897                                 releaseParent= false;
898                                 newobj->m_pDeformer = skinDeformer;
899                         }
900                         else if (bHasDvert)
901                         {
902                                 BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
903                                         newobj, oldblendobj, static_cast<BL_SkinMeshObject*>(mesh)
904                                 );
905                                 newobj->m_pDeformer = meshdeformer;
906                         }
907
908                         // release parent reference if its not being used 
909                         if( releaseParent && parentobj)
910                                 parentobj->Release();
911                 }
912         }
913         gameobj->Bucketize();
914 }
915
916
917
918 MT_CmMatrix4x4& KX_Scene::GetViewMatrix()
919 {
920         MT_Scalar cammat[16];
921         m_active_camera->GetWorldToCamera().getValue(cammat);
922         m_viewmat = cammat;
923         return m_viewmat;
924 }
925
926
927
928 MT_CmMatrix4x4& KX_Scene::GetProjectionMatrix()
929 {
930         return m_projectionmat;
931 }
932
933
934 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
935 {
936         list<KX_Camera*>::iterator it = m_cameras.begin();
937
938         while ( (it != m_cameras.end()) 
939                         && ((*it) != cam) ) {
940           it++;
941         }
942
943         return ((it == m_cameras.end()) ? NULL : (*it));
944 }
945
946
947 KX_Camera* KX_Scene::FindCamera(STR_String& name)
948 {
949         list<KX_Camera*>::iterator it = m_cameras.begin();
950
951         while ( (it != m_cameras.end()) 
952                         && ((*it)->GetName() != name) ) {
953           it++;
954         }
955
956         return ((it == m_cameras.end()) ? NULL : (*it));
957 }
958
959 void KX_Scene::AddCamera(KX_Camera* cam)
960 {
961         if (!FindCamera(cam))
962                 m_cameras.push_back(cam);
963 }
964
965
966 KX_Camera* KX_Scene::GetActiveCamera()
967 {       
968         // NULL if not defined
969         return m_active_camera;
970 }
971
972
973 void KX_Scene::SetActiveCamera(KX_Camera* cam)
974 {
975         // only set if the cam is in the active list? Or add it otherwise?
976         if (!FindCamera(cam)){
977                 AddCamera(cam);
978                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
979         } 
980
981         m_active_camera = cam;
982 }
983
984 void KX_Scene::SetCameraOnTop(KX_Camera* cam)
985 {
986         if (!FindCamera(cam)){
987                 // adding is always done at the back, so that's all that needs to be done
988                 AddCamera(cam);
989                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
990         } else {
991                 m_cameras.remove(cam);
992                 m_cameras.push_back(cam);
993         }
994 }
995
996
997 void KX_Scene::UpdateMeshTransformations()
998 {
999         // do this incrementally in the future
1000         for (int i = 0; i < m_objectlist->GetCount(); i++)
1001         {
1002                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
1003                 gameobj->GetOpenGLMatrix();
1004 //              gameobj->UpdateNonDynas();
1005         }
1006 }
1007
1008 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam, int layer)
1009 {
1010         int intersect = KX_Camera::INTERSECT;
1011         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
1012         bool visible = (gameobj && gameobj->GetVisible() && (!layer || (gameobj->GetLayer() & layer)));
1013         bool dotest = visible || node->Left() || node->Right();
1014
1015         /* If the camera is inside the box, assume intersect. */
1016         if (dotest && !node->inside( cam->NodeGetWorldPosition()))
1017         {
1018                 MT_Scalar radius = node->Radius();
1019                 MT_Point3 center = node->Center();
1020                 
1021                 intersect =  cam->SphereInsideFrustum(center, radius); 
1022                 
1023                 if (intersect == KX_Camera::INTERSECT)
1024                 {
1025                         MT_Point3 box[8];
1026                         node->get(box);
1027                         intersect = cam->BoxInsideFrustum(box);
1028                 }
1029         }
1030
1031         switch (intersect)
1032         {
1033                 case KX_Camera::OUTSIDE:
1034                         MarkSubTreeVisible(node, rasty, false, cam);
1035                         break;
1036                 case KX_Camera::INTERSECT:
1037                         if (gameobj)
1038                                 MarkVisible(rasty, gameobj, cam, layer);
1039                         if (node->Left())
1040                                 MarkVisible(node->Left(), rasty, cam, layer);
1041                         if (node->Right())
1042                                 MarkVisible(node->Right(), rasty, cam, layer);
1043                         break;
1044                 case KX_Camera::INSIDE:
1045                         MarkSubTreeVisible(node, rasty, true, cam, layer);
1046                         break;
1047         }
1048 }
1049
1050 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera* cam, int layer)
1051 {
1052         if (node->Client())
1053         {
1054                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
1055                 if (gameobj->GetVisible())
1056                 {
1057                         if (visible)
1058                         {
1059                                 int nummeshes = gameobj->GetMeshCount();
1060                                 MT_Transform t( cam->GetWorldToCamera() * gameobj->GetSGNode()->GetWorldTransform());
1061         
1062                                 
1063                                 for (int m=0;m<nummeshes;m++)
1064                                 {
1065                                         // this adds the vertices to the display list
1066                                         (gameobj->GetMesh(m))->SchedulePolygons(t, rasty->GetDrawingMode());
1067                                 }
1068                         }
1069                         gameobj->MarkVisible(visible);
1070                 }
1071         }
1072         if (node->Left())
1073                 MarkSubTreeVisible(node->Left(), rasty, visible, cam, layer);
1074         if (node->Right())
1075                 MarkSubTreeVisible(node->Right(), rasty, visible, cam, layer);
1076 }
1077
1078 void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera*  cam,int layer)
1079 {
1080         // User (Python/Actuator) has forced object invisible...
1081         if (!gameobj->GetVisible())
1082                 return;
1083         
1084         // Shadow lamp layers
1085         if(layer && !(gameobj->GetLayer() & layer)) {
1086                 gameobj->MarkVisible(false);
1087                 return;
1088         }
1089
1090         // If Frustum culling is off, the object is always visible.
1091         bool vis = !cam->GetFrustumCulling();
1092         
1093         // If the camera is inside this node, then the object is visible.
1094         if (!vis)
1095         {
1096                 vis = gameobj->GetSGNode()->inside( GetActiveCamera()->GetCameraLocation() );
1097         }
1098                 
1099         // Test the object's bound sphere against the view frustum.
1100         if (!vis)
1101         {
1102                 MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
1103                 MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
1104                 switch (cam->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
1105                 {
1106                         case KX_Camera::INSIDE:
1107                                 vis = true;
1108                                 break;
1109                         case KX_Camera::OUTSIDE:
1110                                 vis = false;
1111                                 break;
1112                         case KX_Camera::INTERSECT:
1113                                 // Test the object's bound box against the view frustum.
1114                                 MT_Point3 box[8];
1115                                 gameobj->GetSGNode()->getBBox(box); 
1116                                 vis = cam->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
1117                                 break;
1118                 }
1119         }
1120         
1121         if (vis)
1122         {
1123                 int nummeshes = gameobj->GetMeshCount();
1124                 MT_Transform t(cam->GetWorldToCamera() * gameobj->GetSGNode()->GetWorldTransform());
1125                 
1126                 for (int m=0;m<nummeshes;m++)
1127                 {
1128                         // this adds the vertices to the display list
1129                         (gameobj->GetMesh(m))->SchedulePolygons(t, rasty->GetDrawingMode());
1130                 }
1131                 // Visibility/ non-visibility are marked
1132                 // elsewhere now.
1133                 gameobj->MarkVisible();
1134         } else {
1135                 gameobj->MarkVisible(false);
1136         }
1137 }
1138
1139 void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam, int layer)
1140 {
1141 // FIXME: When tree is operational
1142 #if 1
1143         // do this incrementally in the future
1144         for (int i = 0; i < m_objectlist->GetCount(); i++)
1145         {
1146                 MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)), cam, layer);
1147         }
1148 #else
1149         if (cam->GetFrustumCulling())
1150                 MarkVisible(m_objecttree, rasty, cam, layer);
1151         else
1152                 MarkSubTreeVisible(m_objecttree, rasty, true, cam, layer);
1153 #endif
1154 }
1155
1156 // logic stuff
1157 void KX_Scene::LogicBeginFrame(double curtime)
1158 {
1159         // have a look at temp objects ...
1160         int lastobj = m_tempObjectList->GetCount() - 1;
1161         
1162         for (int i = lastobj; i >= 0; i--)
1163         {
1164                 CValue* objval = m_tempObjectList->GetValue(i);
1165                 CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
1166                 
1167                 if (propval)
1168                 {
1169                         float timeleft = propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate();
1170                         
1171                         if (timeleft > 0)
1172                         {
1173                                 propval->SetFloat(timeleft);
1174                         }
1175                         else
1176                         {
1177                                 DelayedRemoveObject(objval);
1178                                 // remove obj
1179                         }
1180                 }
1181                 else
1182                 {
1183                         // all object is the tempObjectList should have a clock
1184                 }
1185         }
1186         m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate());
1187 }
1188
1189
1190
1191 void KX_Scene::LogicUpdateFrame(double curtime, bool frame)
1192 {
1193         m_logicmgr->UpdateFrame(curtime, frame);
1194 }
1195
1196
1197
1198 void KX_Scene::LogicEndFrame()
1199 {
1200         m_logicmgr->EndFrame();
1201         int numobj = m_euthanasyobjects->GetCount();
1202         int i;
1203         for (i = numobj - 1; i >= 0; i--)
1204         {
1205                 KX_GameObject* gameobj = (KX_GameObject*)m_euthanasyobjects->GetValue(i);
1206                 // KX_Scene::RemoveObject will also remove the object from this list
1207                 // that's why we start from the end
1208                 this->RemoveObject(gameobj);
1209         }
1210
1211         numobj= m_delayReleaseObjects->GetCount();
1212         for (i = numobj-1;i>=0;i--)
1213         {
1214                 KX_GameObject* gameobj = (KX_GameObject*)m_delayReleaseObjects->GetValue(i);
1215                 // This list is not for object removal, but just object release
1216                 gameobj->Release();
1217         }
1218         // empty the list as we have removed all references
1219         m_delayReleaseObjects->Resize(0);       
1220 }
1221
1222
1223
1224 /**
1225   * UpdateParents: SceneGraph transformation update.
1226   */
1227 void KX_Scene::UpdateParents(double curtime)
1228 {
1229 //      int numrootobjects = GetRootParentList()->GetCount();
1230
1231         for (int i=0; i<GetRootParentList()->GetCount(); i++)
1232         {
1233                 KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
1234                 parentobj->NodeUpdateGS(curtime,true);
1235         }
1236 }
1237
1238
1239
1240 RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat, bool &bucketCreated)
1241 {
1242         return m_bucketmanager->RAS_BucketManagerFindBucket(polymat, bucketCreated);
1243 }
1244
1245
1246
1247 void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
1248                                                          class RAS_IRasterizer* rasty,
1249                                                          class RAS_IRenderTools* rendertools)
1250 {
1251         m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
1252 }
1253
1254
1255
1256 void KX_Scene::UpdateObjectActivity(void) 
1257 {
1258         if (m_activity_culling) {
1259                 /* determine the activity criterium and set objects accordingly */
1260                 int i=0;
1261                 
1262                 MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
1263                 
1264                 for (i=0;i<GetObjectList()->GetCount();i++)
1265                 {
1266                         KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
1267                         
1268                         if (!ob->GetIgnoreActivityCulling()) {
1269                                 /* Simple test: more than 10 away from the camera, count
1270                                  * Manhattan distance. */
1271                                 MT_Point3 obpos = ob->NodeGetWorldPosition();
1272                                 
1273                                 if ( (fabs(camloc[0] - obpos[0]) > m_activity_box_radius)
1274                                          || (fabs(camloc[1] - obpos[1]) > m_activity_box_radius)
1275                                          || (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
1276                                 {                       
1277                                         ob->Suspend();
1278                                 } else {
1279                                         ob->Resume();
1280                                 }
1281                         }
1282                 }               
1283         }
1284 }
1285
1286 void KX_Scene::SetActivityCullingRadius(float f)
1287 {
1288         if (f < 0.5)
1289                 f = 0.5;
1290         m_activity_box_radius = f;
1291 }
1292         
1293 NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
1294 {
1295         return m_networkDeviceInterface;
1296 }
1297
1298 NG_NetworkScene* KX_Scene::GetNetworkScene()
1299 {
1300         return m_networkScene;
1301 }
1302
1303 void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
1304 {
1305         m_networkDeviceInterface = newInterface;
1306 }
1307
1308 void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
1309 {
1310         m_networkScene = newScene;
1311 }
1312
1313
1314 void    KX_Scene::SetGravity(const MT_Vector3& gravity)
1315 {
1316         GetPhysicsEnvironment()->setGravity(gravity[0],gravity[1],gravity[2]);
1317 }
1318
1319 void KX_Scene::SetNodeTree(SG_Tree* root)
1320 {
1321         m_objecttree = root;
1322 }
1323
1324 void KX_Scene::SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter)
1325 {
1326         m_sceneConverter = sceneConverter;
1327 }
1328
1329 void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
1330 {
1331         m_physicsEnvironment = physEnv;
1332
1333         KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, physEnv);
1334         m_logicmgr->RegisterEventManager(touchmgr);
1335         return;
1336 }
1337  
1338 void KX_Scene::setSuspendedTime(double suspendedtime)
1339 {
1340         m_suspendedtime = suspendedtime;
1341 }
1342 double KX_Scene::getSuspendedTime()
1343 {
1344         return m_suspendedtime;
1345 }
1346 void KX_Scene::setSuspendedDelta(double suspendeddelta)
1347 {
1348         m_suspendeddelta = suspendeddelta;
1349 }
1350 double KX_Scene::getSuspendedDelta()
1351 {
1352         return m_suspendeddelta;
1353 }
1354
1355 //----------------------------------------------------------------------------
1356 //Python
1357
1358 PyMethodDef KX_Scene::Methods[] = {
1359         KX_PYMETHODTABLE(KX_Scene, getLightList),
1360         KX_PYMETHODTABLE(KX_Scene, getObjectList),
1361         KX_PYMETHODTABLE(KX_Scene, getName),
1362         
1363         {NULL,NULL} //Sentinel
1364 };
1365
1366 PyTypeObject KX_Scene::Type = {
1367         PyObject_HEAD_INIT(&PyType_Type)
1368                 0,
1369                 "KX_Scene",
1370                 sizeof(KX_Scene),
1371                 0,
1372                 PyDestructor,
1373                 0,
1374                 __getattr,
1375                 __setattr,
1376                 0, //&MyPyCompare,
1377                 __repr,
1378                 0, //&cvalue_as_number,
1379                 0,
1380                 0,
1381                 0,
1382                 0, 0, 0, 0, 0, 0
1383 };
1384
1385 PyParentObject KX_Scene::Parents[] = {
1386         &KX_Scene::Type,
1387                 &CValue::Type,
1388                 NULL
1389 };
1390
1391 PyObject* KX_Scene::_getattr(const STR_String& attr)
1392 {
1393         if (attr == "name")
1394                 return PyString_FromString(GetName());
1395         
1396         if (attr == "active_camera")
1397         {
1398                 KX_Camera *camera = GetActiveCamera();
1399                 camera->AddRef();
1400                 return (PyObject*) camera;
1401         }
1402         
1403         if (attr == "suspended")
1404                 return PyInt_FromLong(m_suspend);
1405         
1406         if (attr == "activity_culling")
1407                 return PyInt_FromLong(m_activity_culling);
1408         
1409         if (attr == "activity_culling_radius")
1410                 return PyFloat_FromDouble(m_activity_box_radius);
1411         
1412         PyObject* value = PyDict_GetItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()));
1413         if (value)
1414         {
1415                 Py_INCREF(value);
1416                 return value;
1417         }
1418         
1419         _getattr_up(PyObjectPlus);
1420 }
1421
1422 int KX_Scene::_delattr(const STR_String &attr)
1423 {
1424         PyDict_DelItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()));
1425         return 0;
1426 }
1427
1428 int KX_Scene::_setattr(const STR_String &attr, PyObject *pyvalue)
1429 {
1430
1431         if (!PyDict_SetItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()), pyvalue))
1432                 return 0;
1433
1434         return PyObjectPlus::_setattr(attr, pyvalue);
1435 }
1436
1437 KX_PYMETHODDEF_DOC(KX_Scene, getLightList,
1438 "getLightList() -> list [KX_Light]\n"
1439 "Returns a list of all lights in the scene.\n"
1440 )
1441 {
1442         m_lightlist->AddRef();
1443         return (PyObject*) m_lightlist;
1444 }
1445
1446 KX_PYMETHODDEF_DOC(KX_Scene, getObjectList,
1447 "getObjectList() -> list [KX_GameObject]\n"
1448 "Returns a list of all game objects in the scene.\n"
1449 )
1450 {
1451         m_objectlist->AddRef();
1452         return (PyObject*) m_objectlist;
1453 }
1454
1455 KX_PYMETHODDEF_DOC(KX_Scene, getName,
1456 "getName() -> string\n"
1457 "Returns the name of the scene.\n"
1458 )
1459 {
1460         return PyString_FromString(GetName());
1461 }