merging trunk 17520:19093
[blender.git] / source / gameengine / Ketsji / KX_Scene.cpp
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * Ketsji scene. Holds references to all scene data.
29  */
30
31 #ifdef WIN32
32 #pragma warning (disable : 4786)
33 #endif //WIN32
34
35
36 #include "KX_Scene.h"
37 #include "MT_assert.h"
38
39 #include "KX_KetsjiEngine.h"
40 #include "KX_BlenderMaterial.h"
41 #include "RAS_IPolygonMaterial.h"
42 #include "ListValue.h"
43 #include "SCA_LogicManager.h"
44 #include "SCA_TimeEventManager.h"
45 #include "SCA_AlwaysEventManager.h"
46 #include "SCA_RandomEventManager.h"
47 #include "KX_RayEventManager.h"
48 #include "KX_TouchEventManager.h"
49 #include "SCA_KeyboardManager.h"
50 #include "SCA_MouseManager.h"
51 #include "SCA_PropertyEventManager.h"
52 #include "SCA_ActuatorEventManager.h"
53 #include "KX_Camera.h"
54 #include "SCA_JoystickManager.h"
55
56 #include "RAS_MeshObject.h"
57 #include "BL_SkinMeshObject.h"
58
59 #include "RAS_IRasterizer.h"
60 #include "RAS_BucketManager.h"
61
62 #include "FloatValue.h"
63 #include "SCA_IController.h"
64 #include "SCA_IActuator.h"
65 #include "SG_Node.h"
66 #include "SYS_System.h"
67 #include "SG_Controller.h"
68 #include "SG_IObject.h"
69 #include "SG_Tree.h"
70 #include "DNA_group_types.h"
71 #include "DNA_scene_types.h"
72 #include "BKE_anim.h"
73
74 #include "KX_SG_NodeRelationships.h"
75
76 #include "KX_NetworkEventManager.h"
77 #include "NG_NetworkScene.h"
78 #include "PHY_IPhysicsEnvironment.h"
79 #include "KX_IPhysicsController.h"
80 #include "KX_BlenderSceneConverter.h"
81
82 #include "BL_ShapeDeformer.h"
83 #include "BL_DeformableGameObject.h"
84
85 // to get USE_BULLET!
86 #include "KX_ConvertPhysicsObject.h"
87
88 #ifdef USE_BULLET
89 #include "CcdPhysicsEnvironment.h"
90 #include "CcdPhysicsController.h"
91 #endif
92
93 void* KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
94 {
95         KX_GameObject* replica = ((KX_Scene*)scene)->AddNodeReplicaObject(node,(KX_GameObject*)gameobj);
96
97         if(replica)
98                 replica->Release();
99
100         return (void*)replica;
101 }
102
103 void* KX_SceneDestructionFunc(SG_IObject* node,void* gameobj,void* scene)
104 {
105         ((KX_Scene*)scene)->RemoveNodeDestructObject(node,(KX_GameObject*)gameobj);
106
107         return NULL;
108 };
109
110 SG_Callbacks KX_Scene::m_callbacks = SG_Callbacks(KX_SceneReplicationFunc,KX_SceneDestructionFunc,KX_GameObject::UpdateTransformFunc);
111
112 // temporarily var until there is a button in the userinterface
113 // (defined in KX_PythonInit.cpp)
114 extern bool gUseVisibilityTemp;
115
116 KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
117                                    class SCA_IInputDevice* mousedevice,
118                                    class NG_NetworkDeviceInterface *ndi,
119                                    class SND_IAudioDevice* adi,
120                                    const STR_String& sceneName,
121                                    Scene *scene): 
122         PyObjectPlus(&KX_Scene::Type),
123         m_keyboardmgr(NULL),
124         m_mousemgr(NULL),
125         m_sceneConverter(NULL),
126         m_physicsEnvironment(0),
127         m_sceneName(sceneName),
128         m_adi(adi),
129         m_networkDeviceInterface(ndi),
130         m_active_camera(NULL),
131         m_ueberExecutionPriority(0),
132         m_blenderScene(scene)
133 {
134         m_suspendedtime = 0.0;
135         m_suspendeddelta = 0.0;
136
137         m_activity_culling = false;
138         m_suspend = false;
139         m_isclearingZbuffer = true;
140         m_tempObjectList = new CListValue();
141         m_objectlist = new CListValue();
142         m_parentlist = new CListValue();
143         m_lightlist= new CListValue();
144         m_inactivelist = new CListValue();
145         m_euthanasyobjects = new CListValue();
146         m_delayReleaseObjects = new CListValue();
147
148         m_logicmgr = new SCA_LogicManager();
149         
150         m_timemgr = new SCA_TimeEventManager(m_logicmgr);
151         m_keyboardmgr = new SCA_KeyboardManager(m_logicmgr,keyboarddevice);
152         m_mousemgr = new SCA_MouseManager(m_logicmgr,mousedevice);
153         
154         SCA_AlwaysEventManager* alwaysmgr = new SCA_AlwaysEventManager(m_logicmgr);
155         SCA_PropertyEventManager* propmgr = new SCA_PropertyEventManager(m_logicmgr);
156         SCA_ActuatorEventManager* actmgr = new SCA_ActuatorEventManager(m_logicmgr);
157         SCA_RandomEventManager* rndmgr = new SCA_RandomEventManager(m_logicmgr);
158         KX_RayEventManager* raymgr = new KX_RayEventManager(m_logicmgr);
159
160         KX_NetworkEventManager* netmgr = new KX_NetworkEventManager(m_logicmgr, ndi);
161         
162         
163
164         m_logicmgr->RegisterEventManager(alwaysmgr);
165         m_logicmgr->RegisterEventManager(propmgr);
166         m_logicmgr->RegisterEventManager(actmgr);
167         m_logicmgr->RegisterEventManager(m_keyboardmgr);
168         m_logicmgr->RegisterEventManager(m_mousemgr);
169         m_logicmgr->RegisterEventManager(m_timemgr);
170         m_logicmgr->RegisterEventManager(rndmgr);
171         m_logicmgr->RegisterEventManager(raymgr);
172         m_logicmgr->RegisterEventManager(netmgr);
173
174
175         SYS_SystemHandle hSystem = SYS_GetSystem();
176         bool nojoystick= SYS_GetCommandLineInt(hSystem,"nojoystick",0);
177         if (!nojoystick)
178         {
179                 SCA_JoystickManager *joymgr     = new SCA_JoystickManager(m_logicmgr);
180                 m_logicmgr->RegisterEventManager(joymgr);
181         }
182
183         m_soundScene = new SND_Scene(adi);
184         MT_assert (m_networkDeviceInterface != NULL);
185         m_networkScene = new NG_NetworkScene(m_networkDeviceInterface);
186         
187         m_rootnode = NULL;
188
189         m_bucketmanager=new RAS_BucketManager();
190
191         m_canvasDesignWidth = 0;
192         m_canvasDesignHeight = 0;
193         
194         m_attrlist = PyDict_New(); /* new ref */
195 }
196
197
198
199 KX_Scene::~KX_Scene()
200 {
201         // The release of debug properties used to be in SCA_IScene::~SCA_IScene
202         // It's still there but we remove all properties here otherwise some
203         // reference might be hanging and causing late release of objects
204         RemoveAllDebugProperties();
205
206         while (GetRootParentList()->GetCount() > 0) 
207         {
208                 KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(0);
209                 this->RemoveObject(parentobj);
210         }
211
212         if(m_objectlist)
213                 m_objectlist->Release();
214
215         if (m_parentlist)
216                 m_parentlist->Release();
217         
218         if (m_inactivelist)
219                 m_inactivelist->Release();
220
221         if (m_lightlist)
222                 m_lightlist->Release();
223         
224         if (m_tempObjectList)
225                 m_tempObjectList->Release();
226
227         if (m_euthanasyobjects)
228                 m_euthanasyobjects->Release();
229         if (m_delayReleaseObjects)
230                 m_delayReleaseObjects->Release();
231
232         if (m_logicmgr)
233                 delete m_logicmgr;
234
235         if (m_physicsEnvironment)
236                 delete m_physicsEnvironment;
237
238         if (m_soundScene)
239                 delete m_soundScene;
240
241         if (m_networkScene)
242                 delete m_networkScene;
243         
244         if (m_bucketmanager)
245         {
246                 delete m_bucketmanager;
247         }
248         //Py_DECREF(m_attrlist);
249 }
250
251 void KX_Scene::SetProjectionMatrix(MT_CmMatrix4x4& pmat)
252 {
253         m_projectionmat = pmat;
254 }
255
256
257
258 RAS_BucketManager* KX_Scene::GetBucketManager()
259 {
260         return m_bucketmanager;
261 }
262
263
264
265 CListValue* KX_Scene::GetObjectList()
266 {
267         return m_objectlist;
268 }
269
270
271
272 CListValue* KX_Scene::GetRootParentList()
273 {
274         return m_parentlist;
275 }
276
277 CListValue* KX_Scene::GetInactiveList()
278 {
279         return m_inactivelist;
280 }
281
282
283
284 CListValue* KX_Scene::GetLightList()
285 {
286         return m_lightlist;
287 }
288
289 SCA_LogicManager* KX_Scene::GetLogicManager()
290 {
291         return m_logicmgr;
292 }
293
294 SCA_TimeEventManager* KX_Scene::GetTimeEventManager()
295 {
296         return m_timemgr;
297 }
298
299
300
301  
302 list<class KX_Camera*>* KX_Scene::GetCameras()
303 {
304         return &m_cameras;
305 }
306
307
308
309 void KX_Scene::SetFramingType(RAS_FrameSettings & frame_settings)
310 {
311         m_frame_settings = frame_settings;
312 };
313
314 /**
315  * Return a const reference to the framing 
316  * type set by the above call.
317  * The contents are not guarenteed to be sensible
318  * if you don't call the above function.
319  */
320 const RAS_FrameSettings& KX_Scene::GetFramingType() const 
321 {
322         return m_frame_settings;
323 };      
324
325
326
327 /**
328  * Store the current scene's viewport on the 
329  * game engine canvas.
330  */
331 void KX_Scene::SetSceneViewport(const RAS_Rect &viewport)
332 {
333         m_viewport = viewport;
334 }
335
336
337
338 const RAS_Rect& KX_Scene::GetSceneViewport() const 
339 {
340         return m_viewport;
341 }
342
343
344
345 void KX_Scene::SetWorldInfo(class KX_WorldInfo* worldinfo)
346 {
347         m_worldinfo = worldinfo;
348 }
349
350
351
352 class KX_WorldInfo* KX_Scene::GetWorldInfo()
353 {
354         return m_worldinfo;
355 }
356
357
358
359 SND_Scene* KX_Scene::GetSoundScene()
360 {
361         return m_soundScene;
362 }
363
364 const STR_String& KX_Scene::GetName()
365 {
366         return m_sceneName;
367 }
368
369
370 void KX_Scene::Suspend()
371 {
372         m_suspend = true;
373 }
374
375 void KX_Scene::Resume()
376 {
377         m_suspend = false;
378 }
379
380 void KX_Scene::SetActivityCulling(bool b)
381 {
382         m_activity_culling = b;
383 }
384
385 bool KX_Scene::IsSuspended()
386 {
387         return m_suspend;
388 }
389
390 bool KX_Scene::IsClearingZBuffer()
391 {
392         return m_isclearingZbuffer;
393 }
394
395 void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer)
396 {
397         m_isclearingZbuffer = isclearingZbuffer;
398 }
399
400 void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj)
401 {
402         KX_GameObject* orgobj = (KX_GameObject*)gameobj;        
403         if (NewRemoveObject(orgobj) != 0)
404         {
405                 // object is not yet deleted (this can happen when it hangs in an add object actuator
406                 // last object created reference. It's a bad situation, don't know how to fix it exactly
407                 // The least I can do, is remove the reference to the node in the object as the node
408                 // will in any case be deleted. This ensures that the object will not try to use the node
409                 // when it is finally deleted (see KX_GameObject destructor)
410                 orgobj->SetSGNode(NULL);
411         }
412         if (node)
413                 delete node;
414 }
415
416 KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CValue* gameobj)
417 {
418         // for group duplication, limit the duplication of the hierarchy to the
419         // objects that are part of the group. 
420         if (!IsObjectInGroup(gameobj))
421                 return NULL;
422         
423         KX_GameObject* orgobj = (KX_GameObject*)gameobj;
424         KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica();
425         m_map_gameobject_to_replica.insert(orgobj, newobj);
426
427         // also register 'timers' (time properties) of the replica
428         int numprops = newobj->GetPropertyCount();
429
430         for (int i = 0; i < numprops; i++)
431         {
432                 CValue* prop = newobj->GetProperty(i);
433
434                 if (prop->GetProperty("timer"))
435                         this->m_timemgr->AddTimeProperty(prop);
436         }
437
438         if (node)
439         {
440                 newobj->SetSGNode((SG_Node*)node);
441         }
442         else
443         {
444                 m_rootnode = new SG_Node(newobj,this,KX_Scene::m_callbacks);
445         
446                 // this fixes part of the scaling-added object bug
447                 SG_Node* orgnode = orgobj->GetSGNode();
448                 m_rootnode->SetLocalScale(orgnode->GetLocalScale());
449                 m_rootnode->SetLocalPosition(orgnode->GetLocalPosition());
450                 m_rootnode->SetLocalOrientation(orgnode->GetLocalOrientation());
451
452                 // define the relationship between this node and it's parent.
453                 KX_NormalParentRelation * parent_relation = 
454                         KX_NormalParentRelation::New();
455                 m_rootnode->SetParentRelation(parent_relation);
456
457                 newobj->SetSGNode(m_rootnode);
458         }
459         
460         SG_IObject* replicanode = newobj->GetSGNode();
461 //      SG_Node* rootnode = (replicanode == m_rootnode ? NULL : m_rootnode);
462
463         replicanode->SetSGClientObject(newobj);
464
465         // this is the list of object that are send to the graphics pipeline
466         m_objectlist->Add(newobj->AddRef());
467         newobj->AddMeshUser();
468
469         // logic cannot be replicated, until the whole hierarchy is replicated.
470         m_logicHierarchicalGameObjects.push_back(newobj);
471         //replicate controllers of this node
472         SGControllerList        scenegraphcontrollers = orgobj->GetSGNode()->GetSGControllerList();
473         replicanode->RemoveAllControllers();
474         SGControllerList::iterator cit;
475         //int numcont = scenegraphcontrollers.size();
476         
477         for (cit = scenegraphcontrollers.begin();!(cit==scenegraphcontrollers.end());++cit)
478         {
479                 // controller replication is quite complicated
480                 // only replicate ipo and physics controller for now
481
482                 SG_Controller* replicacontroller = (*cit)->GetReplica((SG_Node*) replicanode);
483                 if (replicacontroller)
484                 {
485                         replicacontroller->SetObject(replicanode);
486                         replicanode->AddSGController(replicacontroller);
487                 }
488         }
489         
490         return newobj;
491 }
492
493
494
495 // before calling this method KX_Scene::ReplicateLogic(), make sure to
496 // have called 'GameObject::ReParentLogic' for each object this
497 // hierarchy that's because first ALL bricks must exist in the new
498 // replica of the hierarchy in order to make cross-links work properly
499 // !
500 // It is VERY important that the order of sensors and actuators in
501 // the replicated object is preserved: it is is used to reconnect the logic.
502 // This method is more robust then using the bricks name in case of complex 
503 // group replication. The replication of logic bricks is done in 
504 // SCA_IObject::ReParentLogic(), make sure it preserves the order of the bricks.
505 void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
506 {
507         // also relink the controller to sensors/actuators
508         SCA_ControllerList& controllers = newobj->GetControllers();
509         //SCA_SensorList&     sensors     = newobj->GetSensors();
510         //SCA_ActuatorList&   actuators   = newobj->GetActuators();
511
512         for (SCA_ControllerList::iterator itc = controllers.begin(); !(itc==controllers.end());itc++)
513         {
514                 SCA_IController* cont = (*itc);
515                 cont->SetUeberExecutePriority(m_ueberExecutionPriority);
516                 vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
517                 vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
518
519                 // disconnect the sensors and actuators
520                 cont->UnlinkAllSensors();
521                 cont->UnlinkAllActuators();
522                 
523                 // now relink each sensor
524                 for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++)
525                 {
526                         SCA_ISensor* oldsensor = (*its);
527                         SCA_IObject* oldsensorobj = oldsensor->GetParent();
528                         SCA_IObject* newsensorobj = NULL;
529                 
530                         // the original owner of the sensor has been replicated?
531                         void **h_obj = m_map_gameobject_to_replica[oldsensorobj];
532                         if (h_obj)
533                                 newsensorobj = (SCA_IObject*)(*h_obj);
534                         if (!newsensorobj)
535                         {
536                                 // no, then the sensor points outside the hierachy, keep it the same
537                                 if (m_objectlist->SearchValue(oldsensorobj))
538                                         // only replicate links that points to active objects
539                                         m_logicmgr->RegisterToSensor(cont,oldsensor);
540                         }
541                         else
542                         {
543                                 // yes, then the new sensor has the same position
544                                 SCA_SensorList& sensorlist = oldsensorobj->GetSensors();
545                                 SCA_SensorList::iterator sit;
546                                 SCA_ISensor* newsensor = NULL;
547                                 int sensorpos;
548
549                                 for (sensorpos=0, sit=sensorlist.begin(); sit!=sensorlist.end(); sit++, sensorpos++)
550                                 {
551                                         if ((*sit) == oldsensor) 
552                                         {
553                                                 newsensor = newsensorobj->GetSensors().at(sensorpos);
554                                                 break;
555                                         }
556                                 }
557                                 assert(newsensor != NULL);
558                                 m_logicmgr->RegisterToSensor(cont,newsensor);
559                         }
560                 }
561                 
562                 // now relink each actuator
563                 for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++)
564                 {
565                         SCA_IActuator* oldactuator = (*ita);
566                         SCA_IObject* oldactuatorobj = oldactuator->GetParent();
567                         SCA_IObject* newactuatorobj = NULL;
568
569                         // the original owner of the sensor has been replicated?
570                         void **h_obj = m_map_gameobject_to_replica[oldactuatorobj];
571                         if (h_obj)
572                                 newactuatorobj = (SCA_IObject*)(*h_obj);
573
574                         if (!newactuatorobj)
575                         {
576                                 // no, then the sensor points outside the hierachy, keep it the same
577                                 if (m_objectlist->SearchValue(oldactuatorobj))
578                                         // only replicate links that points to active objects
579                                         m_logicmgr->RegisterToActuator(cont,oldactuator);
580                         }
581                         else
582                         {
583                                 // yes, then the new sensor has the same position
584                                 SCA_ActuatorList& actuatorlist = oldactuatorobj->GetActuators();
585                                 SCA_ActuatorList::iterator ait;
586                                 SCA_IActuator* newactuator = NULL;
587                                 int actuatorpos;
588
589                                 for (actuatorpos=0, ait=actuatorlist.begin(); ait!=actuatorlist.end(); ait++, actuatorpos++)
590                                 {
591                                         if ((*ait) == oldactuator) 
592                                         {
593                                                 newactuator = newactuatorobj->GetActuators().at(actuatorpos);
594                                                 break;
595                                         }
596                                 }
597                                 assert(newactuator != NULL);
598                                 m_logicmgr->RegisterToActuator(cont,newactuator);
599                                 newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
600                         }
601                 }
602         }
603         // ready to set initial state
604         newobj->ResetState();
605 }
606
607 void KX_Scene::DupliGroupRecurse(CValue* obj, int level)
608 {
609         KX_GameObject* groupobj = (KX_GameObject*) obj;
610         KX_GameObject* replica;
611         KX_GameObject* gameobj;
612         Object* blgroupobj = groupobj->GetBlenderObject();
613         Group* group;
614         GroupObject *go;
615         vector<KX_GameObject*> duplilist;
616
617         if (!groupobj->GetSGNode() ||
618                 !groupobj->IsDupliGroup() ||
619                 level>MAX_DUPLI_RECUR)
620                 return;
621
622         // we will add one group at a time
623         m_logicHierarchicalGameObjects.clear();
624         m_map_gameobject_to_replica.clear();
625         m_ueberExecutionPriority++;
626         // for groups will do something special: 
627         // we will force the creation of objects to those in the group only
628         // Again, this is match what Blender is doing (it doesn't care of parent relationship)
629         m_groupGameObjects.clear();
630
631         group = blgroupobj->dup_group;
632         for(go=(GroupObject*)group->gobject.first; go; go=(GroupObject*)go->next) 
633         {
634                 Object* blenderobj = go->ob;
635                 if (blgroupobj == blenderobj)
636                         // this check is also in group_duplilist()
637                         continue;
638
639                 gameobj = (KX_GameObject*)m_logicmgr->FindGameObjByBlendObj(blenderobj);
640                 if (gameobj == NULL) 
641                 {
642                         // this object has not been converted!!!
643                         // Should not happen as dupli group are created automatically 
644                         continue;
645                 }
646
647                 gameobj->SetBlenderGroupObject(blgroupobj);
648
649                 if ((blenderobj->lay & group->layer)==0)
650                 {
651                         // object is not visible in the 3D view, will not be instantiated
652                         continue;
653                 }
654                 m_groupGameObjects.insert(gameobj);
655         }
656
657         set<CValue*>::iterator oit;
658         for (oit=m_groupGameObjects.begin(); oit != m_groupGameObjects.end(); oit++)
659         {
660                 gameobj = (KX_GameObject*)(*oit);
661
662                 KX_GameObject *parent = gameobj->GetParent();
663                 if (parent != NULL)
664                 {
665                         parent->Release(); // GetParent() increased the refcount
666
667                         // this object is not a top parent. Either it is the child of another
668                         // object in the group and it will be added automatically when the parent
669                         // is added. Or it is the child of an object outside the group and the group
670                         // is inconsistent, skip it anyway
671                         continue;
672                 }
673                 replica = (KX_GameObject*) AddNodeReplicaObject(NULL,gameobj);
674                 // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
675                 m_parentlist->Add(replica->AddRef());
676
677                 // recurse replication into children nodes
678                 NodeList& children = gameobj->GetSGNode()->GetSGChildren();
679
680                 replica->GetSGNode()->ClearSGChildren();
681                 for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
682                 {
683                         SG_Node* orgnode = (*childit);
684                         SG_Node* childreplicanode = orgnode->GetSGReplica();
685                         if (childreplicanode)
686                                 replica->GetSGNode()->AddChild(childreplicanode);
687                 }
688                 // don't replicate logic now: we assume that the objects in the group can have
689                 // logic relationship, even outside parent relationship
690                 // In order to match 3D view, the position of groupobj is used as a 
691                 // transformation matrix instead of the new position. This means that 
692                 // the group reference point is 0,0,0
693
694                 // get the rootnode's scale
695                 MT_Vector3 newscale = groupobj->NodeGetWorldScaling();
696                 // set the replica's relative scale with the rootnode's scale
697                 replica->NodeSetRelativeScale(newscale);
698
699                 MT_Matrix3x3 newori = groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldOrientation();
700                 replica->NodeSetLocalOrientation(newori);
701
702                 MT_Point3 newpos = groupobj->NodeGetWorldPosition() + 
703                         newscale*(groupobj->NodeGetWorldOrientation() * gameobj->NodeGetWorldPosition());
704                 replica->NodeSetLocalPosition(newpos);
705
706                 replica->GetSGNode()->UpdateWorldData(0);
707                 replica->GetSGNode()->SetBBox(gameobj->GetSGNode()->BBox());
708                 replica->GetSGNode()->SetRadius(gameobj->GetSGNode()->Radius());
709                 // done with replica
710                 replica->Release();
711         }
712
713         // the logic must be replicated first because we need
714         // the new logic bricks before relinking
715         vector<KX_GameObject*>::iterator git;
716         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
717         {
718                 (*git)->ReParentLogic();
719         }
720         
721         //      relink any pointers as necessary, sort of a temporary solution
722         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
723         {
724                 // this will also relink the actuator to objects within the hierarchy
725                 (*git)->Relink(&m_map_gameobject_to_replica);
726                 // add the object in the layer of the parent
727                 (*git)->SetLayer(groupobj->GetLayer());
728         }
729
730         // replicate crosslinks etc. between logic bricks
731         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
732         {
733                 ReplicateLogic((*git));
734         }
735         
736         // now look if object in the hierarchy have dupli group and recurse
737         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
738         {
739                 if ((*git) != groupobj && (*git)->IsDupliGroup())
740                         // can't instantiate group immediately as it destroys m_logicHierarchicalGameObjects
741                         duplilist.push_back((*git));
742         }
743
744         for (git = duplilist.begin(); !(git == duplilist.end()); ++git)
745         {
746                 DupliGroupRecurse((*git), level+1);
747         }
748 }
749
750
751 SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
752                                                                                 class CValue* parentobject,
753                                                                                 int lifespan)
754 {
755
756         m_logicHierarchicalGameObjects.clear();
757         m_map_gameobject_to_replica.clear();
758         m_groupGameObjects.clear();
759
760         // todo: place a timebomb in the object, for temporarily objects :)
761         // lifespan of zero means 'this object lives forever'
762         KX_GameObject* originalobj = (KX_GameObject*) originalobject;
763         KX_GameObject* parentobj = (KX_GameObject*) parentobject;
764
765         m_ueberExecutionPriority++;
766
767         // lets create a replica
768         KX_GameObject* replica = (KX_GameObject*) AddNodeReplicaObject(NULL,originalobj);
769
770         if (lifespan > 0)
771         {
772                 // add a timebomb to this object
773                 // for now, convert between so called frames and realtime
774                 m_tempObjectList->Add(replica->AddRef());
775                 CValue *fval = new CFloatValue(lifespan*0.02);
776                 replica->SetProperty("::timebomb",fval);
777                 fval->Release();
778         }
779
780         // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
781         m_parentlist->Add(replica->AddRef());
782
783         // recurse replication into children nodes
784
785         NodeList& children = originalobj->GetSGNode()->GetSGChildren();
786
787         replica->GetSGNode()->ClearSGChildren();
788         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
789         {
790                 SG_Node* orgnode = (*childit);
791                 SG_Node* childreplicanode = orgnode->GetSGReplica();
792                 if (childreplicanode)
793                         replica->GetSGNode()->AddChild(childreplicanode);
794         }
795
796         // now replicate logic
797         vector<KX_GameObject*>::iterator git;
798         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
799         {
800                 (*git)->ReParentLogic();
801         }
802         
803         //      relink any pointers as necessary, sort of a temporary solution
804         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
805         {
806                 // this will also relink the actuators in the hierarchy
807                 (*git)->Relink(&m_map_gameobject_to_replica);
808                 // add the object in the layer of the parent
809                 (*git)->SetLayer(parentobj->GetLayer());
810         }
811
812         // replicate crosslinks etc. between logic bricks
813         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
814         {
815                 ReplicateLogic((*git));
816         }
817         
818         MT_Point3 newpos = ((KX_GameObject*) parentobject)->NodeGetWorldPosition();
819         replica->NodeSetLocalPosition(newpos);
820
821         MT_Matrix3x3 newori = ((KX_GameObject*) parentobject)->NodeGetWorldOrientation();
822         replica->NodeSetLocalOrientation(newori);
823         
824         // get the rootnode's scale
825         MT_Vector3 newscale = parentobj->GetSGNode()->GetRootSGParent()->GetLocalScale();
826
827         // set the replica's relative scale with the rootnode's scale
828         replica->NodeSetRelativeScale(newscale);
829
830         replica->GetSGNode()->UpdateWorldData(0);
831         replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
832         replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
833         // check if there are objects with dupligroup in the hierarchy
834         vector<KX_GameObject*> duplilist;
835         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
836         {
837                 if ((*git)->IsDupliGroup())
838                 {
839                         // separate list as m_logicHierarchicalGameObjects is also used by DupliGroupRecurse()
840                         duplilist.push_back(*git);
841                 }
842         }
843         for (git = duplilist.begin();!(git==duplilist.end());++git)
844         {
845                 DupliGroupRecurse(*git, 0);
846         }
847         //      don't release replica here because we are returning it, not done with it...
848         return replica;
849 }
850
851
852
853 void KX_Scene::RemoveObject(class CValue* gameobj)
854 {
855         KX_GameObject* newobj = (KX_GameObject*) gameobj;
856
857         // first disconnect child from parent
858         SG_Node* node = newobj->GetSGNode();
859
860         if (node)
861         {
862                 node->DisconnectFromParent();
863
864                 // recursively destruct
865                 node->Destruct();
866         }
867         //no need to do that: the object is destroyed and memory released 
868         //newobj->SetSGNode(0);
869 }
870
871 void KX_Scene::DelayedReleaseObject(CValue* gameobj)
872 {
873         m_delayReleaseObjects->Add(gameobj->AddRef());
874 }
875
876
877 void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
878 {
879         //KX_GameObject* newobj = (KX_GameObject*) gameobj;
880         if (!m_euthanasyobjects->SearchValue(gameobj))
881         {
882                 m_euthanasyobjects->Add(gameobj->AddRef());
883         } 
884 }
885
886
887
888 int KX_Scene::NewRemoveObject(class CValue* gameobj)
889 {
890         int ret;
891         KX_GameObject* newobj = (KX_GameObject*) gameobj;
892
893         // keep the blender->game object association up to date
894         // note that all the replicas of an object will have the same
895         // blender object, that's why we need to check the game object
896         // as only the deletion of the original object must be recorded
897         m_logicmgr->UnregisterGameObj(newobj->GetBlenderObject(), gameobj);
898
899         //todo: look at this
900         //GetPhysicsEnvironment()->RemovePhysicsController(gameobj->getPhysicsController());
901
902         // remove all sensors/controllers/actuators from logicsystem...
903         
904         SCA_SensorList& sensors = newobj->GetSensors();
905         for (SCA_SensorList::iterator its = sensors.begin();
906                  !(its==sensors.end());its++)
907         {
908                 m_logicmgr->RemoveSensor(*its);
909         }
910         
911     SCA_ControllerList& controllers = newobj->GetControllers();
912         for (SCA_ControllerList::iterator itc = controllers.begin();
913                  !(itc==controllers.end());itc++)
914         {
915                 m_logicmgr->RemoveController(*itc);
916         }
917
918         SCA_ActuatorList& actuators = newobj->GetActuators();
919         for (SCA_ActuatorList::iterator ita = actuators.begin();
920                  !(ita==actuators.end());ita++)
921         {
922                 m_logicmgr->RemoveDestroyedActuator(*ita);
923         }
924         // the sensors/controllers/actuators must also be released, this is done in ~SCA_IObject
925
926         // now remove the timer properties from the time manager
927         int numprops = newobj->GetPropertyCount();
928
929         for (int i = 0; i < numprops; i++)
930         {
931                 CValue* propval = newobj->GetProperty(i);
932                 if (propval->GetProperty("timer"))
933                 {
934                         m_timemgr->RemoveTimeProperty(propval);
935                 }
936         }
937         
938         newobj->RemoveMeshes();
939         ret = 1;
940         if (m_lightlist->RemoveValue(newobj)) // TODO - use newobj->IsLight() test when its merged in from apricot. - Campbell
941                 ret = newobj->Release();
942         if (m_objectlist->RemoveValue(newobj))
943                 ret = newobj->Release();
944         if (m_tempObjectList->RemoveValue(newobj))
945                 ret = newobj->Release();
946         if (m_parentlist->RemoveValue(newobj))
947                 ret = newobj->Release();
948         if (m_inactivelist->RemoveValue(newobj))
949                 ret = newobj->Release();
950         if (m_euthanasyobjects->RemoveValue(newobj))
951                 ret = newobj->Release();
952                 
953         if (newobj == m_active_camera)
954         {
955                 //no AddRef done on m_active_camera so no Release
956                 //m_active_camera->Release();
957                 m_active_camera = NULL;
958         }
959
960         // in case this is a camera
961         m_cameras.remove((KX_Camera*)newobj);
962
963         if (m_sceneConverter)
964                 m_sceneConverter->UnregisterGameObject(newobj);
965         // return value will be 0 if the object is actually deleted (all reference gone)
966         return ret;
967 }
968
969
970
971 void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj)
972 {
973         KX_GameObject* gameobj = static_cast<KX_GameObject*>(obj);
974         RAS_MeshObject* mesh = static_cast<RAS_MeshObject*>(meshobj);
975
976         if(!gameobj || !mesh)
977         {
978                 std::cout << "warning: invalid object, mesh will not be replaced" << std::endl;
979                 return;
980         }
981
982         gameobj->RemoveMeshes();
983         gameobj->AddMesh(mesh);
984         
985         if (gameobj->m_isDeformable)
986         {
987                 BL_DeformableGameObject* newobj = static_cast<BL_DeformableGameObject*>( gameobj );
988                 
989                 if (newobj->GetDeformer())
990                 {
991                         delete newobj->GetDeformer();
992                         newobj->SetDeformer(NULL);
993                 }
994
995                 if (mesh->IsDeformed())
996                 {
997                         // we must create a new deformer but which one?
998                         KX_GameObject* parentobj = newobj->GetParent();
999                         // this always return the original game object (also for replicate)
1000                         Object* blendobj = newobj->GetBlenderObject();
1001                         // object that owns the new mesh
1002                         Object* oldblendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameMeshName(mesh->GetName()));
1003                         Mesh* blendmesh = mesh->GetMesh();
1004
1005                         bool bHasShapeKey = blendmesh->key != NULL && blendmesh->key->type==KEY_RELATIVE;
1006                         bool bHasDvert = blendmesh->dvert != NULL;
1007                         bool bHasArmature = 
1008                                 parentobj &&                                                            // current parent is armature
1009                                 parentobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE &&
1010                                 oldblendobj &&                                                          // needed for mesh deform
1011                                 blendobj->parent &&                                                     // original object had armature (not sure this test is needed)
1012                                 blendobj->parent->type == OB_ARMATURE && 
1013                                 blendobj->partype==PARSKEL && 
1014                                 blendmesh->dvert!=NULL;                                         // mesh has vertex group
1015                         bool releaseParent = true;
1016
1017                         if (bHasShapeKey)
1018                         {
1019                                 BL_ShapeDeformer* shapeDeformer;
1020                                 if (bHasArmature) 
1021                                 {
1022                                         shapeDeformer = new BL_ShapeDeformer(
1023                                                 newobj,
1024                                                 oldblendobj, blendobj,
1025                                                 static_cast<BL_SkinMeshObject*>(mesh),
1026                                                 true,
1027                                                 static_cast<BL_ArmatureObject*>( parentobj )
1028                                         );
1029                                         releaseParent= false;
1030                                         shapeDeformer->LoadShapeDrivers(blendobj->parent);
1031                                 }
1032                                 else
1033                                 {
1034                                         shapeDeformer = new BL_ShapeDeformer(
1035                                                 newobj,
1036                                                 oldblendobj, blendobj,
1037                                                 static_cast<BL_SkinMeshObject*>(mesh),
1038                                                 false,
1039                                                 NULL
1040                                         );
1041                                 }
1042                                 newobj->SetDeformer( shapeDeformer);
1043                         }
1044                         else if (bHasArmature) 
1045                         {
1046                                 BL_SkinDeformer* skinDeformer = new BL_SkinDeformer(
1047                                         newobj,
1048                                         oldblendobj, blendobj,
1049                                         static_cast<BL_SkinMeshObject*>(mesh),
1050                                         true,
1051                                         static_cast<BL_ArmatureObject*>( parentobj )
1052                                 );
1053                                 releaseParent= false;
1054                                 newobj->SetDeformer(skinDeformer);
1055                         }
1056                         else if (bHasDvert)
1057                         {
1058                                 BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
1059                                         newobj, oldblendobj, static_cast<BL_SkinMeshObject*>(mesh)
1060                                 );
1061                                 newobj->SetDeformer(meshdeformer);
1062                         }
1063
1064                         // release parent reference if its not being used 
1065                         if( releaseParent && parentobj)
1066                                 parentobj->Release();
1067                 }
1068         }
1069
1070         gameobj->AddMeshUser();
1071 }
1072
1073
1074
1075 MT_CmMatrix4x4& KX_Scene::GetViewMatrix()
1076 {
1077         MT_Scalar cammat[16];
1078         m_active_camera->GetWorldToCamera().getValue(cammat);
1079         m_viewmat = cammat;
1080         return m_viewmat;
1081 }
1082
1083
1084
1085 MT_CmMatrix4x4& KX_Scene::GetProjectionMatrix()
1086 {
1087         return m_projectionmat;
1088 }
1089
1090
1091 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
1092 {
1093         list<KX_Camera*>::iterator it = m_cameras.begin();
1094
1095         while ( (it != m_cameras.end()) 
1096                         && ((*it) != cam) ) {
1097           it++;
1098         }
1099
1100         return ((it == m_cameras.end()) ? NULL : (*it));
1101 }
1102
1103
1104 KX_Camera* KX_Scene::FindCamera(STR_String& name)
1105 {
1106         list<KX_Camera*>::iterator it = m_cameras.begin();
1107
1108         while ( (it != m_cameras.end()) 
1109                         && ((*it)->GetName() != name) ) {
1110           it++;
1111         }
1112
1113         return ((it == m_cameras.end()) ? NULL : (*it));
1114 }
1115
1116 void KX_Scene::AddCamera(KX_Camera* cam)
1117 {
1118         if (!FindCamera(cam))
1119                 m_cameras.push_back(cam);
1120 }
1121
1122
1123 KX_Camera* KX_Scene::GetActiveCamera()
1124 {       
1125         // NULL if not defined
1126         return m_active_camera;
1127 }
1128
1129
1130 void KX_Scene::SetActiveCamera(KX_Camera* cam)
1131 {
1132         // only set if the cam is in the active list? Or add it otherwise?
1133         if (!FindCamera(cam)){
1134                 AddCamera(cam);
1135                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1136         } 
1137
1138         m_active_camera = cam;
1139 }
1140
1141 void KX_Scene::SetCameraOnTop(KX_Camera* cam)
1142 {
1143         if (!FindCamera(cam)){
1144                 // adding is always done at the back, so that's all that needs to be done
1145                 AddCamera(cam);
1146                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1147         } else {
1148                 m_cameras.remove(cam);
1149                 m_cameras.push_back(cam);
1150         }
1151 }
1152
1153
1154 void KX_Scene::UpdateMeshTransformations()
1155 {
1156         // do this incrementally in the future
1157         for (int i = 0; i < m_objectlist->GetCount(); i++)
1158         {
1159                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
1160                 gameobj->GetOpenGLMatrix();
1161 //              gameobj->UpdateNonDynas();
1162         }
1163 }
1164
1165 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam, int layer)
1166 {
1167         int intersect = KX_Camera::INTERSECT;
1168         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
1169         bool visible = (gameobj && gameobj->GetVisible() && (!layer || (gameobj->GetLayer() & layer)));
1170         bool dotest = visible || node->Left() || node->Right();
1171
1172         /* If the camera is inside the box, assume intersect. */
1173         if (dotest && !node->inside( cam->NodeGetWorldPosition()))
1174         {
1175                 MT_Scalar radius = node->Radius();
1176                 MT_Point3 center = node->Center();
1177                 
1178                 intersect =  cam->SphereInsideFrustum(center, radius); 
1179                 
1180                 if (intersect == KX_Camera::INTERSECT)
1181                 {
1182                         MT_Point3 box[8];
1183                         node->get(box);
1184                         intersect = cam->BoxInsideFrustum(box);
1185                 }
1186         }
1187
1188         switch (intersect)
1189         {
1190                 case KX_Camera::OUTSIDE:
1191                         MarkSubTreeVisible(node, rasty, false, cam);
1192                         break;
1193                 case KX_Camera::INTERSECT:
1194                         if (gameobj)
1195                                 MarkVisible(rasty, gameobj, cam, layer);
1196                         if (node->Left())
1197                                 MarkVisible(node->Left(), rasty, cam, layer);
1198                         if (node->Right())
1199                                 MarkVisible(node->Right(), rasty, cam, layer);
1200                         break;
1201                 case KX_Camera::INSIDE:
1202                         MarkSubTreeVisible(node, rasty, true, cam, layer);
1203                         break;
1204         }
1205 }
1206
1207 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera* cam, int layer)
1208 {
1209         if (node->Client())
1210         {
1211                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
1212                 if (gameobj->GetVisible())
1213                 {
1214                         if (visible)
1215                         {
1216                                 int nummeshes = gameobj->GetMeshCount();
1217                                 
1218                                 // this adds the vertices to the display list
1219                                 for (int m=0;m<nummeshes;m++)
1220                                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1221                         }
1222
1223                         gameobj->SetCulled(!visible);
1224                         gameobj->UpdateBuckets(false);
1225                 }
1226         }
1227         if (node->Left())
1228                 MarkSubTreeVisible(node->Left(), rasty, visible, cam, layer);
1229         if (node->Right())
1230                 MarkSubTreeVisible(node->Right(), rasty, visible, cam, layer);
1231 }
1232
1233 void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera*  cam,int layer)
1234 {
1235         // User (Python/Actuator) has forced object invisible...
1236         if (!gameobj->GetSGNode() || !gameobj->GetVisible())
1237                 return;
1238         
1239         // Shadow lamp layers
1240         if(layer && !(gameobj->GetLayer() & layer)) {
1241                 gameobj->SetCulled(true);
1242                 gameobj->UpdateBuckets(false);
1243                 return;
1244         }
1245
1246         // If Frustum culling is off, the object is always visible.
1247         bool vis = !cam->GetFrustumCulling();
1248         
1249         // If the camera is inside this node, then the object is visible.
1250         if (!vis)
1251         {
1252                 vis = gameobj->GetSGNode()->inside( cam->GetCameraLocation() );
1253         }
1254                 
1255         // Test the object's bound sphere against the view frustum.
1256         if (!vis)
1257         {
1258                 MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
1259                 MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
1260                 switch (cam->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
1261                 {
1262                         case KX_Camera::INSIDE:
1263                                 vis = true;
1264                                 break;
1265                         case KX_Camera::OUTSIDE:
1266                                 vis = false;
1267                                 break;
1268                         case KX_Camera::INTERSECT:
1269                                 // Test the object's bound box against the view frustum.
1270                                 MT_Point3 box[8];
1271                                 gameobj->GetSGNode()->getBBox(box); 
1272                                 vis = cam->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
1273                                 break;
1274                 }
1275         }
1276         
1277         if (vis)
1278         {
1279                 int nummeshes = gameobj->GetMeshCount();
1280                 
1281                 for (int m=0;m<nummeshes;m++)
1282                 {
1283                         // this adds the vertices to the display list
1284                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1285                 }
1286                 // Visibility/ non-visibility are marked
1287                 // elsewhere now.
1288                 gameobj->SetCulled(false);
1289                 gameobj->UpdateBuckets(false);
1290         } else {
1291                 gameobj->SetCulled(true);
1292                 gameobj->UpdateBuckets(false);
1293         }
1294 }
1295
1296 void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam, int layer)
1297 {
1298 // FIXME: When tree is operational
1299 #if 1
1300         // do this incrementally in the future
1301         for (int i = 0; i < m_objectlist->GetCount(); i++)
1302         {
1303                 MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)), cam, layer);
1304         }
1305 #else
1306         if (cam->GetFrustumCulling())
1307                 MarkVisible(m_objecttree, rasty, cam, layer);
1308         else
1309                 MarkSubTreeVisible(m_objecttree, rasty, true, cam, layer);
1310 #endif
1311 }
1312
1313 // logic stuff
1314 void KX_Scene::LogicBeginFrame(double curtime)
1315 {
1316         // have a look at temp objects ...
1317         int lastobj = m_tempObjectList->GetCount() - 1;
1318         
1319         for (int i = lastobj; i >= 0; i--)
1320         {
1321                 CValue* objval = m_tempObjectList->GetValue(i);
1322                 CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
1323                 
1324                 if (propval)
1325                 {
1326                         float timeleft = propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate();
1327                         
1328                         if (timeleft > 0)
1329                         {
1330                                 propval->SetFloat(timeleft);
1331                         }
1332                         else
1333                         {
1334                                 DelayedRemoveObject(objval);
1335                                 // remove obj
1336                         }
1337                 }
1338                 else
1339                 {
1340                         // all object is the tempObjectList should have a clock
1341                 }
1342         }
1343         m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate());
1344 }
1345
1346
1347
1348 void KX_Scene::LogicUpdateFrame(double curtime, bool frame)
1349 {
1350         m_logicmgr->UpdateFrame(curtime, frame);
1351 }
1352
1353
1354
1355 void KX_Scene::LogicEndFrame()
1356 {
1357         m_logicmgr->EndFrame();
1358         int numobj = m_euthanasyobjects->GetCount();
1359         int i;
1360         for (i = numobj - 1; i >= 0; i--)
1361         {
1362                 KX_GameObject* gameobj = (KX_GameObject*)m_euthanasyobjects->GetValue(i);
1363                 // KX_Scene::RemoveObject will also remove the object from this list
1364                 // that's why we start from the end
1365                 this->RemoveObject(gameobj);
1366         }
1367
1368         numobj= m_delayReleaseObjects->GetCount();
1369         for (i = numobj-1;i>=0;i--)
1370         {
1371                 KX_GameObject* gameobj = (KX_GameObject*)m_delayReleaseObjects->GetValue(i);
1372                 // This list is not for object removal, but just object release
1373                 gameobj->Release();
1374         }
1375         // empty the list as we have removed all references
1376         m_delayReleaseObjects->Resize(0);       
1377 }
1378
1379
1380
1381 /**
1382   * UpdateParents: SceneGraph transformation update.
1383   */
1384 void KX_Scene::UpdateParents(double curtime)
1385 {
1386 //      int numrootobjects = GetRootParentList()->GetCount();
1387
1388         for (int i=0; i<GetRootParentList()->GetCount(); i++)
1389         {
1390                 KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
1391                 parentobj->NodeUpdateGS(curtime,true);
1392         }
1393 }
1394
1395
1396
1397 RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat, bool &bucketCreated)
1398 {
1399         return m_bucketmanager->FindBucket(polymat, bucketCreated);
1400 }
1401
1402
1403
1404 void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
1405                                                          class RAS_IRasterizer* rasty,
1406                                                          class RAS_IRenderTools* rendertools)
1407 {
1408         m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
1409         KX_BlenderMaterial::EndFrame();
1410 }
1411
1412 void KX_Scene::UpdateObjectActivity(void) 
1413 {
1414         if (m_activity_culling) {
1415                 /* determine the activity criterium and set objects accordingly */
1416                 int i=0;
1417                 
1418                 MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
1419                 
1420                 for (i=0;i<GetObjectList()->GetCount();i++)
1421                 {
1422                         KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
1423                         
1424                         if (!ob->GetIgnoreActivityCulling()) {
1425                                 /* Simple test: more than 10 away from the camera, count
1426                                  * Manhattan distance. */
1427                                 MT_Point3 obpos = ob->NodeGetWorldPosition();
1428                                 
1429                                 if ( (fabs(camloc[0] - obpos[0]) > m_activity_box_radius)
1430                                          || (fabs(camloc[1] - obpos[1]) > m_activity_box_radius)
1431                                          || (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
1432                                 {                       
1433                                         ob->Suspend();
1434                                 } else {
1435                                         ob->Resume();
1436                                 }
1437                         }
1438                 }               
1439         }
1440 }
1441
1442 void KX_Scene::SetActivityCullingRadius(float f)
1443 {
1444         if (f < 0.5)
1445                 f = 0.5;
1446         m_activity_box_radius = f;
1447 }
1448         
1449 NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
1450 {
1451         return m_networkDeviceInterface;
1452 }
1453
1454 NG_NetworkScene* KX_Scene::GetNetworkScene()
1455 {
1456         return m_networkScene;
1457 }
1458
1459 void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
1460 {
1461         m_networkDeviceInterface = newInterface;
1462 }
1463
1464 void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
1465 {
1466         m_networkScene = newScene;
1467 }
1468
1469
1470 void    KX_Scene::SetGravity(const MT_Vector3& gravity)
1471 {
1472         GetPhysicsEnvironment()->setGravity(gravity[0],gravity[1],gravity[2]);
1473 }
1474
1475 void KX_Scene::SetNodeTree(SG_Tree* root)
1476 {
1477         m_objecttree = root;
1478 }
1479
1480 void KX_Scene::SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter)
1481 {
1482         m_sceneConverter = sceneConverter;
1483 }
1484
1485 void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
1486 {
1487         m_physicsEnvironment = physEnv;
1488
1489         KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, physEnv);
1490         m_logicmgr->RegisterEventManager(touchmgr);
1491         return;
1492 }
1493  
1494 void KX_Scene::setSuspendedTime(double suspendedtime)
1495 {
1496         m_suspendedtime = suspendedtime;
1497 }
1498 double KX_Scene::getSuspendedTime()
1499 {
1500         return m_suspendedtime;
1501 }
1502 void KX_Scene::setSuspendedDelta(double suspendeddelta)
1503 {
1504         m_suspendeddelta = suspendeddelta;
1505 }
1506 double KX_Scene::getSuspendedDelta()
1507 {
1508         return m_suspendeddelta;
1509 }
1510
1511 //----------------------------------------------------------------------------
1512 //Python
1513
1514 PyMethodDef KX_Scene::Methods[] = {
1515         KX_PYMETHODTABLE_NOARGS(KX_Scene, getLightList),
1516         KX_PYMETHODTABLE_NOARGS(KX_Scene, getObjectList),
1517         KX_PYMETHODTABLE_NOARGS(KX_Scene, getName),
1518         
1519         {NULL,NULL} //Sentinel
1520 };
1521
1522 PyTypeObject KX_Scene::Type = {
1523         PyObject_HEAD_INIT(&PyType_Type)
1524                 0,
1525                 "KX_Scene",
1526                 sizeof(KX_Scene),
1527                 0,
1528                 PyDestructor,
1529                 0,
1530                 __getattr,
1531                 __setattr,
1532                 0, //&MyPyCompare,
1533                 __repr,
1534                 0, //&cvalue_as_number,
1535                 0,
1536                 0,
1537                 0,
1538                 0, 0, 0, 0, 0, 0
1539 };
1540
1541 PyParentObject KX_Scene::Parents[] = {
1542         &KX_Scene::Type,
1543                 &CValue::Type,
1544                 NULL
1545 };
1546
1547 PyObject* KX_Scene::_getattr(const char *attr)
1548 {
1549         if (!strcmp(attr, "name"))
1550                 return PyString_FromString(GetName());
1551         
1552         if (!strcmp(attr, "objects"))
1553                 return (PyObject*) m_objectlist->AddRef();
1554         
1555         if (!strcmp(attr, "active_camera"))
1556                 return (PyObject*) GetActiveCamera()->AddRef();
1557         
1558         if (!strcmp(attr, "suspended"))
1559                 return PyInt_FromLong(m_suspend);
1560         
1561         if (!strcmp(attr, "activity_culling"))
1562                 return PyInt_FromLong(m_activity_culling);
1563         
1564         if (!strcmp(attr, "activity_culling_radius"))
1565                 return PyFloat_FromDouble(m_activity_box_radius);
1566         
1567         PyObject* value = PyDict_GetItemString(m_attrlist, attr);
1568         if (value)
1569         {
1570                 Py_INCREF(value);
1571                 return value;
1572         }
1573         
1574         _getattr_up(PyObjectPlus);
1575 }
1576
1577 int KX_Scene::_delattr(const char *attr)
1578 {
1579         PyDict_DelItemString(m_attrlist, attr);
1580         return 0;
1581 }
1582
1583 int KX_Scene::_setattr(const char *attr, PyObject *pyvalue)
1584 {
1585         if (!PyDict_SetItemString(m_attrlist, attr, pyvalue))
1586                 return 0;
1587
1588         return PyObjectPlus::_setattr(attr, pyvalue);
1589 }
1590
1591 KX_PYMETHODDEF_DOC_NOARGS(KX_Scene, getLightList,
1592 "getLightList() -> list [KX_Light]\n"
1593 "Returns a list of all lights in the scene.\n"
1594 )
1595 {
1596         return (PyObject*) m_lightlist->AddRef();
1597 }
1598
1599 KX_PYMETHODDEF_DOC_NOARGS(KX_Scene, getObjectList,
1600 "getObjectList() -> list [KX_GameObject]\n"
1601 "Returns a list of all game objects in the scene.\n"
1602 )
1603 {
1604         // ShowDeprecationWarning("getObjectList()", "the objects property"); // XXX Grr, why doesnt this work?
1605         return (PyObject*) m_objectlist->AddRef();
1606 }
1607
1608 KX_PYMETHODDEF_DOC_NOARGS(KX_Scene, getName,
1609 "getName() -> string\n"
1610 "Returns the name of the scene.\n"
1611 )
1612 {
1613         return PyString_FromString(GetName());
1614 }