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