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