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