BGE : Standardization of callbacks execution.
[blender.git] / source / gameengine / Ketsji / KX_Scene.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  * Ketsji scene. Holds references to all scene data.
27  */
28
29 /** \file gameengine/Ketsji/KX_Scene.cpp
30  *  \ingroup ketsji
31  */
32
33
34 #ifdef _MSC_VER
35 #  pragma warning (disable:4786)
36 #endif
37
38 #include "KX_Scene.h"
39 #include "KX_PythonInit.h"
40 #include "MT_assert.h"
41 #include "KX_KetsjiEngine.h"
42 #include "KX_BlenderMaterial.h"
43 #include "KX_FontObject.h"
44 #include "RAS_IPolygonMaterial.h"
45 #include "ListValue.h"
46 #include "KX_PythonCallBack.h"
47 #include "SCA_LogicManager.h"
48 #include "SCA_TimeEventManager.h"
49 //#include "SCA_AlwaysEventManager.h"
50 //#include "SCA_RandomEventManager.h"
51 //#include "KX_RayEventManager.h"
52 #include "SCA_2DFilterActuator.h"
53 #include "SCA_PythonController.h"
54 #include "KX_TouchEventManager.h"
55 #include "SCA_KeyboardManager.h"
56 #include "SCA_MouseManager.h"
57 //#include "SCA_PropertyEventManager.h"
58 #include "SCA_ActuatorEventManager.h"
59 #include "SCA_BasicEventManager.h"
60 #include "KX_Camera.h"
61 #include "SCA_JoystickManager.h"
62 #include "KX_PyMath.h"
63 #include "RAS_MeshObject.h"
64 #include "SCA_IScene.h"
65
66 #include "RAS_IRasterizer.h"
67 #include "RAS_ICanvas.h"
68 #include "RAS_BucketManager.h"
69
70 #include "FloatValue.h"
71 #include "SCA_IController.h"
72 #include "SCA_IActuator.h"
73 #include "SG_Node.h"
74 #include "BL_System.h"
75 #include "SG_Controller.h"
76 #include "SG_IObject.h"
77 #include "SG_Tree.h"
78 #include "DNA_group_types.h"
79 #include "DNA_scene_types.h"
80 #include "DNA_property_types.h"
81
82 #include "KX_SG_NodeRelationships.h"
83
84 #include "KX_NetworkEventManager.h"
85 #include "NG_NetworkScene.h"
86 #include "PHY_IPhysicsEnvironment.h"
87 #include "PHY_IGraphicController.h"
88 #include "PHY_IPhysicsController.h"
89 #include "KX_BlenderSceneConverter.h"
90 #include "KX_MotionState.h"
91
92 #include "BL_ModifierDeformer.h"
93 #include "BL_ShapeDeformer.h"
94 #include "BL_DeformableGameObject.h"
95 #include "KX_ObstacleSimulation.h"
96
97 #ifdef WITH_BULLET
98 #include "KX_SoftBodyDeformer.h"
99 #endif
100
101 #include "KX_Light.h"
102
103 #include <stdio.h>
104
105 #include "BLI_task.h"
106
107 static void *KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
108 {
109         KX_GameObject* replica = ((KX_Scene*)scene)->AddNodeReplicaObject(node,(KX_GameObject*)gameobj);
110
111         if (replica)
112                 replica->Release();
113
114         return (void*)replica;
115 }
116
117 static void *KX_SceneDestructionFunc(SG_IObject* node,void* gameobj,void* scene)
118 {
119         ((KX_Scene*)scene)->RemoveNodeDestructObject(node,(KX_GameObject*)gameobj);
120
121         return NULL;
122 };
123
124 bool KX_Scene::KX_ScenegraphUpdateFunc(SG_IObject* node,void* gameobj,void* scene)
125 {
126         return ((SG_Node*)node)->Schedule(((KX_Scene*)scene)->m_sghead);
127 }
128
129 bool KX_Scene::KX_ScenegraphRescheduleFunc(SG_IObject* node,void* gameobj,void* scene)
130 {
131         return ((SG_Node*)node)->Reschedule(((KX_Scene*)scene)->m_sghead);
132 }
133
134 SG_Callbacks KX_Scene::m_callbacks = SG_Callbacks(
135         KX_SceneReplicationFunc,
136         KX_SceneDestructionFunc,
137         KX_GameObject::UpdateTransformFunc,
138         KX_Scene::KX_ScenegraphUpdateFunc,
139         KX_Scene::KX_ScenegraphRescheduleFunc);
140
141 // temporarily var until there is a button in the userinterface
142 // (defined in KX_PythonInit.cpp)
143 extern bool gUseVisibilityTemp;
144
145 KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
146                                    class SCA_IInputDevice* mousedevice,
147                                    class NG_NetworkDeviceInterface *ndi,
148                                    const STR_String& sceneName,
149                                    Scene *scene,
150                                    class RAS_ICanvas* canvas): 
151         PyObjectPlus(),
152         m_keyboardmgr(NULL),
153         m_mousemgr(NULL),
154         m_sceneConverter(NULL),
155         m_physicsEnvironment(0),
156         m_sceneName(sceneName),
157         m_networkDeviceInterface(ndi),
158         m_active_camera(NULL),
159         m_ueberExecutionPriority(0),
160         m_blenderScene(scene),
161         m_isActivedHysteresis(false),
162         m_lodHysteresisValue(0)
163 {
164         m_suspendedtime = 0.0;
165         m_suspendeddelta = 0.0;
166
167         m_dbvt_culling = false;
168         m_dbvt_occlusion_res = 0;
169         m_activity_culling = false;
170         m_suspend = false;
171         m_isclearingZbuffer = true;
172         m_tempObjectList = new CListValue();
173         m_objectlist = new CListValue();
174         m_parentlist = new CListValue();
175         m_lightlist= new CListValue();
176         m_inactivelist = new CListValue();
177         m_euthanasyobjects = new CListValue();
178         m_animatedlist = new CListValue();
179
180         m_logicmgr = new SCA_LogicManager();
181         
182         m_timemgr = new SCA_TimeEventManager(m_logicmgr);
183         m_keyboardmgr = new SCA_KeyboardManager(m_logicmgr,keyboarddevice);
184         m_mousemgr = new SCA_MouseManager(m_logicmgr,mousedevice, canvas);
185         
186         //SCA_AlwaysEventManager* alwaysmgr = new SCA_AlwaysEventManager(m_logicmgr);
187         //SCA_PropertyEventManager* propmgr = new SCA_PropertyEventManager(m_logicmgr);
188         SCA_ActuatorEventManager* actmgr = new SCA_ActuatorEventManager(m_logicmgr);
189         //SCA_RandomEventManager* rndmgr = new SCA_RandomEventManager(m_logicmgr);
190         SCA_BasicEventManager* basicmgr = new SCA_BasicEventManager(m_logicmgr);
191         //KX_RayEventManager* raymgr = new KX_RayEventManager(m_logicmgr);
192
193         KX_NetworkEventManager* netmgr = new KX_NetworkEventManager(m_logicmgr, ndi);
194         
195         
196
197         //m_logicmgr->RegisterEventManager(alwaysmgr);
198         //m_logicmgr->RegisterEventManager(propmgr);
199         m_logicmgr->RegisterEventManager(actmgr);
200         m_logicmgr->RegisterEventManager(m_keyboardmgr);
201         m_logicmgr->RegisterEventManager(m_mousemgr);
202         m_logicmgr->RegisterEventManager(m_timemgr);
203         //m_logicmgr->RegisterEventManager(rndmgr);
204         //m_logicmgr->RegisterEventManager(raymgr);
205         m_logicmgr->RegisterEventManager(netmgr);
206         m_logicmgr->RegisterEventManager(basicmgr);
207
208
209         SYS_SystemHandle hSystem = SYS_GetSystem();
210         bool nojoystick= SYS_GetCommandLineInt(hSystem,"nojoystick",0);
211         if (!nojoystick)
212         {
213                 SCA_JoystickManager *joymgr     = new SCA_JoystickManager(m_logicmgr);
214                 m_logicmgr->RegisterEventManager(joymgr);
215         }
216
217         MT_assert (m_networkDeviceInterface != NULL);
218         m_networkScene = new NG_NetworkScene(m_networkDeviceInterface);
219         
220         m_rootnode = NULL;
221
222         m_bucketmanager=new RAS_BucketManager();
223         
224         bool showObstacleSimulation = (scene->gm.flag & GAME_SHOW_OBSTACLE_SIMULATION) != 0;
225         switch (scene->gm.obstacleSimulation)
226         {
227         case OBSTSIMULATION_TOI_rays:
228                 m_obstacleSimulation = new KX_ObstacleSimulationTOI_rays((MT_Scalar)scene->gm.levelHeight, showObstacleSimulation);
229                 break;
230         case OBSTSIMULATION_TOI_cells:
231                 m_obstacleSimulation = new KX_ObstacleSimulationTOI_cells((MT_Scalar)scene->gm.levelHeight, showObstacleSimulation);
232                 break;
233         default:
234                 m_obstacleSimulation = NULL;
235         }
236         
237 #ifdef WITH_PYTHON
238         m_attr_dict = NULL;
239         m_draw_call_pre = NULL;
240         m_draw_call_post = NULL;
241 #endif
242 }
243
244
245
246 KX_Scene::~KX_Scene()
247 {
248         // The release of debug properties used to be in SCA_IScene::~SCA_IScene
249         // It's still there but we remove all properties here otherwise some
250         // reference might be hanging and causing late release of objects
251         RemoveAllDebugProperties();
252
253         while (GetRootParentList()->GetCount() > 0) 
254         {
255                 KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(0);
256                 this->RemoveObject(parentobj);
257         }
258
259         if (m_obstacleSimulation)
260                 delete m_obstacleSimulation;
261
262         if (m_objectlist)
263                 m_objectlist->Release();
264
265         if (m_parentlist)
266                 m_parentlist->Release();
267         
268         if (m_inactivelist)
269                 m_inactivelist->Release();
270
271         if (m_lightlist)
272                 m_lightlist->Release();
273         
274         if (m_tempObjectList)
275                 m_tempObjectList->Release();
276
277         if (m_euthanasyobjects)
278                 m_euthanasyobjects->Release();
279
280         if (m_animatedlist)
281                 m_animatedlist->Release();
282
283         if (m_logicmgr)
284                 delete m_logicmgr;
285
286         if (m_physicsEnvironment)
287                 delete m_physicsEnvironment;
288
289         if (m_networkScene)
290                 delete m_networkScene;
291         
292         if (m_bucketmanager)
293         {
294                 delete m_bucketmanager;
295         }
296
297 #ifdef WITH_PYTHON
298         if (m_attr_dict) {
299                 PyDict_Clear(m_attr_dict);
300                 /* Py_CLEAR: Py_DECREF's and NULL's */
301                 Py_CLEAR(m_attr_dict);
302         }
303
304         /* these may be NULL but the macro checks */
305         Py_CLEAR(m_draw_call_pre);
306         Py_CLEAR(m_draw_call_post);
307 #endif
308 }
309
310 RAS_BucketManager* KX_Scene::GetBucketManager()
311 {
312         return m_bucketmanager;
313 }
314
315
316 CListValue* KX_Scene::GetTempObjectList()
317 {
318         return m_tempObjectList;
319 }
320
321 CListValue* KX_Scene::GetObjectList()
322 {
323         return m_objectlist;
324 }
325
326
327 CListValue* KX_Scene::GetRootParentList()
328 {
329         return m_parentlist;
330 }
331
332 CListValue* KX_Scene::GetInactiveList()
333 {
334         return m_inactivelist;
335 }
336
337
338
339 CListValue* KX_Scene::GetLightList()
340 {
341         return m_lightlist;
342 }
343
344 SCA_LogicManager* KX_Scene::GetLogicManager()
345 {
346         return m_logicmgr;
347 }
348
349 SCA_TimeEventManager* KX_Scene::GetTimeEventManager()
350 {
351         return m_timemgr;
352 }
353
354
355
356  
357 list<class KX_Camera*>* KX_Scene::GetCameras()
358 {
359         return &m_cameras;
360 }
361
362 void KX_Scene::SetFramingType(RAS_FrameSettings & frame_settings)
363 {
364         m_frame_settings = frame_settings;
365 };
366
367 /**
368  * Return a const reference to the framing 
369  * type set by the above call.
370  * The contents are not guaranteed to be sensible
371  * if you don't call the above function.
372  */
373 const RAS_FrameSettings& KX_Scene::GetFramingType() const 
374 {
375         return m_frame_settings;
376 };
377
378
379
380 /**
381  * Store the current scene's viewport on the 
382  * game engine canvas.
383  */
384 void KX_Scene::SetSceneViewport(const RAS_Rect &viewport)
385 {
386         m_viewport = viewport;
387 }
388
389
390
391 const RAS_Rect& KX_Scene::GetSceneViewport() const 
392 {
393         return m_viewport;
394 }
395
396
397
398 void KX_Scene::SetWorldInfo(class KX_WorldInfo* worldinfo)
399 {
400         m_worldinfo = worldinfo;
401 }
402
403
404
405 class KX_WorldInfo* KX_Scene::GetWorldInfo()
406 {
407         return m_worldinfo;
408 }
409
410
411 const STR_String& KX_Scene::GetName()
412 {
413         return m_sceneName;
414 }
415
416
417 void KX_Scene::Suspend()
418 {
419         m_suspend = true;
420 }
421
422 void KX_Scene::Resume()
423 {
424         m_suspend = false;
425 }
426
427 void KX_Scene::SetActivityCulling(bool b)
428 {
429         m_activity_culling = b;
430 }
431
432 bool KX_Scene::IsSuspended()
433 {
434         return m_suspend;
435 }
436
437 bool KX_Scene::IsClearingZBuffer()
438 {
439         return m_isclearingZbuffer;
440 }
441
442 void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer)
443 {
444         m_isclearingZbuffer = isclearingZbuffer;
445 }
446
447 void KX_Scene::AddObjectDebugProperties(class KX_GameObject* gameobj)
448 {
449         Object* blenderobject = gameobj->GetBlenderObject();
450         bProperty* prop = (bProperty*)blenderobject->prop.first;
451
452         while (prop) {
453                 if (prop->flag & PROP_DEBUG)
454                         AddDebugProperty(gameobj,STR_String(prop->name));
455                 prop = prop->next;
456         }       
457
458         if (blenderobject->scaflag & OB_DEBUGSTATE)
459                 AddDebugProperty(gameobj,STR_String("__state__"));
460 }
461
462 void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj)
463 {
464         KX_GameObject* orgobj = (KX_GameObject*)gameobj;
465         if (NewRemoveObject(orgobj) != 0)
466         {
467                 // object is not yet deleted because a reference is hanging somewhere.
468                 // This should not happen anymore since we use proxy object for Python
469                 // confident enough to put an assert?
470                 //assert(false);
471                 printf("Zombie object! name=%s\n", orgobj->GetName().ReadPtr());
472                 orgobj->SetSGNode(NULL);
473                 PHY_IGraphicController* ctrl = orgobj->GetGraphicController();
474                 if (ctrl)
475                 {
476                         // a graphic controller is set, we must delete it as the node will be deleted
477                         delete ctrl;
478                         orgobj->SetGraphicController(NULL);
479                 }
480         }
481         if (node)
482                 delete node;
483 }
484
485 KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CValue* gameobj)
486 {
487         // for group duplication, limit the duplication of the hierarchy to the
488         // objects that are part of the group. 
489         if (!IsObjectInGroup(gameobj))
490                 return NULL;
491         
492         KX_GameObject* orgobj = (KX_GameObject*)gameobj;
493         KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica();
494         m_map_gameobject_to_replica.insert(orgobj, newobj);
495
496         // also register 'timers' (time properties) of the replica
497         int numprops = newobj->GetPropertyCount();
498
499         for (int i = 0; i < numprops; i++)
500         {
501                 CValue* prop = newobj->GetProperty(i);
502
503                 if (prop->GetProperty("timer"))
504                         this->m_timemgr->AddTimeProperty(prop);
505         }
506
507         if (node)
508         {
509                 newobj->SetSGNode((SG_Node*)node);
510         }
511         else
512         {
513                 m_rootnode = new SG_Node(newobj,this,KX_Scene::m_callbacks);
514         
515                 // this fixes part of the scaling-added object bug
516                 SG_Node* orgnode = orgobj->GetSGNode();
517                 m_rootnode->SetLocalScale(orgnode->GetLocalScale());
518                 m_rootnode->SetLocalPosition(orgnode->GetLocalPosition());
519                 m_rootnode->SetLocalOrientation(orgnode->GetLocalOrientation());
520
521                 // define the relationship between this node and it's parent.
522                 KX_NormalParentRelation * parent_relation = 
523                         KX_NormalParentRelation::New();
524                 m_rootnode->SetParentRelation(parent_relation);
525
526                 newobj->SetSGNode(m_rootnode);
527         }
528         
529         SG_IObject* replicanode = newobj->GetSGNode();
530 //      SG_Node* rootnode = (replicanode == m_rootnode ? NULL : m_rootnode);
531
532         replicanode->SetSGClientObject(newobj);
533
534         // this is the list of object that are send to the graphics pipeline
535         m_objectlist->Add(newobj->AddRef());
536         if (newobj->GetGameObjectType()==SCA_IObject::OBJ_LIGHT)
537                 m_lightlist->Add(newobj->AddRef());
538         else if (newobj->GetGameObjectType()==SCA_IObject::OBJ_TEXT)
539                 AddFont((KX_FontObject*)newobj);
540         newobj->AddMeshUser();
541
542         // logic cannot be replicated, until the whole hierarchy is replicated.
543         m_logicHierarchicalGameObjects.push_back(newobj);
544         //replicate controllers of this node
545         SGControllerList        scenegraphcontrollers = orgobj->GetSGNode()->GetSGControllerList();
546         replicanode->RemoveAllControllers();
547         SGControllerList::iterator cit;
548         //int numcont = scenegraphcontrollers.size();
549         
550         for (cit = scenegraphcontrollers.begin();!(cit==scenegraphcontrollers.end());++cit)
551         {
552                 // controller replication is quite complicated
553                 // only replicate ipo controller for now
554
555                 SG_Controller* replicacontroller = (*cit)->GetReplica((SG_Node*) replicanode);
556                 if (replicacontroller)
557                 {
558                         replicacontroller->SetObject(replicanode);
559                         replicanode->AddSGController(replicacontroller);
560                 }
561         }
562         // replicate graphic controller
563         if (orgobj->GetGraphicController())
564         {
565                 PHY_IMotionState* motionstate = new KX_MotionState(newobj->GetSGNode());
566                 PHY_IGraphicController* newctrl = orgobj->GetGraphicController()->GetReplica(motionstate);
567                 newctrl->SetNewClientInfo(newobj->getClientInfo());
568                 newobj->SetGraphicController(newctrl);
569         }
570
571         // replicate physics controller
572         if (orgobj->GetPhysicsController())
573         {
574                 PHY_IMotionState* motionstate = new KX_MotionState(newobj->GetSGNode());
575                 PHY_IPhysicsController* newctrl = orgobj->GetPhysicsController()->GetReplica();
576
577                 KX_GameObject *parent = newobj->GetParent();
578                 PHY_IPhysicsController* parentctrl = (parent) ? parent->GetPhysicsController() : NULL;
579
580                 newctrl->SetNewClientInfo(newobj->getClientInfo());
581                 newobj->SetPhysicsController(newctrl, newobj->IsDynamic());
582                 newctrl->PostProcessReplica(motionstate, parentctrl);
583         }
584
585         return newobj;
586 }
587
588
589
590 // before calling this method KX_Scene::ReplicateLogic(), make sure to
591 // have called 'GameObject::ReParentLogic' for each object this
592 // hierarchy that's because first ALL bricks must exist in the new
593 // replica of the hierarchy in order to make cross-links work properly
594 // !
595 // It is VERY important that the order of sensors and actuators in
596 // the replicated object is preserved: it is used to reconnect the logic.
597 // This method is more robust then using the bricks name in case of complex 
598 // group replication. The replication of logic bricks is done in 
599 // SCA_IObject::ReParentLogic(), make sure it preserves the order of the bricks.
600 void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
601 {
602         /* add properties to debug list, for added objects and DupliGroups */
603         if (KX_GetActiveEngine()->GetAutoAddDebugProperties()) {
604                 AddObjectDebugProperties(newobj);
605         }
606         // also relink the controller to sensors/actuators
607         SCA_ControllerList& controllers = newobj->GetControllers();
608         //SCA_SensorList&     sensors     = newobj->GetSensors();
609         //SCA_ActuatorList&   actuators   = newobj->GetActuators();
610
611         for (SCA_ControllerList::iterator itc = controllers.begin(); !(itc==controllers.end());itc++)
612         {
613                 SCA_IController* cont = (*itc);
614                 cont->SetUeberExecutePriority(m_ueberExecutionPriority);
615                 vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
616                 vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
617
618                 // disconnect the sensors and actuators
619                 // do it directly on the list at this controller is not connected to anything at this stage
620                 cont->GetLinkedSensors().clear();
621                 cont->GetLinkedActuators().clear();
622                 
623                 // now relink each sensor
624                 for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++)
625                 {
626                         SCA_ISensor* oldsensor = (*its);
627                         SCA_IObject* oldsensorobj = oldsensor->GetParent();
628                         SCA_IObject* newsensorobj = NULL;
629                 
630                         // the original owner of the sensor has been replicated?
631                         void **h_obj = m_map_gameobject_to_replica[oldsensorobj];
632                         if (h_obj)
633                                 newsensorobj = (SCA_IObject*)(*h_obj);
634                         if (!newsensorobj)
635                         {
636                                 // no, then the sensor points outside the hierarchy, keep it the same
637                                 if (m_objectlist->SearchValue(oldsensorobj))
638                                         // only replicate links that points to active objects
639                                         m_logicmgr->RegisterToSensor(cont,oldsensor);
640                         }
641                         else
642                         {
643                                 // yes, then the new sensor has the same position
644                                 SCA_SensorList& sensorlist = oldsensorobj->GetSensors();
645                                 SCA_SensorList::iterator sit;
646                                 SCA_ISensor* newsensor = NULL;
647                                 int sensorpos;
648
649                                 for (sensorpos=0, sit=sensorlist.begin(); sit!=sensorlist.end(); sit++, sensorpos++)
650                                 {
651                                         if ((*sit) == oldsensor) 
652                                         {
653                                                 newsensor = newsensorobj->GetSensors().at(sensorpos);
654                                                 break;
655                                         }
656                                 }
657                                 assert(newsensor != NULL);
658                                 m_logicmgr->RegisterToSensor(cont,newsensor);
659                         }
660                 }
661                 
662                 // now relink each actuator
663                 for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++)
664                 {
665                         SCA_IActuator* oldactuator = (*ita);
666                         SCA_IObject* oldactuatorobj = oldactuator->GetParent();
667                         SCA_IObject* newactuatorobj = NULL;
668
669                         // the original owner of the sensor has been replicated?
670                         void **h_obj = m_map_gameobject_to_replica[oldactuatorobj];
671                         if (h_obj)
672                                 newactuatorobj = (SCA_IObject*)(*h_obj);
673
674                         if (!newactuatorobj)
675                         {
676                                 // no, then the sensor points outside the hierarchy, keep it the same
677                                 if (m_objectlist->SearchValue(oldactuatorobj))
678                                         // only replicate links that points to active objects
679                                         m_logicmgr->RegisterToActuator(cont,oldactuator);
680                         }
681                         else
682                         {
683                                 // yes, then the new sensor has the same position
684                                 SCA_ActuatorList& actuatorlist = oldactuatorobj->GetActuators();
685                                 SCA_ActuatorList::iterator ait;
686                                 SCA_IActuator* newactuator = NULL;
687                                 int actuatorpos;
688
689                                 for (actuatorpos=0, ait=actuatorlist.begin(); ait!=actuatorlist.end(); ait++, actuatorpos++)
690                                 {
691                                         if ((*ait) == oldactuator) 
692                                         {
693                                                 newactuator = newactuatorobj->GetActuators().at(actuatorpos);
694                                                 break;
695                                         }
696                                 }
697                                 assert(newactuator != NULL);
698                                 m_logicmgr->RegisterToActuator(cont,newactuator);
699                                 newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
700                         }
701                 }
702         }
703         // ready to set initial state
704         newobj->ResetState();
705 }
706
707 void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
708 {
709         KX_GameObject* groupobj = (KX_GameObject*) obj;
710         KX_GameObject* replica;
711         KX_GameObject* gameobj;
712         Object* blgroupobj = groupobj->GetBlenderObject();
713         Group* group;
714         GroupObject *go;
715         vector<KX_GameObject*> duplilist;
716
717         if (!groupobj->GetSGNode() ||
718                 !groupobj->IsDupliGroup() ||
719                 level>MAX_DUPLI_RECUR)
720                 return;
721
722         // we will add one group at a time
723         m_logicHierarchicalGameObjects.clear();
724         m_map_gameobject_to_replica.clear();
725         m_ueberExecutionPriority++;
726         // for groups will do something special: 
727         // we will force the creation of objects to those in the group only
728         // Again, this is match what Blender is doing (it doesn't care of parent relationship)
729         m_groupGameObjects.clear();
730
731         group = blgroupobj->dup_group;
732         for (go=(GroupObject*)group->gobject.first; go; go=(GroupObject*)go->next) 
733         {
734                 Object* blenderobj = go->ob;
735                 if (blgroupobj == blenderobj)
736                         // this check is also in group_duplilist()
737                         continue;
738
739                 gameobj = (KX_GameObject*)m_logicmgr->FindGameObjByBlendObj(blenderobj);
740                 if (gameobj == NULL) 
741                 {
742                         // this object has not been converted!!!
743                         // Should not happen as dupli group are created automatically 
744                         continue;
745                 }
746
747                 gameobj->SetBlenderGroupObject(blgroupobj);
748
749                 if ((blenderobj->lay & group->layer)==0)
750                 {
751                         // object is not visible in the 3D view, will not be instantiated
752                         continue;
753                 }
754                 m_groupGameObjects.insert(gameobj);
755         }
756
757         set<CValue*>::iterator oit;
758         for (oit=m_groupGameObjects.begin(); oit != m_groupGameObjects.end(); oit++)
759         {
760                 gameobj = (KX_GameObject*)(*oit);
761
762                 KX_GameObject *parent = gameobj->GetParent();
763                 if (parent != NULL)
764                 {
765                         // this object is not a top parent. Either it is the child of another
766                         // object in the group and it will be added automatically when the parent
767                         // is added. Or it is the child of an object outside the group and the group
768                         // is inconsistent, skip it anyway
769                         continue;
770                 }
771                 replica = (KX_GameObject*) AddNodeReplicaObject(NULL,gameobj);
772                 // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
773                 m_parentlist->Add(replica->AddRef());
774
775                 // recurse replication into children nodes
776                 NodeList& children = gameobj->GetSGNode()->GetSGChildren();
777
778                 replica->GetSGNode()->ClearSGChildren();
779                 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
780                 {
781                         SG_Node* orgnode = (*childit);
782                         SG_Node* childreplicanode = orgnode->GetSGReplica();
783                         if (childreplicanode)
784                                 replica->GetSGNode()->AddChild(childreplicanode);
785                 }
786                 // don't replicate logic now: we assume that the objects in the group can have
787                 // logic relationship, even outside parent relationship
788                 // In order to match 3D view, the position of groupobj is used as a 
789                 // transformation matrix instead of the new position. This means that 
790                 // the group reference point is 0,0,0
791
792                 // get the rootnode's scale
793                 MT_Vector3 newscale = groupobj->NodeGetWorldScaling();
794                 // set the replica's relative scale with the rootnode's scale
795                 replica->NodeSetRelativeScale(newscale);
796
797                 MT_Point3 offset(group->dupli_ofs);
798                 MT_Point3 newpos = groupobj->NodeGetWorldPosition() + 
799                         newscale*(groupobj->NodeGetWorldOrientation() * (gameobj->NodeGetWorldPosition()-offset));
800                 replica->NodeSetLocalPosition(newpos);
801                 // set the orientation after position for softbody!
802                 MT_Matrix3x3 newori = groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldOrientation();
803                 replica->NodeSetLocalOrientation(newori);
804                 // update scenegraph for entire tree of children
805                 replica->GetSGNode()->UpdateWorldData(0);
806                 replica->GetSGNode()->SetBBox(gameobj->GetSGNode()->BBox());
807                 replica->GetSGNode()->SetRadius(gameobj->GetSGNode()->Radius());
808                 // we can now add the graphic controller to the physic engine
809                 replica->ActivateGraphicController(true);
810
811                 // set references for dupli-group
812                 // groupobj holds a list of all objects, that belongs to this group
813                 groupobj->AddInstanceObjects(replica);
814
815                 // every object gets the reference to its dupli-group object
816                 replica->SetDupliGroupObject(groupobj);
817
818                 // done with replica
819                 replica->Release();
820         }
821
822         // the logic must be replicated first because we need
823         // the new logic bricks before relinking
824         vector<KX_GameObject*>::iterator git;
825         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
826         {
827                 (*git)->ReParentLogic();
828         }
829         
830         //      relink any pointers as necessary, sort of a temporary solution
831         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
832         {
833                 // this will also relink the actuator to objects within the hierarchy
834                 (*git)->Relink(&m_map_gameobject_to_replica);
835                 // add the object in the layer of the parent
836                 (*git)->SetLayer(groupobj->GetLayer());
837                 // If the object was a light, we need to update it's RAS_LightObject as well
838                 if ((*git)->GetGameObjectType()==SCA_IObject::OBJ_LIGHT)
839                 {
840                         KX_LightObject* lightobj = static_cast<KX_LightObject*>(*git);
841                         lightobj->SetLayer(groupobj->GetLayer());
842                 }
843         }
844
845         // replicate crosslinks etc. between logic bricks
846         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
847         {
848                 ReplicateLogic((*git));
849         }
850         
851         // now look if object in the hierarchy have dupli group and recurse
852         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
853         {
854                 /* Replicate all constraints. */
855                 if ((*git)->GetPhysicsController()) {
856                         (*git)->GetPhysicsController()->ReplicateConstraints((*git), m_logicHierarchicalGameObjects);
857                         (*git)->ClearConstraints();
858                 }
859
860                 if ((*git) != groupobj && (*git)->IsDupliGroup())
861                         // can't instantiate group immediately as it destroys m_logicHierarchicalGameObjects
862                         duplilist.push_back((*git));
863         }
864
865         for (git = duplilist.begin(); !(git == duplilist.end()); ++git)
866         {
867                 DupliGroupRecurse((*git), level+1);
868         }
869 }
870
871
872 SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
873                                                                                 class CValue* referenceobject,
874                                                                                 int lifespan)
875 {
876
877         m_logicHierarchicalGameObjects.clear();
878         m_map_gameobject_to_replica.clear();
879         m_groupGameObjects.clear();
880
881         KX_GameObject* originalobj = (KX_GameObject*) originalobject;
882         KX_GameObject* referenceobj = (KX_GameObject*) referenceobject;
883
884         m_ueberExecutionPriority++;
885
886         // lets create a replica
887         KX_GameObject* replica = (KX_GameObject*) AddNodeReplicaObject(NULL,originalobj);
888
889         // add a timebomb to this object
890         // lifespan of zero means 'this object lives forever'
891         if (lifespan > 0)
892         {
893                 // for now, convert between so called frames and realtime
894                 m_tempObjectList->Add(replica->AddRef());
895                 // this convert the life from frames to sort-of seconds, hard coded 0.02 that assumes we have 50 frames per second
896                 // if you change this value, make sure you change it in KX_GameObject::pyattr_get_life property too
897                 CValue *fval = new CFloatValue(lifespan*0.02);
898                 replica->SetProperty("::timebomb",fval);
899                 fval->Release();
900         }
901
902         // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
903         m_parentlist->Add(replica->AddRef());
904
905         // recurse replication into children nodes
906
907         NodeList& children = originalobj->GetSGNode()->GetSGChildren();
908
909         replica->GetSGNode()->ClearSGChildren();
910         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
911         {
912                 SG_Node* orgnode = (*childit);
913                 SG_Node* childreplicanode = orgnode->GetSGReplica();
914                 if (childreplicanode)
915                         replica->GetSGNode()->AddChild(childreplicanode);
916         }
917
918         // At this stage all the objects in the hierarchy have been duplicated,
919         // we can update the scenegraph, we need it for the duplication of logic
920         MT_Point3 newpos = referenceobj->NodeGetWorldPosition();
921         replica->NodeSetLocalPosition(newpos);
922
923         MT_Matrix3x3 newori = referenceobj->NodeGetWorldOrientation();
924         replica->NodeSetLocalOrientation(newori);
925         
926         // get the rootnode's scale
927         MT_Vector3 newscale = referenceobj->GetSGNode()->GetRootSGParent()->GetLocalScale();
928         // set the replica's relative scale with the rootnode's scale
929         replica->NodeSetRelativeScale(newscale);
930
931         replica->GetSGNode()->UpdateWorldData(0);
932         replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
933         replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
934         // the size is correct, we can add the graphic controller to the physic engine
935         replica->ActivateGraphicController(true);
936
937         // now replicate logic
938         vector<KX_GameObject*>::iterator git;
939         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
940         {
941                 (*git)->ReParentLogic();
942         }
943         
944         //      relink any pointers as necessary, sort of a temporary solution
945         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
946         {
947                 // this will also relink the actuators in the hierarchy
948                 (*git)->Relink(&m_map_gameobject_to_replica);
949                 // add the object in the layer of the reference object
950                 (*git)->SetLayer(referenceobj->GetLayer());
951                 // If the object was a light, we need to update it's RAS_LightObject as well
952                 if ((*git)->GetGameObjectType()==SCA_IObject::OBJ_LIGHT)
953                 {
954                         KX_LightObject* lightobj = static_cast<KX_LightObject*>(*git);
955                         lightobj->SetLayer(referenceobj->GetLayer());
956                 }
957         }
958
959         // replicate crosslinks etc. between logic bricks
960         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
961         {
962                 ReplicateLogic((*git));
963         }
964         
965         // check if there are objects with dupligroup in the hierarchy
966         vector<KX_GameObject*> duplilist;
967         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
968         {
969                 if ((*git)->IsDupliGroup())
970                 {
971                         // separate list as m_logicHierarchicalGameObjects is also used by DupliGroupRecurse()
972                         duplilist.push_back(*git);
973                 }
974         }
975         for (git = duplilist.begin();!(git==duplilist.end());++git)
976         {
977                 DupliGroupRecurse(*git, 0);
978         }
979         //      don't release replica here because we are returning it, not done with it...
980         return replica;
981 }
982
983
984
985 void KX_Scene::RemoveObject(class CValue* gameobj)
986 {
987         KX_GameObject* newobj = (KX_GameObject*) gameobj;
988
989         // disconnect child from parent
990         SG_Node* node = newobj->GetSGNode();
991
992         if (node)
993         {
994                 node->DisconnectFromParent();
995
996                 // recursively destruct
997                 node->Destruct();
998         }
999         //no need to do that: the object is destroyed and memory released 
1000         //newobj->SetSGNode(0);
1001 }
1002
1003 void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
1004 {
1005         //KX_GameObject* newobj = (KX_GameObject*) gameobj;
1006         if (!m_euthanasyobjects->SearchValue(gameobj))
1007         {
1008                 m_euthanasyobjects->Add(gameobj->AddRef());
1009         } 
1010 }
1011
1012
1013
1014 int KX_Scene::NewRemoveObject(class CValue* gameobj)
1015 {
1016         int ret;
1017         KX_GameObject* newobj = (KX_GameObject*) gameobj;
1018
1019         /* remove property from debug list */
1020         RemoveObjectDebugProperties(newobj);
1021
1022         /* Invalidate the python reference, since the object may exist in script lists
1023          * its possible that it wont be automatically invalidated, so do it manually here,
1024          * 
1025          * if for some reason the object is added back into the scene python can always get a new Proxy
1026          */
1027         newobj->InvalidateProxy();
1028
1029         // keep the blender->game object association up to date
1030         // note that all the replicas of an object will have the same
1031         // blender object, that's why we need to check the game object
1032         // as only the deletion of the original object must be recorded
1033         m_logicmgr->UnregisterGameObj(newobj->GetBlenderObject(), gameobj);
1034
1035         //todo: look at this
1036         //GetPhysicsEnvironment()->RemovePhysicsController(gameobj->getPhysicsController());
1037
1038         // remove all sensors/controllers/actuators from logicsystem...
1039         
1040         SCA_SensorList& sensors = newobj->GetSensors();
1041         for (SCA_SensorList::iterator its = sensors.begin();
1042                  !(its==sensors.end());its++)
1043         {
1044                 m_logicmgr->RemoveSensor(*its);
1045         }
1046
1047         SCA_ControllerList& controllers = newobj->GetControllers();
1048         for (SCA_ControllerList::iterator itc = controllers.begin();
1049                  !(itc==controllers.end());itc++)
1050         {
1051                 m_logicmgr->RemoveController(*itc);
1052                 (*itc)->ReParent(NULL);
1053         }
1054
1055         SCA_ActuatorList& actuators = newobj->GetActuators();
1056         for (SCA_ActuatorList::iterator ita = actuators.begin();
1057                  !(ita==actuators.end());ita++)
1058         {
1059                 m_logicmgr->RemoveActuator(*ita);
1060         }
1061         // the sensors/controllers/actuators must also be released, this is done in ~SCA_IObject
1062
1063         // now remove the timer properties from the time manager
1064         int numprops = newobj->GetPropertyCount();
1065
1066         for (int i = 0; i < numprops; i++)
1067         {
1068                 CValue* propval = newobj->GetProperty(i);
1069                 if (propval->GetProperty("timer"))
1070                 {
1071                         m_timemgr->RemoveTimeProperty(propval);
1072                 }
1073         }
1074
1075         // if the object is the dupligroup proxy, you have to cleanup all m_pDupliGroupObject's in all
1076         // instances refering to this group
1077         if (newobj->GetInstanceObjects()) {
1078                 for (int i = 0; i < newobj->GetInstanceObjects()->GetCount(); i++) {
1079                         KX_GameObject* instance = (KX_GameObject*)newobj->GetInstanceObjects()->GetValue(i);
1080                         instance->RemoveDupliGroupObject();
1081                 }
1082         }
1083
1084         // if this object was part of a group, make sure to remove it from that group's instance list
1085         KX_GameObject* group = newobj->GetDupliGroupObject();
1086         if (group)
1087                 group->RemoveInstanceObject(newobj);
1088         
1089         newobj->RemoveMeshes();
1090         ret = 1;
1091         if (newobj->GetGameObjectType()==SCA_IObject::OBJ_LIGHT && m_lightlist->RemoveValue(newobj))
1092                 ret = newobj->Release();
1093         if (m_objectlist->RemoveValue(newobj))
1094                 ret = newobj->Release();
1095         if (m_tempObjectList->RemoveValue(newobj))
1096                 ret = newobj->Release();
1097         if (m_parentlist->RemoveValue(newobj))
1098                 ret = newobj->Release();
1099         if (m_inactivelist->RemoveValue(newobj))
1100                 ret = newobj->Release();
1101         if (m_euthanasyobjects->RemoveValue(newobj))
1102                 ret = newobj->Release();
1103         if (m_animatedlist->RemoveValue(newobj))
1104                 ret = newobj->Release();
1105                 
1106         if (newobj == m_active_camera)
1107         {
1108                 //no AddRef done on m_active_camera so no Release
1109                 //m_active_camera->Release();
1110                 m_active_camera = NULL;
1111         }
1112
1113         // in case this is a camera
1114         m_cameras.remove((KX_Camera*)newobj);
1115
1116         // in case this is a font
1117         m_fonts.remove((KX_FontObject*)newobj);
1118
1119         /* currently does nothing, keep in case we need to Unregister something */
1120 #if 0
1121         if (m_sceneConverter)
1122                 m_sceneConverter->UnregisterGameObject(newobj);
1123 #endif
1124         
1125         // return value will be 0 if the object is actually deleted (all reference gone)
1126         
1127         return ret;
1128 }
1129
1130
1131
1132 void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj, bool use_gfx, bool use_phys)
1133 {
1134         KX_GameObject* gameobj = static_cast<KX_GameObject*>(obj);
1135         RAS_MeshObject* mesh = static_cast<RAS_MeshObject*>(meshobj);
1136
1137         if (!gameobj) {
1138                 std::cout << "KX_Scene::ReplaceMesh Warning: invalid object, doing nothing" << std::endl;
1139                 return;
1140         }
1141
1142         if (use_gfx && mesh != NULL)
1143         {
1144         gameobj->RemoveMeshes();
1145         gameobj->AddMesh(mesh);
1146         
1147         if (gameobj->m_isDeformable)
1148         {
1149                 BL_DeformableGameObject* newobj = static_cast<BL_DeformableGameObject*>( gameobj );
1150                 
1151                 if (newobj->GetDeformer())
1152                 {
1153                         delete newobj->GetDeformer();
1154                         newobj->SetDeformer(NULL);
1155                 }
1156
1157                 if (mesh->GetMesh()) 
1158                 {
1159                         // we must create a new deformer but which one?
1160                         KX_GameObject* parentobj = newobj->GetParent();
1161                         // this always return the original game object (also for replicate)
1162                         Object* blendobj = newobj->GetBlenderObject();
1163                         // object that owns the new mesh
1164                         Object* oldblendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameMeshName(mesh->GetName()));
1165                         Mesh* blendmesh = mesh->GetMesh();
1166
1167                         bool bHasModifier = BL_ModifierDeformer::HasCompatibleDeformer(blendobj);
1168                         bool bHasShapeKey = blendmesh->key != NULL && blendmesh->key->type==KEY_RELATIVE;
1169                         bool bHasDvert = blendmesh->dvert != NULL;
1170                         bool bHasArmature = 
1171                                 BL_ModifierDeformer::HasArmatureDeformer(blendobj) &&
1172                                 parentobj &&                                                            // current parent is armature
1173                                 parentobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE &&
1174                                 oldblendobj &&                                                          // needed for mesh deform
1175                                 blendobj->parent &&                                                     // original object had armature (not sure this test is needed)
1176                                 blendobj->parent->type == OB_ARMATURE &&
1177                                 blendmesh->dvert!=NULL;                                         // mesh has vertex group
1178 #ifdef WITH_BULLET
1179                         bool bHasSoftBody = (!parentobj && (blendobj->gameflag & OB_SOFT_BODY));
1180 #endif
1181                         
1182                         if (oldblendobj==NULL) {
1183                                 if (bHasModifier || bHasShapeKey || bHasDvert || bHasArmature) {
1184                                         std::cout << "warning: ReplaceMesh() new mesh is not used in an object from the current scene, you will get incorrect behavior" << std::endl;
1185                                         bHasShapeKey= bHasDvert= bHasArmature=bHasModifier= false;
1186                                 }
1187                         }
1188                         
1189                         if (bHasModifier)
1190                         {
1191                                 BL_ModifierDeformer* modifierDeformer;
1192                                 if (bHasShapeKey || bHasArmature)
1193                                 {
1194                                         modifierDeformer = new BL_ModifierDeformer(
1195                                                 newobj,
1196                                                 m_blenderScene,
1197                                                 oldblendobj, blendobj,
1198                                                 mesh,
1199                                                 true,
1200                                                 static_cast<BL_ArmatureObject*>( parentobj->AddRef() )
1201                                         );
1202                                         modifierDeformer->LoadShapeDrivers(parentobj);
1203                                 }
1204                                 else
1205                                 {
1206                                         modifierDeformer = new BL_ModifierDeformer(
1207                                                 newobj,
1208                                                 m_blenderScene,
1209                                                 oldblendobj, blendobj,
1210                                                 mesh,
1211                                                 false,
1212                                                 NULL
1213                                         );
1214                                 }
1215                                 newobj->SetDeformer(modifierDeformer);
1216                         }
1217                         else if (bHasShapeKey) {
1218                                 BL_ShapeDeformer* shapeDeformer;
1219                                 if (bHasArmature) 
1220                                 {
1221                                         shapeDeformer = new BL_ShapeDeformer(
1222                                                 newobj,
1223                                                 oldblendobj, blendobj,
1224                                                 mesh,
1225                                                 true,
1226                                                 true,
1227                                                 static_cast<BL_ArmatureObject*>( parentobj->AddRef() )
1228                                         );
1229                                         shapeDeformer->LoadShapeDrivers(parentobj);
1230                                 }
1231                                 else
1232                                 {
1233                                         shapeDeformer = new BL_ShapeDeformer(
1234                                                 newobj,
1235                                                 oldblendobj, blendobj,
1236                                                 mesh,
1237                                                 false,
1238                                                 true,
1239                                                 NULL
1240                                         );
1241                                 }
1242                                 newobj->SetDeformer( shapeDeformer);
1243                         }
1244                         else if (bHasArmature) 
1245                         {
1246                                 BL_SkinDeformer* skinDeformer = new BL_SkinDeformer(
1247                                         newobj,
1248                                         oldblendobj, blendobj,
1249                                         mesh,
1250                                         true,
1251                                         true,
1252                                         static_cast<BL_ArmatureObject*>( parentobj->AddRef() )
1253                                 );
1254                                 newobj->SetDeformer(skinDeformer);
1255                         }
1256                         else if (bHasDvert)
1257                         {
1258                                 BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
1259                                         newobj, oldblendobj, mesh
1260                                 );
1261                                 newobj->SetDeformer(meshdeformer);
1262                         }
1263 #ifdef WITH_BULLET
1264                         else if (bHasSoftBody)
1265                         {
1266                                 KX_SoftBodyDeformer *softdeformer = new KX_SoftBodyDeformer(mesh, newobj);
1267                                 newobj->SetDeformer(softdeformer);
1268                         }
1269 #endif
1270                 }
1271         }
1272
1273         gameobj->AddMeshUser();
1274         }
1275
1276         if (use_phys) { /* update the new assigned mesh with the physics mesh */
1277                 if (gameobj->GetPhysicsController())
1278                         gameobj->GetPhysicsController()->ReinstancePhysicsShape(NULL, use_gfx?NULL:mesh);
1279         }
1280 }
1281
1282 /* Font Object routines */
1283 void KX_Scene::AddFont(KX_FontObject* font)
1284 {
1285         if (!FindFont(font))
1286                 m_fonts.push_back(font);
1287 }
1288
1289 KX_FontObject* KX_Scene::FindFont(KX_FontObject* font)
1290 {
1291         list<KX_FontObject*>::iterator it = m_fonts.begin();
1292
1293         while ((it != m_fonts.end()) && ((*it) != font))
1294         {
1295                 ++it;
1296         }
1297
1298         return ((it == m_fonts.end()) ? NULL : (*it));
1299 }
1300
1301
1302 /* Camera Object routines */
1303 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
1304 {
1305         list<KX_Camera*>::iterator it = m_cameras.begin();
1306
1307         while ((it != m_cameras.end()) && ((*it) != cam)) {
1308                 it++;
1309         }
1310
1311         return ((it == m_cameras.end()) ? NULL : (*it));
1312 }
1313
1314
1315 KX_Camera* KX_Scene::FindCamera(STR_String& name)
1316 {
1317         list<KX_Camera*>::iterator it = m_cameras.begin();
1318
1319         while ((it != m_cameras.end()) && ((*it)->GetName() != name)) {
1320                 it++;
1321         }
1322
1323         return ((it == m_cameras.end()) ? NULL : (*it));
1324 }
1325
1326 void KX_Scene::AddCamera(KX_Camera* cam)
1327 {
1328         if (!FindCamera(cam))
1329                 m_cameras.push_back(cam);
1330 }
1331
1332
1333 KX_Camera* KX_Scene::GetActiveCamera()
1334 {
1335         // NULL if not defined
1336         return m_active_camera;
1337 }
1338
1339
1340 void KX_Scene::SetActiveCamera(KX_Camera* cam)
1341 {
1342         // only set if the cam is in the active list? Or add it otherwise?
1343         if (!FindCamera(cam)) {
1344                 AddCamera(cam);
1345                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1346         } 
1347
1348         m_active_camera = cam;
1349 }
1350
1351 void KX_Scene::SetCameraOnTop(KX_Camera* cam)
1352 {
1353         if (!FindCamera(cam)) {
1354                 // adding is always done at the back, so that's all that needs to be done
1355                 AddCamera(cam);
1356                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1357         } else {
1358                 m_cameras.remove(cam);
1359                 m_cameras.push_back(cam);
1360         }
1361 }
1362
1363 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam, int layer)
1364 {
1365         int intersect = KX_Camera::INTERSECT;
1366         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
1367         bool visible = (gameobj && gameobj->GetVisible() && (!layer || (gameobj->GetLayer() & layer)));
1368         bool dotest = visible || node->Left() || node->Right();
1369
1370         /* If the camera is inside the box, assume intersect. */
1371         if (dotest && !node->inside( cam->NodeGetWorldPosition()))
1372         {
1373                 MT_Scalar radius = node->Radius();
1374                 MT_Point3 center = node->Center();
1375                 
1376                 intersect =  cam->SphereInsideFrustum(center, radius); 
1377                 
1378                 if (intersect == KX_Camera::INTERSECT)
1379                 {
1380                         MT_Point3 box[8];
1381                         node->get(box);
1382                         intersect = cam->BoxInsideFrustum(box);
1383                 }
1384         }
1385
1386         switch (intersect)
1387         {
1388                 case KX_Camera::OUTSIDE:
1389                         MarkSubTreeVisible(node, rasty, false, cam);
1390                         break;
1391                 case KX_Camera::INTERSECT:
1392                         if (gameobj)
1393                                 MarkVisible(rasty, gameobj, cam, layer);
1394                         if (node->Left())
1395                                 MarkVisible(node->Left(), rasty, cam, layer);
1396                         if (node->Right())
1397                                 MarkVisible(node->Right(), rasty, cam, layer);
1398                         break;
1399                 case KX_Camera::INSIDE:
1400                         MarkSubTreeVisible(node, rasty, true, cam, layer);
1401                         break;
1402         }
1403 }
1404
1405 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera* cam, int layer)
1406 {
1407         if (node->Client())
1408         {
1409                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
1410                 if (gameobj->GetVisible())
1411                 {
1412                         if (visible)
1413                         {
1414                                 int nummeshes = gameobj->GetMeshCount();
1415                                 
1416                                 // this adds the vertices to the display list
1417                                 for (int m=0;m<nummeshes;m++)
1418                                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1419                         }
1420
1421                         gameobj->SetCulled(!visible);
1422                         gameobj->UpdateBuckets(false);
1423                 }
1424         }
1425         if (node->Left())
1426                 MarkSubTreeVisible(node->Left(), rasty, visible, cam, layer);
1427         if (node->Right())
1428                 MarkSubTreeVisible(node->Right(), rasty, visible, cam, layer);
1429 }
1430
1431 void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera*  cam,int layer)
1432 {
1433         // User (Python/Actuator) has forced object invisible...
1434         if (!gameobj->GetSGNode() || !gameobj->GetVisible())
1435                 return;
1436         
1437         // Shadow lamp layers
1438         if (layer && !(gameobj->GetLayer() & layer)) {
1439                 gameobj->SetCulled(true);
1440                 gameobj->UpdateBuckets(false);
1441                 return;
1442         }
1443
1444         // If Frustum culling is off, the object is always visible.
1445         bool vis = !cam->GetFrustumCulling();
1446         
1447         // If the camera is inside this node, then the object is visible.
1448         if (!vis)
1449         {
1450                 vis = gameobj->GetSGNode()->inside( cam->GetCameraLocation() );
1451         }
1452                 
1453         // Test the object's bound sphere against the view frustum.
1454         if (!vis)
1455         {
1456                 MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
1457                 MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
1458                 switch (cam->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
1459                 {
1460                         case KX_Camera::INSIDE:
1461                                 vis = true;
1462                                 break;
1463                         case KX_Camera::OUTSIDE:
1464                                 vis = false;
1465                                 break;
1466                         case KX_Camera::INTERSECT:
1467                                 // Test the object's bound box against the view frustum.
1468                                 MT_Point3 box[8];
1469                                 gameobj->GetSGNode()->getBBox(box); 
1470                                 vis = cam->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
1471                                 break;
1472                 }
1473         }
1474         
1475         if (vis)
1476         {
1477                 int nummeshes = gameobj->GetMeshCount();
1478                 
1479                 for (int m=0;m<nummeshes;m++)
1480                 {
1481                         // this adds the vertices to the display list
1482                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1483                 }
1484                 // Visibility/ non-visibility are marked
1485                 // elsewhere now.
1486                 gameobj->SetCulled(false);
1487                 gameobj->UpdateBuckets(false);
1488         } else {
1489                 gameobj->SetCulled(true);
1490                 gameobj->UpdateBuckets(false);
1491         }
1492 }
1493
1494 void KX_Scene::PhysicsCullingCallback(KX_ClientObjectInfo *objectInfo, void* cullingInfo)
1495 {
1496         KX_GameObject* gameobj = objectInfo->m_gameobject;
1497         if (!gameobj->GetVisible())
1498                 // ideally, invisible objects should be removed from the culling tree temporarily
1499                 return;
1500         if (((CullingInfo*)cullingInfo)->m_layer && !(gameobj->GetLayer() & ((CullingInfo*)cullingInfo)->m_layer))
1501                 // used for shadow: object is not in shadow layer
1502                 return;
1503
1504         // make object visible
1505         gameobj->SetCulled(false);
1506         gameobj->UpdateBuckets(false);
1507 }
1508
1509 void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam, int layer)
1510 {
1511         bool dbvt_culling = false;
1512         if (m_dbvt_culling) 
1513         {
1514                 /* Reset KX_GameObject m_bCulled to true before doing culling
1515                  * since DBVT culling will only set it to false.
1516                  * This is similar to what RAS_BucketManager does for RAS_MeshSlot culling.
1517                  */
1518                 for (int i = 0; i < m_objectlist->GetCount(); i++) {
1519                         KX_GameObject *gameobj = static_cast<KX_GameObject*>(m_objectlist->GetValue(i));
1520                         gameobj->SetCulled(true);
1521                 }
1522
1523                 // test culling through Bullet
1524                 MT_Vector4 planes[6];
1525                 // get the clip planes
1526                 MT_Vector4* cplanes = cam->GetNormalizedClipPlanes();
1527                 // and convert
1528                 planes[0].setValue(cplanes[4].getValue());      // near
1529                 planes[1].setValue(cplanes[5].getValue());      // far
1530                 planes[2].setValue(cplanes[0].getValue());      // left
1531                 planes[3].setValue(cplanes[1].getValue());      // right
1532                 planes[4].setValue(cplanes[2].getValue());      // top
1533                 planes[5].setValue(cplanes[3].getValue());      // bottom
1534                 CullingInfo info(layer);
1535
1536                 double mvmat[16] = {0};
1537                 cam->GetModelviewMatrix().getValue(mvmat);
1538                 double pmat[16] = {0};
1539                 cam->GetProjectionMatrix().getValue(pmat);
1540
1541                 dbvt_culling = m_physicsEnvironment->CullingTest(PhysicsCullingCallback,&info,planes,5,m_dbvt_occlusion_res,
1542                                                                  KX_GetActiveEngine()->GetCanvas()->GetViewPort(),
1543                                                                  mvmat, pmat);
1544         }
1545         if (!dbvt_culling) {
1546                 // the physics engine couldn't help us, do it the hard way
1547                 for (int i = 0; i < m_objectlist->GetCount(); i++)
1548                 {
1549                         MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)), cam, layer);
1550                 }
1551         }
1552 }
1553
1554 // logic stuff
1555 void KX_Scene::LogicBeginFrame(double curtime)
1556 {
1557         // have a look at temp objects ...
1558         int lastobj = m_tempObjectList->GetCount() - 1;
1559         
1560         for (int i = lastobj; i >= 0; i--)
1561         {
1562                 CValue* objval = m_tempObjectList->GetValue(i);
1563                 CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
1564                 
1565                 if (propval)
1566                 {
1567                         float timeleft = propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate();
1568                         
1569                         if (timeleft > 0)
1570                         {
1571                                 propval->SetFloat(timeleft);
1572                         }
1573                         else
1574                         {
1575                                 DelayedRemoveObject(objval);
1576                                 // remove obj
1577                         }
1578                 }
1579                 else
1580                 {
1581                         // all object is the tempObjectList should have a clock
1582                 }
1583         }
1584         m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate());
1585 }
1586
1587 void KX_Scene::AddAnimatedObject(CValue* gameobj)
1588 {
1589         gameobj->AddRef();
1590         m_animatedlist->Add(gameobj);
1591 }
1592
1593 static void update_anim_thread_func(TaskPool *pool, void *taskdata, int UNUSED(threadid))
1594 {
1595         KX_GameObject *gameobj, *child, *parent;
1596         CListValue *children;
1597         bool needs_update;
1598         double curtime = *(double*)BLI_task_pool_userdata(pool);
1599
1600         gameobj = (KX_GameObject*)taskdata;
1601
1602         // Non-armature updates are fast enough, so just update them
1603         needs_update = gameobj->GetGameObjectType() != SCA_IObject::OBJ_ARMATURE;
1604
1605         if (!needs_update) {
1606                 // If we got here, we're looking to update an armature, so check its children meshes
1607                 // to see if we need to bother with a more expensive pose update
1608                 children = gameobj->GetChildren();
1609
1610                 bool has_mesh = false, has_non_mesh = false;
1611
1612                 // Check for meshes that haven't been culled
1613                 for (int j=0; j<children->GetCount(); ++j) {
1614                         child = (KX_GameObject*)children->GetValue(j);
1615
1616                         if (!child->GetCulled()) {
1617                                 needs_update = true;
1618                                 break;
1619                         }
1620
1621                         if (child->GetMeshCount() == 0)
1622                                 has_non_mesh = true;
1623                         else
1624                                 has_mesh = true;
1625                 }
1626
1627                 // If we didn't find a non-culled mesh, check to see
1628                 // if we even have any meshes, and update if this
1629                 // armature has only non-mesh children.
1630                 if (!needs_update && !has_mesh && has_non_mesh)
1631                         needs_update = true;
1632
1633                 children->Release();
1634         }
1635
1636         if (needs_update) {
1637                 gameobj->UpdateActionManager(curtime);
1638                 children = gameobj->GetChildren();
1639                 parent = gameobj->GetParent();
1640
1641                 // Only do deformers here if they are not parented to an armature, otherwise the armature will
1642                 // handle updating its children
1643                 if (gameobj->GetDeformer() && (!parent || (parent && parent->GetGameObjectType() != SCA_IObject::OBJ_ARMATURE)))
1644                         gameobj->GetDeformer()->Update();
1645
1646                 for (int j=0; j<children->GetCount(); ++j) {
1647                         child = (KX_GameObject*)children->GetValue(j);
1648
1649                         if (child->GetDeformer()) {
1650                                 child->GetDeformer()->Update();
1651                         }
1652                 }
1653
1654                 children->Release();
1655         }
1656 }
1657
1658 void KX_Scene::UpdateAnimations(double curtime)
1659 {
1660         TaskPool *pool = BLI_task_pool_create(KX_GetActiveEngine()->GetTaskScheduler(), &curtime);
1661
1662         for (int i=0; i<m_animatedlist->GetCount(); ++i) {
1663                 BLI_task_pool_push(pool, update_anim_thread_func, m_animatedlist->GetValue(i), false, TASK_PRIORITY_LOW);
1664         }
1665
1666         BLI_task_pool_work_and_wait(pool);
1667         BLI_task_pool_free(pool);
1668
1669         for (int i=0; i<m_animatedlist->GetCount(); ++i) {
1670                 ((KX_GameObject*)m_animatedlist->GetValue(i))->UpdateActionIPOs();
1671         }
1672 }
1673
1674 void KX_Scene::LogicUpdateFrame(double curtime, bool frame)
1675 {
1676         m_logicmgr->UpdateFrame(curtime, frame);
1677 }
1678
1679
1680
1681 void KX_Scene::LogicEndFrame()
1682 {
1683         m_logicmgr->EndFrame();
1684         int numobj;
1685
1686         KX_GameObject* obj;
1687
1688         while ((numobj = m_euthanasyobjects->GetCount()) > 0)
1689         {
1690                 // remove the object from this list to make sure we will not hit it again
1691                 obj = (KX_GameObject*)m_euthanasyobjects->GetValue(numobj-1);
1692                 m_euthanasyobjects->Remove(numobj-1);
1693                 obj->Release();
1694                 RemoveObject(obj);
1695         }
1696
1697         //prepare obstacle simulation for new frame
1698         if (m_obstacleSimulation)
1699                 m_obstacleSimulation->UpdateObstacles();
1700 }
1701
1702
1703
1704 /**
1705  * UpdateParents: SceneGraph transformation update.
1706  */
1707 void KX_Scene::UpdateParents(double curtime)
1708 {
1709         // we use the SG dynamic list
1710         SG_Node* node;
1711
1712         while ((node = SG_Node::GetNextScheduled(m_sghead)) != NULL)
1713         {
1714                 node->UpdateWorldData(curtime);
1715         }
1716
1717         //for (int i=0; i<GetRootParentList()->GetCount(); i++)
1718         //{
1719         //      KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
1720         //      parentobj->NodeUpdateGS(curtime);
1721         //}
1722
1723         // the list must be empty here
1724         assert(m_sghead.Empty());
1725         // some nodes may be ready for reschedule, move them to schedule list for next time
1726         while ((node = SG_Node::GetNextRescheduled(m_sghead)) != NULL)
1727         {
1728                 node->Schedule(m_sghead);
1729         }
1730 }
1731
1732
1733 RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat, bool &bucketCreated)
1734 {
1735         return m_bucketmanager->FindBucket(polymat, bucketCreated);
1736 }
1737
1738
1739
1740 void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
1741                              class RAS_IRasterizer* rasty)
1742 {
1743         m_bucketmanager->Renderbuckets(cameratransform,rasty);
1744         KX_BlenderMaterial::EndFrame();
1745 }
1746
1747 void KX_Scene::RenderFonts()
1748 {
1749         list<KX_FontObject*>::iterator it = m_fonts.begin();
1750         while (it != m_fonts.end()) {
1751                 (*it)->DrawFontText();
1752                 ++it;
1753         }
1754 }
1755
1756 void KX_Scene::UpdateObjectLods(void)
1757 {
1758         KX_GameObject* gameobj;
1759         MT_Vector3 cam_pos = this->m_active_camera->NodeGetWorldPosition();
1760
1761         for (int i = 0; i < this->GetObjectList()->GetCount(); i++) {
1762                 gameobj = (KX_GameObject*) GetObjectList()->GetValue(i);
1763                 if (!gameobj->GetCulled()){
1764                         gameobj->UpdateLod(cam_pos);
1765                 }
1766         }
1767 }
1768
1769 void KX_Scene::SetLodHysteresis(bool active)
1770 {
1771         m_isActivedHysteresis = active;
1772 }
1773
1774 bool KX_Scene::IsActivedLodHysteresis(void)
1775 {
1776         return m_isActivedHysteresis;
1777 }
1778
1779 void KX_Scene::SetLodHysteresisValue(int hysteresisvalue)
1780 {
1781         m_lodHysteresisValue = hysteresisvalue;
1782 }
1783
1784 int KX_Scene::GetLodHysteresisValue(void)
1785 {
1786         return m_lodHysteresisValue;
1787 }
1788
1789 void KX_Scene::UpdateObjectActivity(void) 
1790 {
1791         if (m_activity_culling) {
1792                 /* determine the activity criterium and set objects accordingly */
1793                 int i=0;
1794                 
1795                 MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
1796                 
1797                 for (i=0;i<GetObjectList()->GetCount();i++)
1798                 {
1799                         KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
1800                         
1801                         if (!ob->GetIgnoreActivityCulling()) {
1802                                 /* Simple test: more than 10 away from the camera, count
1803                                  * Manhattan distance. */
1804                                 MT_Point3 obpos = ob->NodeGetWorldPosition();
1805                                 
1806                                 if ((fabs(camloc[0] - obpos[0]) > m_activity_box_radius) ||
1807                                     (fabs(camloc[1] - obpos[1]) > m_activity_box_radius) ||
1808                                     (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
1809                                 {
1810                                         ob->Suspend();
1811                                 }
1812                                 else {
1813                                         ob->Resume();
1814                                 }
1815                         }
1816                 }
1817         }
1818 }
1819
1820 void KX_Scene::SetActivityCullingRadius(float f)
1821 {
1822         if (f < 0.5)
1823                 f = 0.5;
1824         m_activity_box_radius = f;
1825 }
1826         
1827 NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
1828 {
1829         return m_networkDeviceInterface;
1830 }
1831
1832 NG_NetworkScene* KX_Scene::GetNetworkScene()
1833 {
1834         return m_networkScene;
1835 }
1836
1837 void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
1838 {
1839         m_networkDeviceInterface = newInterface;
1840 }
1841
1842 void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
1843 {
1844         m_networkScene = newScene;
1845 }
1846
1847
1848 void    KX_Scene::SetGravity(const MT_Vector3& gravity)
1849 {
1850         GetPhysicsEnvironment()->SetGravity(gravity[0],gravity[1],gravity[2]);
1851 }
1852
1853 MT_Vector3 KX_Scene::GetGravity()
1854 {
1855         MT_Vector3 gravity;
1856
1857         GetPhysicsEnvironment()->GetGravity(gravity);
1858
1859         return gravity;
1860 }
1861
1862 void KX_Scene::SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter)
1863 {
1864         m_sceneConverter = sceneConverter;
1865 }
1866
1867 void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
1868 {
1869         m_physicsEnvironment = physEnv;
1870         if (m_physicsEnvironment) {
1871                 KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, physEnv);
1872                 m_logicmgr->RegisterEventManager(touchmgr);
1873         }
1874 }
1875  
1876 void KX_Scene::setSuspendedTime(double suspendedtime)
1877 {
1878         m_suspendedtime = suspendedtime;
1879 }
1880 double KX_Scene::getSuspendedTime()
1881 {
1882         return m_suspendedtime;
1883 }
1884 void KX_Scene::setSuspendedDelta(double suspendeddelta)
1885 {
1886         m_suspendeddelta = suspendeddelta;
1887 }
1888 double KX_Scene::getSuspendedDelta()
1889 {
1890         return m_suspendeddelta;
1891 }
1892
1893 short KX_Scene::GetAnimationFPS()
1894 {
1895         return m_blenderScene->r.frs_sec;
1896 }
1897
1898 static void MergeScene_LogicBrick(SCA_ILogicBrick* brick, KX_Scene *from, KX_Scene *to)
1899 {
1900         SCA_LogicManager *logicmgr= to->GetLogicManager();
1901
1902         brick->Replace_IScene(to);
1903         brick->Replace_NetworkScene(to->GetNetworkScene());
1904
1905         /* near sensors have physics controllers */
1906         KX_TouchSensor *touch_sensor = dynamic_cast<class KX_TouchSensor *>(brick);
1907         if (touch_sensor) {
1908                 KX_TouchEventManager *tmgr = (KX_TouchEventManager*)from->GetLogicManager()->FindEventManager(SCA_EventManager::TOUCH_EVENTMGR);
1909                 touch_sensor->UnregisterSumo(tmgr);
1910                 touch_sensor->GetPhysicsController()->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1911                 touch_sensor->RegisterSumo(tmgr);
1912         }
1913
1914         // If we end up replacing a KX_TouchEventManager, we need to make sure
1915         // physics controllers are properly in place. In other words, do this
1916         // after merging physics controllers!
1917         SCA_ISensor *sensor=  dynamic_cast<class SCA_ISensor *>(brick);
1918         if (sensor) {
1919                 sensor->Replace_EventManager(logicmgr);
1920         }
1921
1922         SCA_2DFilterActuator *filter_actuator = dynamic_cast<class SCA_2DFilterActuator*>(brick);
1923         if (filter_actuator) {
1924                 filter_actuator->SetScene(to);
1925         }
1926
1927 #ifdef WITH_PYTHON
1928         // Python must be called from the main thread unless we want to deal
1929         // with GIL issues. So, this is delayed until here in case of async
1930         // libload (originally in KX_ConvertControllers)
1931         SCA_PythonController *pyctrl = dynamic_cast<SCA_PythonController*>(brick);
1932         if (pyctrl) {
1933                 pyctrl->SetNamespace(KX_GetActiveEngine()->GetPyNamespace());
1934
1935                 if (pyctrl->m_mode==SCA_PythonController::SCA_PYEXEC_SCRIPT)
1936                         pyctrl->Compile();
1937         }
1938 #endif
1939 }
1940
1941 static void MergeScene_GameObject(KX_GameObject* gameobj, KX_Scene *to, KX_Scene *from)
1942 {
1943         {
1944                 SCA_ActuatorList& actuators= gameobj->GetActuators();
1945                 SCA_ActuatorList::iterator ita;
1946
1947                 for (ita = actuators.begin(); !(ita==actuators.end()); ++ita)
1948                 {
1949                         MergeScene_LogicBrick(*ita, from, to);
1950                 }
1951         }
1952
1953
1954         {
1955                 SCA_SensorList& sensors= gameobj->GetSensors();
1956                 SCA_SensorList::iterator its;
1957
1958                 for (its = sensors.begin(); !(its==sensors.end()); ++its)
1959                 {
1960                         MergeScene_LogicBrick(*its, from, to);
1961                 }
1962         }
1963
1964         {
1965                 SCA_ControllerList& controllers= gameobj->GetControllers();
1966                 SCA_ControllerList::iterator itc;
1967
1968                 for (itc = controllers.begin(); !(itc==controllers.end()); ++itc)
1969                 {
1970                         SCA_IController *cont= *itc;
1971                         MergeScene_LogicBrick(cont, from, to);
1972
1973                         vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
1974                         vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
1975
1976                         for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());++ita) {
1977                                 MergeScene_LogicBrick(*ita, from, to);
1978                         }
1979
1980                         for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());++its) {
1981                                 MergeScene_LogicBrick(*its, from, to);
1982                         }
1983                 }
1984         }
1985
1986         /* graphics controller */
1987         PHY_IController *ctrl = gameobj->GetGraphicController();
1988         if (ctrl) {
1989                 /* SHOULD update the m_cullingTree */
1990                 ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1991         }
1992
1993         ctrl = gameobj->GetPhysicsController();
1994         if (ctrl) {
1995                 ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1996         }
1997
1998         /* SG_Node can hold a scene reference */
1999         SG_Node *sg= gameobj->GetSGNode();
2000         if (sg) {
2001                 if (sg->GetSGClientInfo() == from) {
2002                         sg->SetSGClientInfo(to);
2003
2004                         /* Make sure to grab the children too since they might not be tied to a game object */
2005                         NodeList children = sg->GetSGChildren();
2006                         for (int i=0; i<children.size(); i++)
2007                                         children[i]->SetSGClientInfo(to);
2008                 }
2009         }
2010         /* If the object is a light, update it's scene */
2011         if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_LIGHT)
2012                 ((KX_LightObject*)gameobj)->UpdateScene(to);
2013
2014         if (gameobj->GetGameObjectType() == SCA_IObject::OBJ_CAMERA)
2015                 to->AddCamera((KX_Camera*)gameobj);
2016
2017         /* Add the object to the scene's logic manager */
2018         to->GetLogicManager()->RegisterGameObjectName(gameobj->GetName(), gameobj);
2019         to->GetLogicManager()->RegisterGameObj(gameobj->GetBlenderObject(), gameobj);
2020
2021         for (int i=0; i<gameobj->GetMeshCount(); ++i)
2022                 to->GetLogicManager()->RegisterGameMeshName(gameobj->GetMesh(i)->GetName(), gameobj->GetBlenderObject());
2023 }
2024
2025 bool KX_Scene::MergeScene(KX_Scene *other)
2026 {
2027         PHY_IPhysicsEnvironment *env = this->GetPhysicsEnvironment();
2028         PHY_IPhysicsEnvironment *env_other = other->GetPhysicsEnvironment();
2029
2030         if ((env==NULL) != (env_other==NULL)) /* TODO - even when both scenes have NONE physics, the other is loaded with bullet enabled, ??? */
2031         {
2032                 printf("KX_Scene::MergeScene: physics scenes type differ, aborting\n");
2033                 printf("\tsource %d, terget %d\n", (int)(env!=NULL), (int)(env_other!=NULL));
2034                 return false;
2035         }
2036
2037         if (GetSceneConverter() != other->GetSceneConverter()) {
2038                 printf("KX_Scene::MergeScene: converters differ, aborting\n");
2039                 return false;
2040         }
2041
2042
2043         GetBucketManager()->MergeBucketManager(other->GetBucketManager(), this);
2044
2045
2046         /* active + inactive == all ??? - lets hope so */
2047         for (int i = 0; i < other->GetObjectList()->GetCount(); i++)
2048         {
2049                 KX_GameObject* gameobj = (KX_GameObject*)other->GetObjectList()->GetValue(i);
2050                 MergeScene_GameObject(gameobj, this, other);
2051
2052                 /* add properties to debug list for LibLoad objects */
2053                 if (KX_GetActiveEngine()->GetAutoAddDebugProperties()) {
2054                         AddObjectDebugProperties(gameobj);
2055                 }
2056
2057                 gameobj->UpdateBuckets(false); /* only for active objects */
2058         }
2059
2060         for (int i = 0; i < other->GetInactiveList()->GetCount(); i++)
2061         {
2062                 KX_GameObject* gameobj = (KX_GameObject*)other->GetInactiveList()->GetValue(i);
2063                 MergeScene_GameObject(gameobj, this, other);
2064         }
2065
2066         GetTempObjectList()->MergeList(other->GetTempObjectList());
2067         other->GetTempObjectList()->ReleaseAndRemoveAll();
2068
2069         GetObjectList()->MergeList(other->GetObjectList());
2070         other->GetObjectList()->ReleaseAndRemoveAll();
2071
2072         GetInactiveList()->MergeList(other->GetInactiveList());
2073         other->GetInactiveList()->ReleaseAndRemoveAll();
2074
2075         GetRootParentList()->MergeList(other->GetRootParentList());
2076         other->GetRootParentList()->ReleaseAndRemoveAll();
2077
2078         GetLightList()->MergeList(other->GetLightList());
2079         other->GetLightList()->ReleaseAndRemoveAll();
2080
2081         if (env)
2082                 env->MergeEnvironment(env_other);
2083
2084         /* move materials across, assume they both use the same scene-converters
2085          * Do this after lights are merged so materials can use the lights in shaders
2086          */
2087         GetSceneConverter()->MergeScene(this, other);
2088
2089         /* merge logic */
2090         {
2091                 SCA_LogicManager *logicmgr=                     GetLogicManager();
2092                 SCA_LogicManager *logicmgr_other=       other->GetLogicManager();
2093
2094                 vector<class SCA_EventManager*>evtmgrs= logicmgr->GetEventManagers();
2095                 //vector<class SCA_EventManager*>evtmgrs_others= logicmgr_other->GetEventManagers();
2096
2097                 //SCA_EventManager *evtmgr;
2098                 SCA_EventManager *evtmgr_other;
2099
2100                 for (unsigned int i= 0; i < evtmgrs.size(); i++) {
2101                         evtmgr_other= logicmgr_other->FindEventManager(evtmgrs[i]->GetType());
2102
2103                         if (evtmgr_other) /* unlikely but possible one scene has a joystick and not the other */
2104                                 evtmgr_other->Replace_LogicManager(logicmgr);
2105
2106                         /* when merging objects sensors are moved across into the new manager, don't need to do this here */
2107                 }
2108
2109                 /* grab any timer properties from the other scene */
2110                 SCA_TimeEventManager *timemgr=          GetTimeEventManager();
2111                 SCA_TimeEventManager *timemgr_other=    other->GetTimeEventManager();
2112                 vector<CValue*> times = timemgr_other->GetTimeValues();
2113
2114                 for (unsigned int i= 0; i < times.size(); i++) {
2115                         timemgr->AddTimeProperty(times[i]);
2116                 }
2117                 
2118         }
2119         return true;
2120 }
2121
2122 void KX_Scene::Update2DFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text)
2123 {
2124         m_filtermanager.EnableFilter(propNames, gameObj, filtermode, pass, text);
2125 }
2126
2127 void KX_Scene::Render2DFilters(RAS_ICanvas* canvas)
2128 {
2129         m_filtermanager.RenderFilters(canvas);
2130 }
2131
2132 #ifdef WITH_PYTHON
2133
2134 void KX_Scene::RunDrawingCallbacks(PyObject *cb_list)
2135 {
2136         if (!cb_list || PyList_GET_SIZE(cb_list) == 0)
2137                 return;
2138
2139         RunPythonCallBackList(cb_list, NULL, 0, 0);
2140 }
2141
2142 //----------------------------------------------------------------------------
2143 //Python
2144
2145 PyTypeObject KX_Scene::Type = {
2146         PyVarObject_HEAD_INIT(NULL, 0)
2147         "KX_Scene",
2148         sizeof(PyObjectPlus_Proxy),
2149         0,
2150         py_base_dealloc,
2151         0,
2152         0,
2153         0,
2154         0,
2155         py_base_repr,
2156         0,
2157         &Sequence,
2158         &Mapping,
2159         0,0,0,0,0,0,
2160         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2161         0,0,0,0,0,0,0,
2162         Methods,
2163         0,
2164         0,
2165         &CValue::Type,
2166         0,0,0,0,0,0,
2167         py_base_new
2168 };
2169
2170 PyMethodDef KX_Scene::Methods[] = {
2171         KX_PYMETHODTABLE(KX_Scene, addObject),
2172         KX_PYMETHODTABLE(KX_Scene, end),
2173         KX_PYMETHODTABLE(KX_Scene, restart),
2174         KX_PYMETHODTABLE(KX_Scene, replace),
2175         KX_PYMETHODTABLE(KX_Scene, suspend),
2176         KX_PYMETHODTABLE(KX_Scene, resume),
2177         KX_PYMETHODTABLE(KX_Scene, drawObstacleSimulation),
2178
2179         
2180         /* dict style access */
2181         KX_PYMETHODTABLE(KX_Scene, get),
2182         
2183         {NULL,NULL} //Sentinel
2184 };
2185 static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
2186 {
2187         KX_Scene* self = static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
2188         const char *attr_str= _PyUnicode_AsString(item);
2189         PyObject *pyconvert;
2190         
2191         if (self == NULL) {
2192                 PyErr_SetString(PyExc_SystemError, "val = scene[key]: KX_Scene, " BGE_PROXY_ERROR_MSG);
2193                 return NULL;
2194         }
2195
2196         if (!self->m_attr_dict)
2197                 self->m_attr_dict = PyDict_New();
2198         
2199         if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
2200                 
2201                 if (attr_str)
2202                         PyErr_Clear();
2203                 Py_INCREF(pyconvert);
2204                 return pyconvert;
2205         }
2206         else {
2207                 if (attr_str)   PyErr_Format(PyExc_KeyError, "value = scene[key]: KX_Scene, key \"%s\" does not exist", attr_str);
2208                 else                    PyErr_SetString(PyExc_KeyError, "value = scene[key]: KX_Scene, key does not exist");
2209                 return NULL;
2210         }
2211                 
2212 }
2213
2214 static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
2215 {
2216         KX_Scene* self = static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
2217         const char *attr_str= _PyUnicode_AsString(key);
2218         if (attr_str==NULL)
2219                 PyErr_Clear();
2220         
2221         if (self == NULL) {
2222                 PyErr_SetString(PyExc_SystemError, "scene[key] = value: KX_Scene, " BGE_PROXY_ERROR_MSG);
2223                 return -1;
2224         }
2225
2226         if (!self->m_attr_dict)
2227                 self->m_attr_dict = PyDict_New();
2228
2229         if (val==NULL) { /* del ob["key"] */
2230                 int del= 0;
2231                 
2232                 if (self->m_attr_dict)
2233                         del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
2234                 
2235                 if (del==0) {
2236                         if (attr_str)   PyErr_Format(PyExc_KeyError, "scene[key] = value: KX_Scene, key \"%s\" could not be set", attr_str);
2237                         else                    PyErr_SetString(PyExc_KeyError, "del scene[key]: KX_Scene, key could not be deleted");
2238                         return -1;
2239                 }
2240                 else if (self->m_attr_dict) {
2241                         PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
2242                 }
2243         }
2244         else { /* ob["key"] = value */
2245                 int set = 0;
2246
2247                 if (self->m_attr_dict==NULL) /* lazy init */
2248                         self->m_attr_dict= PyDict_New();
2249                 
2250                 
2251                 if (PyDict_SetItem(self->m_attr_dict, key, val)==0)
2252                         set= 1;
2253                 else
2254                         PyErr_SetString(PyExc_KeyError, "scene[key] = value: KX_Scene, key not be added to internal dictionary");
2255         
2256                 if (set==0)
2257                         return -1; /* pythons error value */
2258                 
2259         }
2260         
2261         return 0; /* success */
2262 }
2263
2264 static int Seq_Contains(PyObject *self_v, PyObject *value)
2265 {
2266         KX_Scene* self = static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
2267         
2268         if (self == NULL) {
2269                 PyErr_SetString(PyExc_SystemError, "val in scene: KX_Scene, " BGE_PROXY_ERROR_MSG);
2270                 return -1;
2271         }
2272
2273         if (!self->m_attr_dict)
2274                 self->m_attr_dict = PyDict_New();
2275
2276         if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
2277                 return 1;
2278         
2279         return 0;
2280 }
2281
2282 PyMappingMethods KX_Scene::Mapping = {
2283         (lenfunc)NULL,                  /* inquiry mp_length */
2284         (binaryfunc)Map_GetItem,        /* binaryfunc mp_subscript */
2285         (objobjargproc)Map_SetItem,     /* objobjargproc mp_ass_subscript */
2286 };
2287
2288 PySequenceMethods KX_Scene::Sequence = {
2289         NULL,                       /* Cant set the len otherwise it can evaluate as false */
2290         NULL,                       /* sq_concat */
2291         NULL,                       /* sq_repeat */
2292         NULL,                       /* sq_item */
2293         NULL,                       /* sq_slice */
2294         NULL,                       /* sq_ass_item */
2295         NULL,                       /* sq_ass_slice */
2296         (objobjproc)Seq_Contains,   /* sq_contains */
2297         (binaryfunc) NULL,          /* sq_inplace_concat */
2298         (ssizeargfunc) NULL,        /* sq_inplace_repeat */
2299 };
2300
2301 PyObject *KX_Scene::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2302 {
2303         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2304         return PyUnicode_From_STR_String(self->GetName());
2305 }
2306
2307 PyObject *KX_Scene::pyattr_get_objects(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2308 {
2309         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2310         return self->GetObjectList()->GetProxy();
2311 }
2312
2313 PyObject *KX_Scene::pyattr_get_objects_inactive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2314 {
2315         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2316         return self->GetInactiveList()->GetProxy();
2317 }
2318
2319 PyObject *KX_Scene::pyattr_get_lights(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2320 {
2321         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2322         return self->GetLightList()->GetProxy();
2323 }
2324
2325 PyObject *KX_Scene::pyattr_get_world(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2326 {
2327         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2328         KX_WorldInfo *world = self->GetWorldInfo();
2329
2330         if (world->GetName() != "") {
2331                 return world->GetProxy();
2332         }
2333         else {
2334                 Py_RETURN_NONE;
2335         }
2336 }
2337
2338 PyObject *KX_Scene::pyattr_get_cameras(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2339 {
2340         /* With refcounts in this case...
2341          * the new CListValue is owned by python, so its possible python holds onto it longer then the BGE
2342          * however this is the same with "scene.objects + []", when you make a copy by adding lists.
2343          */
2344         
2345         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2346         CListValue* clist = new CListValue();
2347         
2348         /* return self->GetCameras()->GetProxy(); */
2349         
2350         list<KX_Camera*>::iterator it = self->GetCameras()->begin();
2351         while (it != self->GetCameras()->end()) {
2352                 clist->Add((*it)->AddRef());
2353                 it++;
2354         }
2355         
2356         return clist->NewProxy(true);
2357 }
2358
2359 PyObject *KX_Scene::pyattr_get_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2360 {
2361         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2362         KX_Camera* cam= self->GetActiveCamera();
2363         if (cam)
2364                 return self->GetActiveCamera()->GetProxy();
2365         else
2366                 Py_RETURN_NONE;
2367 }
2368
2369
2370 int KX_Scene::pyattr_set_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2371 {
2372         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2373         KX_Camera *camOb;
2374         
2375         if (!ConvertPythonToCamera(value, &camOb, false, "scene.active_camera = value: KX_Scene"))
2376                 return PY_SET_ATTR_FAIL;
2377         
2378         self->SetActiveCamera(camOb);
2379         return PY_SET_ATTR_SUCCESS;
2380 }
2381
2382 PyObject *KX_Scene::pyattr_get_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2383 {
2384         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2385
2386         if (self->m_draw_call_pre==NULL)
2387                 self->m_draw_call_pre= PyList_New(0);
2388         Py_INCREF(self->m_draw_call_pre);
2389         return self->m_draw_call_pre;
2390 }
2391
2392 PyObject *KX_Scene::pyattr_get_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2393 {
2394         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2395
2396         if (self->m_draw_call_post==NULL)
2397                 self->m_draw_call_post= PyList_New(0);
2398         Py_INCREF(self->m_draw_call_post);
2399         return self->m_draw_call_post;
2400 }
2401
2402 int KX_Scene::pyattr_set_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2403 {
2404         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2405
2406         if (!PyList_CheckExact(value))
2407         {
2408                 PyErr_SetString(PyExc_ValueError, "Expected a list");
2409                 return PY_SET_ATTR_FAIL;
2410         }
2411         Py_XDECREF(self->m_draw_call_pre);
2412
2413         Py_INCREF(value);
2414         self->m_draw_call_pre = value;
2415
2416         return PY_SET_ATTR_SUCCESS;
2417 }
2418
2419 int KX_Scene::pyattr_set_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2420 {
2421         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2422
2423         if (!PyList_CheckExact(value))
2424         {
2425                 PyErr_SetString(PyExc_ValueError, "Expected a list");
2426                 return PY_SET_ATTR_FAIL;
2427         }
2428         Py_XDECREF(self->m_draw_call_post);
2429
2430         Py_INCREF(value);
2431         self->m_draw_call_post = value;
2432
2433         return PY_SET_ATTR_SUCCESS;
2434 }
2435
2436 PyObject *KX_Scene::pyattr_get_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2437 {
2438         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2439
2440         return PyObjectFrom(self->GetGravity());
2441 }
2442
2443 int KX_Scene::pyattr_set_gravity(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2444 {
2445         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2446
2447         MT_Vector3 vec;
2448         if (!PyVecTo(value, vec))
2449                 return PY_SET_ATTR_FAIL;
2450
2451         self->SetGravity(vec);
2452         return PY_SET_ATTR_SUCCESS;
2453 }
2454
2455 PyAttributeDef KX_Scene::Attributes[] = {
2456         KX_PYATTRIBUTE_RO_FUNCTION("name",                              KX_Scene, pyattr_get_name),
2457         KX_PYATTRIBUTE_RO_FUNCTION("objects",                   KX_Scene, pyattr_get_objects),
2458         KX_PYATTRIBUTE_RO_FUNCTION("objectsInactive",   KX_Scene, pyattr_get_objects_inactive),
2459         KX_PYATTRIBUTE_RO_FUNCTION("lights",                    KX_Scene, pyattr_get_lights),
2460         KX_PYATTRIBUTE_RO_FUNCTION("cameras",                   KX_Scene, pyattr_get_cameras),
2461         KX_PYATTRIBUTE_RO_FUNCTION("world",                             KX_Scene, pyattr_get_world),
2462         KX_PYATTRIBUTE_RW_FUNCTION("active_camera",             KX_Scene, pyattr_get_active_camera, pyattr_set_active_camera),
2463         KX_PYATTRIBUTE_RW_FUNCTION("pre_draw",                  KX_Scene, pyattr_get_drawing_callback_pre, pyattr_set_drawing_callback_pre),
2464         KX_PYATTRIBUTE_RW_FUNCTION("post_draw",                 KX_Scene, pyattr_get_drawing_callback_post, pyattr_set_drawing_callback_post),
2465         KX_PYATTRIBUTE_RW_FUNCTION("gravity",                   KX_Scene, pyattr_get_gravity, pyattr_set_gravity),
2466         KX_PYATTRIBUTE_BOOL_RO("suspended",                             KX_Scene, m_suspend),
2467         KX_PYATTRIBUTE_BOOL_RO("activity_culling",              KX_Scene, m_activity_culling),
2468         KX_PYATTRIBUTE_FLOAT_RW("activity_culling_radius", 0.5f, FLT_MAX, KX_Scene, m_activity_box_radius),
2469         KX_PYATTRIBUTE_BOOL_RO("dbvt_culling",                  KX_Scene, m_dbvt_culling),
2470         { NULL }        //Sentinel
2471 };
2472
2473 KX_PYMETHODDEF_DOC(KX_Scene, addObject,
2474 "addObject(object, other, time=0)\n"
2475 "Returns the added object.\n")
2476 {
2477         PyObject *pyob, *pyreference;
2478         KX_GameObject *ob, *reference;
2479
2480         int time = 0;
2481
2482         if (!PyArg_ParseTuple(args, "OO|i:addObject", &pyob, &pyreference, &time))
2483                 return NULL;
2484
2485         if (    !ConvertPythonToGameObject(pyob, &ob, false, "scene.addObject(object, reference, time): KX_Scene (first argument)") ||
2486                         !ConvertPythonToGameObject(pyreference, &reference, false, "scene.addObject(object, reference, time): KX_Scene (second argument)") )
2487                 return NULL;
2488
2489         if (!m_inactivelist->SearchValue(ob)) {
2490                 PyErr_Format(PyExc_ValueError, "scene.addObject(object, reference, time): KX_Scene (first argument): object must be in an inactive layer");
2491                 return NULL;
2492         }
2493         SCA_IObject* replica = AddReplicaObject((SCA_IObject*)ob, reference, time);
2494         
2495         // release here because AddReplicaObject AddRef's
2496         // the object is added to the scene so we don't want python to own a reference
2497         replica->Release();
2498         return replica->GetProxy();
2499 }
2500
2501 KX_PYMETHODDEF_DOC(KX_Scene, end,
2502 "end()\n"
2503 "Removes this scene from the game.\n")
2504 {
2505         
2506         KX_GetActiveEngine()->RemoveScene(m_sceneName);
2507         
2508         Py_RETURN_NONE;
2509 }
2510
2511 KX_PYMETHODDEF_DOC(KX_Scene, restart,
2512                                    "restart()\n"
2513                                    "Restarts this scene.\n")
2514 {
2515         KX_GetActiveEngine()->ReplaceScene(m_sceneName, m_sceneName);
2516         
2517         Py_RETURN_NONE;
2518 }
2519
2520 KX_PYMETHODDEF_DOC(KX_Scene, replace,
2521                                    "replace(newScene)\n"
2522                    "Replaces this scene with another one.\n"
2523                    "Return True if the new scene exists and scheduled for replacement, False otherwise.\n")
2524 {
2525         char* name;
2526         
2527         if (!PyArg_ParseTuple(args, "s:replace", &name))
2528                 return NULL;
2529         
2530     if (KX_GetActiveEngine()->ReplaceScene(m_sceneName, name))
2531         Py_RETURN_TRUE;
2532         
2533     Py_RETURN_FALSE;
2534 }
2535
2536 KX_PYMETHODDEF_DOC(KX_Scene, suspend,
2537                                         "suspend()\n"
2538                                         "Suspends this scene.\n")
2539 {
2540         Suspend();
2541         
2542         Py_RETURN_NONE;
2543 }
2544
2545 KX_PYMETHODDEF_DOC(KX_Scene, resume,
2546                                         "resume()\n"
2547                                         "Resumes this scene.\n")
2548 {
2549         Resume();
2550         
2551         Py_RETURN_NONE;
2552 }
2553
2554 KX_PYMETHODDEF_DOC(KX_Scene, drawObstacleSimulation,
2555                                    "drawObstacleSimulation()\n"
2556                                    "Draw debug visualization of obstacle simulation.\n")
2557 {
2558         if (GetObstacleSimulation())
2559                 GetObstacleSimulation()->DrawObstacles();
2560
2561         Py_RETURN_NONE;
2562 }
2563
2564 /* Matches python dict.get(key, [default]) */
2565 KX_PYMETHODDEF_DOC(KX_Scene, get, "")
2566 {
2567         PyObject *key;
2568         PyObject *def = Py_None;
2569         PyObject *ret;
2570
2571         if (!PyArg_ParseTuple(args, "O|O:get", &key, &def))
2572                 return NULL;
2573         
2574         if (m_attr_dict && (ret=PyDict_GetItem(m_attr_dict, key))) {
2575                 Py_INCREF(ret);
2576                 return ret;
2577         }
2578         
2579         Py_INCREF(def);
2580         return def;
2581 }
2582
2583 #endif // WITH_PYTHON