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