copy of docs from 2.4x for python modules that have been kept
[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                                 if (bHasModifier || bHasShapeKey || bHasDvert || bHasArmature) {
1110                                         std::cout << "warning: ReplaceMesh() new mesh is not used in an object from the current scene, you will get incorrect behavior" << std::endl;
1111                                         bHasShapeKey= bHasDvert= bHasArmature=bHasModifier= false;
1112                                 }
1113                         }
1114                         
1115                         if (bHasModifier)
1116                         {
1117                                 BL_ModifierDeformer* modifierDeformer;
1118                                 if (bHasShapeKey || bHasArmature)
1119                                 {
1120                                         modifierDeformer = new BL_ModifierDeformer(
1121                                                 newobj,
1122                                                 m_blenderScene,
1123                                                 oldblendobj, blendobj,
1124                                                 mesh,
1125                                                 true,
1126                                                 static_cast<BL_ArmatureObject*>( parentobj )
1127                                         );
1128                                         releaseParent= false;
1129                                         modifierDeformer->LoadShapeDrivers(blendobj->parent);
1130                                 }
1131                                 else
1132                                 {
1133                                         modifierDeformer = new BL_ModifierDeformer(
1134                                                 newobj,
1135                                                 m_blenderScene,
1136                                                 oldblendobj, blendobj,
1137                                                 mesh,
1138                                                 false,
1139                                                 NULL
1140                                         );
1141                                 }
1142                                 newobj->SetDeformer(modifierDeformer);
1143                         } 
1144                         else    if (bHasShapeKey)
1145                         {
1146                                 BL_ShapeDeformer* shapeDeformer;
1147                                 if (bHasArmature) 
1148                                 {
1149                                         shapeDeformer = new BL_ShapeDeformer(
1150                                                 newobj,
1151                                                 oldblendobj, blendobj,
1152                                                 mesh,
1153                                                 true,
1154                                                 true,
1155                                                 static_cast<BL_ArmatureObject*>( parentobj )
1156                                         );
1157                                         releaseParent= false;
1158                                         shapeDeformer->LoadShapeDrivers(blendobj->parent);
1159                                 }
1160                                 else
1161                                 {
1162                                         shapeDeformer = new BL_ShapeDeformer(
1163                                                 newobj,
1164                                                 oldblendobj, blendobj,
1165                                                 mesh,
1166                                                 false,
1167                                                 true,
1168                                                 NULL
1169                                         );
1170                                 }
1171                                 newobj->SetDeformer( shapeDeformer);
1172                         }
1173                         else if (bHasArmature) 
1174                         {
1175                                 BL_SkinDeformer* skinDeformer = new BL_SkinDeformer(
1176                                         newobj,
1177                                         oldblendobj, blendobj,
1178                                         mesh,
1179                                         true,
1180                                         true,
1181                                         static_cast<BL_ArmatureObject*>( parentobj )
1182                                 );
1183                                 releaseParent= false;
1184                                 newobj->SetDeformer(skinDeformer);
1185                         }
1186                         else if (bHasDvert)
1187                         {
1188                                 BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
1189                                         newobj, oldblendobj, mesh
1190                                 );
1191                                 newobj->SetDeformer(meshdeformer);
1192                         }
1193                         else if (bHasSoftBody)
1194                         {
1195                                 KX_SoftBodyDeformer *softdeformer = new KX_SoftBodyDeformer(mesh, newobj);
1196                                 newobj->SetDeformer(softdeformer);
1197                         }
1198
1199                         // release parent reference if its not being used 
1200                         if( releaseParent && parentobj)
1201                                 parentobj->Release();
1202                 }
1203         }
1204
1205         gameobj->AddMeshUser();
1206         }
1207         
1208         if(use_phys) { /* update the new assigned mesh with the physics mesh */
1209                 KX_ReInstanceBulletShapeFromMesh(gameobj, NULL, use_gfx?NULL:mesh);
1210         }
1211 }
1212
1213 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
1214 {
1215         list<KX_Camera*>::iterator it = m_cameras.begin();
1216
1217         while ( (it != m_cameras.end()) 
1218                         && ((*it) != cam) ) {
1219           it++;
1220         }
1221
1222         return ((it == m_cameras.end()) ? NULL : (*it));
1223 }
1224
1225
1226 KX_Camera* KX_Scene::FindCamera(STR_String& name)
1227 {
1228         list<KX_Camera*>::iterator it = m_cameras.begin();
1229
1230         while ( (it != m_cameras.end()) 
1231                         && ((*it)->GetName() != name) ) {
1232           it++;
1233         }
1234
1235         return ((it == m_cameras.end()) ? NULL : (*it));
1236 }
1237
1238 void KX_Scene::AddCamera(KX_Camera* cam)
1239 {
1240         if (!FindCamera(cam))
1241                 m_cameras.push_back(cam);
1242 }
1243
1244
1245 KX_Camera* KX_Scene::GetActiveCamera()
1246 {       
1247         // NULL if not defined
1248         return m_active_camera;
1249 }
1250
1251
1252 void KX_Scene::SetActiveCamera(KX_Camera* cam)
1253 {
1254         // only set if the cam is in the active list? Or add it otherwise?
1255         if (!FindCamera(cam)){
1256                 AddCamera(cam);
1257                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1258         } 
1259
1260         m_active_camera = cam;
1261 }
1262
1263 void KX_Scene::SetCameraOnTop(KX_Camera* cam)
1264 {
1265         if (!FindCamera(cam)){
1266                 // adding is always done at the back, so that's all that needs to be done
1267                 AddCamera(cam);
1268                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1269         } else {
1270                 m_cameras.remove(cam);
1271                 m_cameras.push_back(cam);
1272         }
1273 }
1274
1275
1276 void KX_Scene::UpdateMeshTransformations()
1277 {
1278         // do this incrementally in the future
1279         for (int i = 0; i < m_objectlist->GetCount(); i++)
1280         {
1281                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
1282                 gameobj->GetOpenGLMatrix();
1283         }
1284 }
1285
1286 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam, int layer)
1287 {
1288         int intersect = KX_Camera::INTERSECT;
1289         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
1290         bool visible = (gameobj && gameobj->GetVisible() && (!layer || (gameobj->GetLayer() & layer)));
1291         bool dotest = visible || node->Left() || node->Right();
1292
1293         /* If the camera is inside the box, assume intersect. */
1294         if (dotest && !node->inside( cam->NodeGetWorldPosition()))
1295         {
1296                 MT_Scalar radius = node->Radius();
1297                 MT_Point3 center = node->Center();
1298                 
1299                 intersect =  cam->SphereInsideFrustum(center, radius); 
1300                 
1301                 if (intersect == KX_Camera::INTERSECT)
1302                 {
1303                         MT_Point3 box[8];
1304                         node->get(box);
1305                         intersect = cam->BoxInsideFrustum(box);
1306                 }
1307         }
1308
1309         switch (intersect)
1310         {
1311                 case KX_Camera::OUTSIDE:
1312                         MarkSubTreeVisible(node, rasty, false, cam);
1313                         break;
1314                 case KX_Camera::INTERSECT:
1315                         if (gameobj)
1316                                 MarkVisible(rasty, gameobj, cam, layer);
1317                         if (node->Left())
1318                                 MarkVisible(node->Left(), rasty, cam, layer);
1319                         if (node->Right())
1320                                 MarkVisible(node->Right(), rasty, cam, layer);
1321                         break;
1322                 case KX_Camera::INSIDE:
1323                         MarkSubTreeVisible(node, rasty, true, cam, layer);
1324                         break;
1325         }
1326 }
1327
1328 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera* cam, int layer)
1329 {
1330         if (node->Client())
1331         {
1332                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
1333                 if (gameobj->GetVisible())
1334                 {
1335                         if (visible)
1336                         {
1337                                 int nummeshes = gameobj->GetMeshCount();
1338                                 
1339                                 // this adds the vertices to the display list
1340                                 for (int m=0;m<nummeshes;m++)
1341                                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1342                         }
1343
1344                         gameobj->SetCulled(!visible);
1345                         gameobj->UpdateBuckets(false);
1346                 }
1347         }
1348         if (node->Left())
1349                 MarkSubTreeVisible(node->Left(), rasty, visible, cam, layer);
1350         if (node->Right())
1351                 MarkSubTreeVisible(node->Right(), rasty, visible, cam, layer);
1352 }
1353
1354 void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera*  cam,int layer)
1355 {
1356         // User (Python/Actuator) has forced object invisible...
1357         if (!gameobj->GetSGNode() || !gameobj->GetVisible())
1358                 return;
1359         
1360         // Shadow lamp layers
1361         if(layer && !(gameobj->GetLayer() & layer)) {
1362                 gameobj->SetCulled(true);
1363                 gameobj->UpdateBuckets(false);
1364                 return;
1365         }
1366
1367         // If Frustum culling is off, the object is always visible.
1368         bool vis = !cam->GetFrustumCulling();
1369         
1370         // If the camera is inside this node, then the object is visible.
1371         if (!vis)
1372         {
1373                 vis = gameobj->GetSGNode()->inside( cam->GetCameraLocation() );
1374         }
1375                 
1376         // Test the object's bound sphere against the view frustum.
1377         if (!vis)
1378         {
1379                 MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
1380                 MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
1381                 switch (cam->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
1382                 {
1383                         case KX_Camera::INSIDE:
1384                                 vis = true;
1385                                 break;
1386                         case KX_Camera::OUTSIDE:
1387                                 vis = false;
1388                                 break;
1389                         case KX_Camera::INTERSECT:
1390                                 // Test the object's bound box against the view frustum.
1391                                 MT_Point3 box[8];
1392                                 gameobj->GetSGNode()->getBBox(box); 
1393                                 vis = cam->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
1394                                 break;
1395                 }
1396         }
1397         
1398         if (vis)
1399         {
1400                 int nummeshes = gameobj->GetMeshCount();
1401                 
1402                 for (int m=0;m<nummeshes;m++)
1403                 {
1404                         // this adds the vertices to the display list
1405                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1406                 }
1407                 // Visibility/ non-visibility are marked
1408                 // elsewhere now.
1409                 gameobj->SetCulled(false);
1410                 gameobj->UpdateBuckets(false);
1411         } else {
1412                 gameobj->SetCulled(true);
1413                 gameobj->UpdateBuckets(false);
1414         }
1415 }
1416
1417 void KX_Scene::PhysicsCullingCallback(KX_ClientObjectInfo* objectInfo, void* cullingInfo)
1418 {
1419         KX_GameObject* gameobj = objectInfo->m_gameobject;
1420         if (!gameobj->GetVisible())
1421                 // ideally, invisible objects should be removed from the culling tree temporarily
1422                 return;
1423         if(((CullingInfo*)cullingInfo)->m_layer && !(gameobj->GetLayer() & ((CullingInfo*)cullingInfo)->m_layer))
1424                 // used for shadow: object is not in shadow layer
1425                 return;
1426
1427         // make object visible
1428         gameobj->SetCulled(false);
1429         gameobj->UpdateBuckets(false);
1430 }
1431
1432 void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam, int layer)
1433 {
1434         bool dbvt_culling = false;
1435         if (m_dbvt_culling) 
1436         {
1437                 // test culling through Bullet
1438                 PHY__Vector4 planes[6];
1439                 // get the clip planes
1440                 MT_Vector4* cplanes = cam->GetNormalizedClipPlanes();
1441                 // and convert
1442                 planes[0].setValue(cplanes[4].getValue());      // near
1443                 planes[1].setValue(cplanes[5].getValue());      // far
1444                 planes[2].setValue(cplanes[0].getValue());      // left
1445                 planes[3].setValue(cplanes[1].getValue());      // right
1446                 planes[4].setValue(cplanes[2].getValue());      // top
1447                 planes[5].setValue(cplanes[3].getValue());      // bottom
1448                 CullingInfo info(layer);
1449                 dbvt_culling = m_physicsEnvironment->cullingTest(PhysicsCullingCallback,&info,planes,5,m_dbvt_occlusion_res);
1450         }
1451         if (!dbvt_culling) {
1452                 // the physics engine couldn't help us, do it the hard way
1453                 for (int i = 0; i < m_objectlist->GetCount(); i++)
1454                 {
1455                         MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)), cam, layer);
1456                 }
1457         }
1458 }
1459
1460 // logic stuff
1461 void KX_Scene::LogicBeginFrame(double curtime)
1462 {
1463         // have a look at temp objects ...
1464         int lastobj = m_tempObjectList->GetCount() - 1;
1465         
1466         for (int i = lastobj; i >= 0; i--)
1467         {
1468                 CValue* objval = m_tempObjectList->GetValue(i);
1469                 CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
1470                 
1471                 if (propval)
1472                 {
1473                         float timeleft = propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate();
1474                         
1475                         if (timeleft > 0)
1476                         {
1477                                 propval->SetFloat(timeleft);
1478                         }
1479                         else
1480                         {
1481                                 DelayedRemoveObject(objval);
1482                                 // remove obj
1483                         }
1484                 }
1485                 else
1486                 {
1487                         // all object is the tempObjectList should have a clock
1488                 }
1489         }
1490         m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate());
1491 }
1492
1493
1494
1495 void KX_Scene::LogicUpdateFrame(double curtime, bool frame)
1496 {
1497         m_logicmgr->UpdateFrame(curtime, frame);
1498 }
1499
1500
1501
1502 void KX_Scene::LogicEndFrame()
1503 {
1504         m_logicmgr->EndFrame();
1505         int numobj = m_euthanasyobjects->GetCount();
1506
1507         KX_GameObject* obj;
1508
1509         while ((numobj = m_euthanasyobjects->GetCount()) > 0)
1510         {
1511                 // remove the object from this list to make sure we will not hit it again
1512                 obj = (KX_GameObject*)m_euthanasyobjects->GetValue(numobj-1);
1513                 m_euthanasyobjects->Remove(numobj-1);
1514                 obj->Release();
1515                 RemoveObject(obj);
1516         }
1517 }
1518
1519
1520
1521 /**
1522   * UpdateParents: SceneGraph transformation update.
1523   */
1524 void KX_Scene::UpdateParents(double curtime)
1525 {
1526         // we use the SG dynamic list
1527         SG_Node* node;
1528
1529         while ((node = SG_Node::GetNextScheduled(m_sghead)) != NULL)
1530         {
1531                 node->UpdateWorldData(curtime);
1532         }
1533
1534         //for (int i=0; i<GetRootParentList()->GetCount(); i++)
1535         //{
1536         //      KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
1537         //      parentobj->NodeUpdateGS(curtime);
1538         //}
1539
1540         // the list must be empty here
1541         assert(m_sghead.Empty());
1542         // some nodes may be ready for reschedule, move them to schedule list for next time
1543         while ((node = SG_Node::GetNextRescheduled(m_sghead)) != NULL)
1544         {
1545                 node->Schedule(m_sghead);
1546         }
1547 }
1548
1549
1550 RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat, bool &bucketCreated)
1551 {
1552         return m_bucketmanager->FindBucket(polymat, bucketCreated);
1553 }
1554
1555
1556
1557 void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
1558                                                          class RAS_IRasterizer* rasty,
1559                                                          class RAS_IRenderTools* rendertools)
1560 {
1561         m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
1562         KX_BlenderMaterial::EndFrame();
1563 }
1564
1565 void KX_Scene::UpdateObjectActivity(void) 
1566 {
1567         if (m_activity_culling) {
1568                 /* determine the activity criterium and set objects accordingly */
1569                 int i=0;
1570                 
1571                 MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
1572                 
1573                 for (i=0;i<GetObjectList()->GetCount();i++)
1574                 {
1575                         KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
1576                         
1577                         if (!ob->GetIgnoreActivityCulling()) {
1578                                 /* Simple test: more than 10 away from the camera, count
1579                                  * Manhattan distance. */
1580                                 MT_Point3 obpos = ob->NodeGetWorldPosition();
1581                                 
1582                                 if ( (fabs(camloc[0] - obpos[0]) > m_activity_box_radius)
1583                                          || (fabs(camloc[1] - obpos[1]) > m_activity_box_radius)
1584                                          || (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
1585                                 {                       
1586                                         ob->Suspend();
1587                                 } else {
1588                                         ob->Resume();
1589                                 }
1590                         }
1591                 }               
1592         }
1593 }
1594
1595 void KX_Scene::SetActivityCullingRadius(float f)
1596 {
1597         if (f < 0.5)
1598                 f = 0.5;
1599         m_activity_box_radius = f;
1600 }
1601         
1602 NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
1603 {
1604         return m_networkDeviceInterface;
1605 }
1606
1607 NG_NetworkScene* KX_Scene::GetNetworkScene()
1608 {
1609         return m_networkScene;
1610 }
1611
1612 void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
1613 {
1614         m_networkDeviceInterface = newInterface;
1615 }
1616
1617 void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
1618 {
1619         m_networkScene = newScene;
1620 }
1621
1622
1623 void    KX_Scene::SetGravity(const MT_Vector3& gravity)
1624 {
1625         GetPhysicsEnvironment()->setGravity(gravity[0],gravity[1],gravity[2]);
1626 }
1627
1628 void KX_Scene::SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter)
1629 {
1630         m_sceneConverter = sceneConverter;
1631 }
1632
1633 void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
1634 {
1635         m_physicsEnvironment = physEnv;
1636         if(m_physicsEnvironment) {
1637                 KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, physEnv);
1638                 m_logicmgr->RegisterEventManager(touchmgr);
1639         }
1640 }
1641  
1642 void KX_Scene::setSuspendedTime(double suspendedtime)
1643 {
1644         m_suspendedtime = suspendedtime;
1645 }
1646 double KX_Scene::getSuspendedTime()
1647 {
1648         return m_suspendedtime;
1649 }
1650 void KX_Scene::setSuspendedDelta(double suspendeddelta)
1651 {
1652         m_suspendeddelta = suspendeddelta;
1653 }
1654 double KX_Scene::getSuspendedDelta()
1655 {
1656         return m_suspendeddelta;
1657 }
1658
1659 #ifndef DISABLE_PYTHON
1660
1661
1662 #include "KX_BulletPhysicsController.h"
1663
1664 static void MergeScene_LogicBrick(SCA_ILogicBrick* brick, KX_Scene *to)
1665 {
1666         SCA_LogicManager *logicmgr= to->GetLogicManager();
1667
1668         brick->Replace_IScene(to);
1669         brick->Replace_NetworkScene(to->GetNetworkScene());
1670
1671         SCA_ISensor *sensor=  dynamic_cast<class SCA_ISensor *>(brick);
1672         if(sensor) {
1673                 sensor->Replace_EventManager(logicmgr);
1674         }
1675
1676         /* near sensors have physics controllers */
1677         KX_TouchSensor *touch_sensor = dynamic_cast<class KX_TouchSensor *>(brick);
1678         if(touch_sensor) {
1679                 touch_sensor->GetPhysicsController()->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1680         }
1681 }
1682
1683 #include "CcdGraphicController.h" // XXX  ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1684 #include "CcdPhysicsEnvironment.h" // XXX  ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1685 #include "KX_BulletPhysicsController.h"
1686
1687
1688 static void MergeScene_GameObject(KX_GameObject* gameobj, KX_Scene *to, KX_Scene *from)
1689 {
1690         {
1691                 SCA_ActuatorList& actuators= gameobj->GetActuators();
1692                 SCA_ActuatorList::iterator ita;
1693
1694                 for (ita = actuators.begin(); !(ita==actuators.end()); ++ita)
1695                 {
1696                         MergeScene_LogicBrick(*ita, to);
1697                 }
1698         }
1699
1700
1701         {
1702                 SCA_SensorList& sensors= gameobj->GetSensors();
1703                 SCA_SensorList::iterator its;
1704
1705                 for (its = sensors.begin(); !(its==sensors.end()); ++its)
1706                 {
1707                         MergeScene_LogicBrick(*its, to);
1708                 }
1709         }
1710
1711         {
1712                 SCA_ControllerList& controllers= gameobj->GetControllers();
1713                 SCA_ControllerList::iterator itc;
1714
1715                 for (itc = controllers.begin(); !(itc==controllers.end()); ++itc)
1716                 {
1717                         SCA_IController *cont= *itc;
1718                         MergeScene_LogicBrick(cont, to);
1719
1720                         vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
1721                         vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
1722
1723                         for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());++ita) {
1724                                 MergeScene_LogicBrick(*ita, to);
1725                         }
1726
1727                         for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());++its) {
1728                                 MergeScene_LogicBrick(*its, to);
1729                         }
1730                 }
1731         }
1732
1733         /* graphics controller */
1734         PHY_IGraphicController *ctrl = gameobj->GetGraphicController();
1735         if(ctrl) {
1736                 /* SHOULD update the m_cullingTree */
1737                 ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1738         }
1739
1740         /* SG_Node can hold a scene reference */
1741         SG_Node *sg= gameobj->GetSGNode();
1742         if(sg) {
1743                 if(sg->GetSGClientInfo() == from) {
1744                         sg->SetSGClientInfo(to);
1745                 }
1746
1747                 SGControllerList::iterator contit;
1748                 SGControllerList& controllers = sg->GetSGControllerList();
1749                 for (contit = controllers.begin();contit!=controllers.end();++contit)
1750                 {
1751                         KX_BulletPhysicsController *phys_ctrl= dynamic_cast<KX_BulletPhysicsController *>(*contit);
1752                         if (phys_ctrl)
1753                                 phys_ctrl->SetPhysicsEnvironment(to->GetPhysicsEnvironment());
1754                 }
1755         }
1756 }
1757
1758 bool KX_Scene::MergeScene(KX_Scene *other)
1759 {
1760         CcdPhysicsEnvironment *env=                     dynamic_cast<CcdPhysicsEnvironment *>(this->GetPhysicsEnvironment());
1761         CcdPhysicsEnvironment *env_other=       dynamic_cast<CcdPhysicsEnvironment *>(other->GetPhysicsEnvironment());
1762
1763         if((env==NULL) != (env_other==NULL)) /* TODO - even when both scenes have NONE physics, the other is loaded with bullet enabled, ??? */
1764         {
1765                 printf("KX_Scene::MergeScene: physics scenes type differ, aborting\n");
1766                 printf("\tsource %d, terget %d\n", (int)(env!=NULL), (int)(env_other!=NULL));
1767                 return false;
1768         }
1769
1770         if(GetSceneConverter() != other->GetSceneConverter()) {
1771                 printf("KX_Scene::MergeScene: converters differ, aborting\n");
1772                 return false;
1773         }
1774
1775
1776         GetBucketManager()->MergeBucketManager(other->GetBucketManager());
1777
1778         /* move materials across, assume they both use the same scene-converters */
1779         GetSceneConverter()->MergeScene(this, other);
1780
1781         /* active + inactive == all ??? - lets hope so */
1782         for (int i = 0; i < other->GetObjectList()->GetCount(); i++)
1783         {
1784                 KX_GameObject* gameobj = (KX_GameObject*)other->GetObjectList()->GetValue(i);
1785                 MergeScene_GameObject(gameobj, this, other);
1786
1787                 gameobj->UpdateBuckets(false); /* only for active objects */
1788         }
1789
1790         for (int i = 0; i < other->GetInactiveList()->GetCount(); i++)
1791         {
1792                 KX_GameObject* gameobj = (KX_GameObject*)other->GetInactiveList()->GetValue(i);
1793                 MergeScene_GameObject(gameobj, this, other);
1794         }
1795
1796         GetTempObjectList()->MergeList(other->GetTempObjectList());
1797         other->GetTempObjectList()->ReleaseAndRemoveAll();
1798
1799         GetObjectList()->MergeList(other->GetObjectList());
1800         other->GetObjectList()->ReleaseAndRemoveAll();
1801
1802         GetInactiveList()->MergeList(other->GetInactiveList());
1803         other->GetInactiveList()->ReleaseAndRemoveAll();
1804
1805         GetRootParentList()->MergeList(other->GetRootParentList());
1806         other->GetRootParentList()->ReleaseAndRemoveAll();
1807
1808         GetLightList()->MergeList(other->GetLightList());
1809         other->GetLightList()->ReleaseAndRemoveAll();
1810
1811         if(env) /* bullet scene? - dummy scenes dont need touching */
1812                 env->MergeEnvironment(env_other);
1813
1814         /* merge logic */
1815         {
1816                 SCA_LogicManager *logicmgr=                     GetLogicManager();
1817                 SCA_LogicManager *logicmgr_other=       other->GetLogicManager();
1818
1819                 vector<class SCA_EventManager*>evtmgrs= logicmgr->GetEventManagers();
1820                 //vector<class SCA_EventManager*>evtmgrs_others= logicmgr_other->GetEventManagers();
1821
1822                 //SCA_EventManager *evtmgr;
1823                 SCA_EventManager *evtmgr_other;
1824
1825                 for(int i= 0; i < evtmgrs.size(); i++) {
1826                         evtmgr_other= logicmgr_other->FindEventManager(evtmgrs[i]->GetType());
1827
1828                         if(evtmgr_other) /* unlikely but possible one scene has a joystick and not the other */
1829                                 evtmgr_other->Replace_LogicManager(logicmgr);
1830
1831                         /* when merging objects sensors are moved across into the new manager, dont need to do this here */
1832                 }
1833         }
1834         return true;
1835 }
1836
1837 //----------------------------------------------------------------------------
1838 //Python
1839
1840 PyTypeObject KX_Scene::Type = {
1841         PyVarObject_HEAD_INIT(NULL, 0)
1842         "KX_Scene",
1843         sizeof(PyObjectPlus_Proxy),
1844         0,
1845         py_base_dealloc,
1846         0,
1847         0,
1848         0,
1849         0,
1850         py_base_repr,
1851         0,
1852         &Sequence,
1853         &Mapping,
1854         0,0,0,0,0,0,
1855         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
1856         0,0,0,0,0,0,0,
1857         Methods,
1858         0,
1859         0,
1860         &CValue::Type,
1861         0,0,0,0,0,0,
1862         py_base_new
1863 };
1864
1865 PyMethodDef KX_Scene::Methods[] = {
1866         KX_PYMETHODTABLE(KX_Scene, addObject),
1867         
1868         /* dict style access */
1869         KX_PYMETHODTABLE(KX_Scene, get),
1870         
1871         {NULL,NULL} //Sentinel
1872 };
1873 static PyObject *Map_GetItem(PyObject *self_v, PyObject *item)
1874 {
1875         KX_Scene* self= static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
1876         const char *attr_str= _PyUnicode_AsString(item);
1877         PyObject* pyconvert;
1878         
1879         if (self==NULL) {
1880                 PyErr_SetString(PyExc_SystemError, "val = scene[key]: KX_Scene, "BGE_PROXY_ERROR_MSG);
1881                 return NULL;
1882         }
1883         
1884         if (self->m_attr_dict && (pyconvert=PyDict_GetItem(self->m_attr_dict, item))) {
1885                 
1886                 if (attr_str)
1887                         PyErr_Clear();
1888                 Py_INCREF(pyconvert);
1889                 return pyconvert;
1890         }
1891         else {
1892                 if(attr_str)    PyErr_Format(PyExc_KeyError, "value = scene[key]: KX_Scene, key \"%s\" does not exist", attr_str);
1893                 else                    PyErr_SetString(PyExc_KeyError, "value = scene[key]: KX_Scene, key does not exist");
1894                 return NULL;
1895         }
1896                 
1897 }
1898
1899 static int Map_SetItem(PyObject *self_v, PyObject *key, PyObject *val)
1900 {
1901         KX_Scene* self= static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
1902         const char *attr_str= _PyUnicode_AsString(key);
1903         if(attr_str==NULL)
1904                 PyErr_Clear();
1905         
1906         if (self==NULL) {
1907                 PyErr_SetString(PyExc_SystemError, "scene[key] = value: KX_Scene, "BGE_PROXY_ERROR_MSG);
1908                 return -1;
1909         }
1910         
1911         if (val==NULL) { /* del ob["key"] */
1912                 int del= 0;
1913                 
1914                 if(self->m_attr_dict)
1915                         del |= (PyDict_DelItem(self->m_attr_dict, key)==0) ? 1:0;
1916                 
1917                 if (del==0) {
1918                         if(attr_str)    PyErr_Format(PyExc_KeyError, "scene[key] = value: KX_Scene, key \"%s\" could not be set", attr_str);
1919                         else                    PyErr_SetString(PyExc_KeyError, "del scene[key]: KX_Scene, key could not be deleted");
1920                         return -1;
1921                 }
1922                 else if (self->m_attr_dict) {
1923                         PyErr_Clear(); /* PyDict_DelItem sets an error when it fails */
1924                 }
1925         }
1926         else { /* ob["key"] = value */
1927                 int set = 0;
1928
1929                 if (self->m_attr_dict==NULL) /* lazy init */
1930                         self->m_attr_dict= PyDict_New();
1931                 
1932                 
1933                 if(PyDict_SetItem(self->m_attr_dict, key, val)==0)
1934                         set= 1;
1935                 else
1936                         PyErr_SetString(PyExc_KeyError, "scene[key] = value: KX_Scene, key not be added to internal dictionary");
1937         
1938                 if(set==0)
1939                         return -1; /* pythons error value */
1940                 
1941         }
1942         
1943         return 0; /* success */
1944 }
1945
1946 static int Seq_Contains(PyObject *self_v, PyObject *value)
1947 {
1948         KX_Scene* self= static_cast<KX_Scene*>BGE_PROXY_REF(self_v);
1949         
1950         if (self==NULL) {
1951                 PyErr_SetString(PyExc_SystemError, "val in scene: KX_Scene, "BGE_PROXY_ERROR_MSG);
1952                 return -1;
1953         }
1954         
1955         if (self->m_attr_dict && PyDict_GetItem(self->m_attr_dict, value))
1956                 return 1;
1957         
1958         return 0;
1959 }
1960
1961 PyMappingMethods KX_Scene::Mapping = {
1962         (lenfunc)NULL                                   ,                       /*inquiry mp_length */
1963         (binaryfunc)Map_GetItem,                /*binaryfunc mp_subscript */
1964         (objobjargproc)Map_SetItem,     /*objobjargproc mp_ass_subscript */
1965 };
1966
1967 PySequenceMethods KX_Scene::Sequence = {
1968         NULL,           /* Cant set the len otherwise it can evaluate as false */
1969         NULL,           /* sq_concat */
1970         NULL,           /* sq_repeat */
1971         NULL,           /* sq_item */
1972         NULL,           /* sq_slice */
1973         NULL,           /* sq_ass_item */
1974         NULL,           /* sq_ass_slice */
1975         (objobjproc)Seq_Contains,       /* sq_contains */
1976 };
1977
1978 PyObject* KX_Scene::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1979 {
1980         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1981         return PyUnicode_FromString(self->GetName().ReadPtr());
1982 }
1983
1984 PyObject* KX_Scene::pyattr_get_objects(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1985 {
1986         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1987         return self->GetObjectList()->GetProxy();
1988 }
1989
1990 PyObject* KX_Scene::pyattr_get_objects_inactive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1991 {
1992         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1993         return self->GetInactiveList()->GetProxy();
1994 }
1995
1996 PyObject* KX_Scene::pyattr_get_lights(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1997 {
1998         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1999         return self->GetLightList()->GetProxy();
2000 }
2001
2002 PyObject* KX_Scene::pyattr_get_cameras(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2003 {
2004         /* With refcounts in this case...
2005          * the new CListValue is owned by python, so its possible python holds onto it longer then the BGE
2006          * however this is the same with "scene.objects + []", when you make a copy by adding lists.
2007          */
2008         
2009         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2010         CListValue* clist = new CListValue();
2011         
2012         /* return self->GetCameras()->GetProxy(); */
2013         
2014         list<KX_Camera*>::iterator it = self->GetCameras()->begin();
2015         while (it != self->GetCameras()->end()) {
2016                 clist->Add((*it)->AddRef());
2017                 it++;
2018         }
2019         
2020         return clist->NewProxy(true);
2021 }
2022
2023 PyObject* KX_Scene::pyattr_get_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2024 {
2025         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2026         return self->GetActiveCamera()->GetProxy();
2027 }
2028
2029
2030 int KX_Scene::pyattr_set_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2031 {
2032         KX_Scene* self= static_cast<KX_Scene*>(self_v);
2033         KX_Camera *camOb;
2034         
2035         if (!ConvertPythonToCamera(value, &camOb, false, "scene.active_camera = value: KX_Scene"))
2036                 return PY_SET_ATTR_FAIL;
2037         
2038         self->SetActiveCamera(camOb);
2039         return PY_SET_ATTR_SUCCESS;
2040 }
2041
2042 PyObject* KX_Scene::pyattr_get_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2043 {
2044         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2045
2046         if(self->m_draw_call_pre==NULL)
2047                 self->m_draw_call_pre= PyList_New(0);
2048         else
2049                 Py_INCREF(self->m_draw_call_pre);
2050         return self->m_draw_call_pre;
2051 }
2052
2053 PyObject* KX_Scene::pyattr_get_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
2054 {
2055         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2056
2057         if(self->m_draw_call_post==NULL)
2058                 self->m_draw_call_post= PyList_New(0);
2059         else
2060                 Py_INCREF(self->m_draw_call_post);
2061         return self->m_draw_call_post;
2062 }
2063
2064 int KX_Scene::pyattr_set_drawing_callback_pre(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2065 {
2066         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2067
2068         if (!PyList_CheckExact(value))
2069         {
2070                 PyErr_SetString(PyExc_ValueError, "Expected a list");
2071                 return PY_SET_ATTR_FAIL;
2072         }
2073         Py_XDECREF(self->m_draw_call_pre);
2074
2075         Py_INCREF(value);
2076         self->m_draw_call_pre = value;
2077
2078         return PY_SET_ATTR_SUCCESS;
2079 }
2080
2081 int KX_Scene::pyattr_set_drawing_callback_post(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
2082 {
2083         KX_Scene* self = static_cast<KX_Scene*>(self_v);
2084
2085         if (!PyList_CheckExact(value))
2086         {
2087                 PyErr_SetString(PyExc_ValueError, "Expected a list");
2088                 return PY_SET_ATTR_FAIL;
2089         }
2090         Py_XDECREF(self->m_draw_call_post);
2091
2092         Py_INCREF(value);
2093         self->m_draw_call_post = value;
2094
2095         return PY_SET_ATTR_SUCCESS;
2096 }
2097
2098 PyAttributeDef KX_Scene::Attributes[] = {
2099         KX_PYATTRIBUTE_RO_FUNCTION("name",                              KX_Scene, pyattr_get_name),
2100         KX_PYATTRIBUTE_RO_FUNCTION("objects",                   KX_Scene, pyattr_get_objects),
2101         KX_PYATTRIBUTE_RO_FUNCTION("objectsInactive",   KX_Scene, pyattr_get_objects_inactive), KX_PYATTRIBUTE_RO_FUNCTION("lights",                    KX_Scene, pyattr_get_lights),
2102         KX_PYATTRIBUTE_RO_FUNCTION("cameras",                   KX_Scene, pyattr_get_cameras),
2103         KX_PYATTRIBUTE_RO_FUNCTION("lights",                    KX_Scene, pyattr_get_lights),
2104         KX_PYATTRIBUTE_RW_FUNCTION("active_camera",             KX_Scene, pyattr_get_active_camera, pyattr_set_active_camera),
2105         KX_PYATTRIBUTE_RW_FUNCTION("pre_draw",                  KX_Scene, pyattr_get_drawing_callback_pre, pyattr_set_drawing_callback_pre),
2106         KX_PYATTRIBUTE_RW_FUNCTION("post_draw",                 KX_Scene, pyattr_get_drawing_callback_post, pyattr_set_drawing_callback_post),
2107         KX_PYATTRIBUTE_BOOL_RO("suspended",                             KX_Scene, m_suspend),
2108         KX_PYATTRIBUTE_BOOL_RO("activity_culling",              KX_Scene, m_activity_culling),
2109         KX_PYATTRIBUTE_FLOAT_RW("activity_culling_radius", 0.5f, FLT_MAX, KX_Scene, m_activity_box_radius),
2110         KX_PYATTRIBUTE_BOOL_RO("dbvt_culling",                  KX_Scene, m_dbvt_culling),
2111         { NULL }        //Sentinel
2112 };
2113
2114 KX_PYMETHODDEF_DOC(KX_Scene, addObject,
2115 "addObject(object, other, time=0)\n"
2116 "Returns the added object.\n")
2117 {
2118         PyObject *pyob, *pyother;
2119         KX_GameObject *ob, *other;
2120
2121         int time = 0;
2122
2123         if (!PyArg_ParseTuple(args, "OO|i:addObject", &pyob, &pyother, &time))
2124                 return NULL;
2125
2126         if (    !ConvertPythonToGameObject(pyob, &ob, false, "scene.addObject(object, other, time): KX_Scene (first argument)") ||
2127                         !ConvertPythonToGameObject(pyother, &other, false, "scene.addObject(object, other, time): KX_Scene (second argument)") )
2128                 return NULL;
2129
2130
2131         SCA_IObject* replica = AddReplicaObject((SCA_IObject*)ob, other, time);
2132         
2133         // release here because AddReplicaObject AddRef's
2134         // the object is added to the scene so we dont want python to own a reference
2135         replica->Release();
2136         return replica->GetProxy();
2137 }
2138
2139 /* Matches python dict.get(key, [default]) */
2140 KX_PYMETHODDEF_DOC(KX_Scene, get, "")
2141 {
2142         PyObject *key;
2143         PyObject* def = Py_None;
2144         PyObject* ret;
2145
2146         if (!PyArg_ParseTuple(args, "O|O:get", &key, &def))
2147                 return NULL;
2148         
2149         if (m_attr_dict && (ret=PyDict_GetItem(m_attr_dict, key))) {
2150                 Py_INCREF(ret);
2151                 return ret;
2152         }
2153         
2154         Py_INCREF(def);
2155         return def;
2156 }
2157
2158 #endif // DISABLE_PYTHON