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