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