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