Py BGE API
[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                         
1018                         if (oldblendobj==NULL) {
1019                                 std::cout << "warning: ReplaceMesh() new mesh is not used in an object from the current scene, you will get incorrect behavior" << std::endl;
1020                                 bHasShapeKey= bHasDvert= bHasArmature= false;
1021                         }
1022                         
1023                         if (bHasShapeKey)
1024                         {
1025                                 BL_ShapeDeformer* shapeDeformer;
1026                                 if (bHasArmature) 
1027                                 {
1028                                         shapeDeformer = new BL_ShapeDeformer(
1029                                                 newobj,
1030                                                 oldblendobj, blendobj,
1031                                                 static_cast<BL_SkinMeshObject*>(mesh),
1032                                                 true,
1033                                                 static_cast<BL_ArmatureObject*>( parentobj )
1034                                         );
1035                                         releaseParent= false;
1036                                         shapeDeformer->LoadShapeDrivers(blendobj->parent);
1037                                 }
1038                                 else
1039                                 {
1040                                         shapeDeformer = new BL_ShapeDeformer(
1041                                                 newobj,
1042                                                 oldblendobj, blendobj,
1043                                                 static_cast<BL_SkinMeshObject*>(mesh),
1044                                                 false,
1045                                                 NULL
1046                                         );
1047                                 }
1048                                 newobj->SetDeformer( shapeDeformer);
1049                         }
1050                         else if (bHasArmature) 
1051                         {
1052                                 BL_SkinDeformer* skinDeformer = new BL_SkinDeformer(
1053                                         newobj,
1054                                         oldblendobj, blendobj,
1055                                         static_cast<BL_SkinMeshObject*>(mesh),
1056                                         true,
1057                                         static_cast<BL_ArmatureObject*>( parentobj )
1058                                 );
1059                                 releaseParent= false;
1060                                 newobj->SetDeformer(skinDeformer);
1061                         }
1062                         else if (bHasDvert)
1063                         {
1064                                 BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
1065                                         newobj, oldblendobj, static_cast<BL_SkinMeshObject*>(mesh)
1066                                 );
1067                                 newobj->SetDeformer(meshdeformer);
1068                         }
1069
1070                         // release parent reference if its not being used 
1071                         if( releaseParent && parentobj)
1072                                 parentobj->Release();
1073                 }
1074         }
1075
1076         gameobj->AddMeshUser();
1077 }
1078
1079
1080
1081 MT_CmMatrix4x4& KX_Scene::GetViewMatrix()
1082 {
1083         MT_Scalar cammat[16];
1084         m_active_camera->GetWorldToCamera().getValue(cammat);
1085         m_viewmat = cammat;
1086         return m_viewmat;
1087 }
1088
1089
1090
1091 MT_CmMatrix4x4& KX_Scene::GetProjectionMatrix()
1092 {
1093         return m_projectionmat;
1094 }
1095
1096
1097 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
1098 {
1099         list<KX_Camera*>::iterator it = m_cameras.begin();
1100
1101         while ( (it != m_cameras.end()) 
1102                         && ((*it) != cam) ) {
1103           it++;
1104         }
1105
1106         return ((it == m_cameras.end()) ? NULL : (*it));
1107 }
1108
1109
1110 KX_Camera* KX_Scene::FindCamera(STR_String& name)
1111 {
1112         list<KX_Camera*>::iterator it = m_cameras.begin();
1113
1114         while ( (it != m_cameras.end()) 
1115                         && ((*it)->GetName() != name) ) {
1116           it++;
1117         }
1118
1119         return ((it == m_cameras.end()) ? NULL : (*it));
1120 }
1121
1122 void KX_Scene::AddCamera(KX_Camera* cam)
1123 {
1124         if (!FindCamera(cam))
1125                 m_cameras.push_back(cam);
1126 }
1127
1128
1129 KX_Camera* KX_Scene::GetActiveCamera()
1130 {       
1131         // NULL if not defined
1132         return m_active_camera;
1133 }
1134
1135
1136 void KX_Scene::SetActiveCamera(KX_Camera* cam)
1137 {
1138         // only set if the cam is in the active list? Or add it otherwise?
1139         if (!FindCamera(cam)){
1140                 AddCamera(cam);
1141                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1142         } 
1143
1144         m_active_camera = cam;
1145 }
1146
1147 void KX_Scene::SetCameraOnTop(KX_Camera* cam)
1148 {
1149         if (!FindCamera(cam)){
1150                 // adding is always done at the back, so that's all that needs to be done
1151                 AddCamera(cam);
1152                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1153         } else {
1154                 m_cameras.remove(cam);
1155                 m_cameras.push_back(cam);
1156         }
1157 }
1158
1159
1160 void KX_Scene::UpdateMeshTransformations()
1161 {
1162         // do this incrementally in the future
1163         for (int i = 0; i < m_objectlist->GetCount(); i++)
1164         {
1165                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
1166                 gameobj->GetOpenGLMatrix();
1167 //              gameobj->UpdateNonDynas();
1168         }
1169 }
1170
1171 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam, int layer)
1172 {
1173         int intersect = KX_Camera::INTERSECT;
1174         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
1175         bool visible = (gameobj && gameobj->GetVisible() && (!layer || (gameobj->GetLayer() & layer)));
1176         bool dotest = visible || node->Left() || node->Right();
1177
1178         /* If the camera is inside the box, assume intersect. */
1179         if (dotest && !node->inside( cam->NodeGetWorldPosition()))
1180         {
1181                 MT_Scalar radius = node->Radius();
1182                 MT_Point3 center = node->Center();
1183                 
1184                 intersect =  cam->SphereInsideFrustum(center, radius); 
1185                 
1186                 if (intersect == KX_Camera::INTERSECT)
1187                 {
1188                         MT_Point3 box[8];
1189                         node->get(box);
1190                         intersect = cam->BoxInsideFrustum(box);
1191                 }
1192         }
1193
1194         switch (intersect)
1195         {
1196                 case KX_Camera::OUTSIDE:
1197                         MarkSubTreeVisible(node, rasty, false, cam);
1198                         break;
1199                 case KX_Camera::INTERSECT:
1200                         if (gameobj)
1201                                 MarkVisible(rasty, gameobj, cam, layer);
1202                         if (node->Left())
1203                                 MarkVisible(node->Left(), rasty, cam, layer);
1204                         if (node->Right())
1205                                 MarkVisible(node->Right(), rasty, cam, layer);
1206                         break;
1207                 case KX_Camera::INSIDE:
1208                         MarkSubTreeVisible(node, rasty, true, cam, layer);
1209                         break;
1210         }
1211 }
1212
1213 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera* cam, int layer)
1214 {
1215         if (node->Client())
1216         {
1217                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
1218                 if (gameobj->GetVisible())
1219                 {
1220                         if (visible)
1221                         {
1222                                 int nummeshes = gameobj->GetMeshCount();
1223                                 
1224                                 // this adds the vertices to the display list
1225                                 for (int m=0;m<nummeshes;m++)
1226                                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1227                         }
1228
1229                         gameobj->SetCulled(!visible);
1230                         gameobj->UpdateBuckets(false);
1231                 }
1232         }
1233         if (node->Left())
1234                 MarkSubTreeVisible(node->Left(), rasty, visible, cam, layer);
1235         if (node->Right())
1236                 MarkSubTreeVisible(node->Right(), rasty, visible, cam, layer);
1237 }
1238
1239 void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera*  cam,int layer)
1240 {
1241         // User (Python/Actuator) has forced object invisible...
1242         if (!gameobj->GetSGNode() || !gameobj->GetVisible())
1243                 return;
1244         
1245         // Shadow lamp layers
1246         if(layer && !(gameobj->GetLayer() & layer)) {
1247                 gameobj->SetCulled(true);
1248                 gameobj->UpdateBuckets(false);
1249                 return;
1250         }
1251
1252         // If Frustum culling is off, the object is always visible.
1253         bool vis = !cam->GetFrustumCulling();
1254         
1255         // If the camera is inside this node, then the object is visible.
1256         if (!vis)
1257         {
1258                 vis = gameobj->GetSGNode()->inside( cam->GetCameraLocation() );
1259         }
1260                 
1261         // Test the object's bound sphere against the view frustum.
1262         if (!vis)
1263         {
1264                 MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
1265                 MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
1266                 switch (cam->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
1267                 {
1268                         case KX_Camera::INSIDE:
1269                                 vis = true;
1270                                 break;
1271                         case KX_Camera::OUTSIDE:
1272                                 vis = false;
1273                                 break;
1274                         case KX_Camera::INTERSECT:
1275                                 // Test the object's bound box against the view frustum.
1276                                 MT_Point3 box[8];
1277                                 gameobj->GetSGNode()->getBBox(box); 
1278                                 vis = cam->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
1279                                 break;
1280                 }
1281         }
1282         
1283         if (vis)
1284         {
1285                 int nummeshes = gameobj->GetMeshCount();
1286                 
1287                 for (int m=0;m<nummeshes;m++)
1288                 {
1289                         // this adds the vertices to the display list
1290                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1291                 }
1292                 // Visibility/ non-visibility are marked
1293                 // elsewhere now.
1294                 gameobj->SetCulled(false);
1295                 gameobj->UpdateBuckets(false);
1296         } else {
1297                 gameobj->SetCulled(true);
1298                 gameobj->UpdateBuckets(false);
1299         }
1300 }
1301
1302 void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam, int layer)
1303 {
1304 // FIXME: When tree is operational
1305 #if 1
1306         // do this incrementally in the future
1307         for (int i = 0; i < m_objectlist->GetCount(); i++)
1308         {
1309                 MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)), cam, layer);
1310         }
1311 #else
1312         if (cam->GetFrustumCulling())
1313                 MarkVisible(m_objecttree, rasty, cam, layer);
1314         else
1315                 MarkSubTreeVisible(m_objecttree, rasty, true, cam, layer);
1316 #endif
1317 }
1318
1319 // logic stuff
1320 void KX_Scene::LogicBeginFrame(double curtime)
1321 {
1322         // have a look at temp objects ...
1323         int lastobj = m_tempObjectList->GetCount() - 1;
1324         
1325         for (int i = lastobj; i >= 0; i--)
1326         {
1327                 CValue* objval = m_tempObjectList->GetValue(i);
1328                 CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
1329                 
1330                 if (propval)
1331                 {
1332                         float timeleft = propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate();
1333                         
1334                         if (timeleft > 0)
1335                         {
1336                                 propval->SetFloat(timeleft);
1337                         }
1338                         else
1339                         {
1340                                 DelayedRemoveObject(objval);
1341                                 // remove obj
1342                         }
1343                 }
1344                 else
1345                 {
1346                         // all object is the tempObjectList should have a clock
1347                 }
1348         }
1349         m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate());
1350 }
1351
1352
1353
1354 void KX_Scene::LogicUpdateFrame(double curtime, bool frame)
1355 {
1356         m_logicmgr->UpdateFrame(curtime, frame);
1357 }
1358
1359
1360
1361 void KX_Scene::LogicEndFrame()
1362 {
1363         m_logicmgr->EndFrame();
1364         int numobj = m_euthanasyobjects->GetCount();
1365         int i;
1366         for (i = numobj - 1; i >= 0; i--)
1367         {
1368                 KX_GameObject* gameobj = (KX_GameObject*)m_euthanasyobjects->GetValue(i);
1369                 // KX_Scene::RemoveObject will also remove the object from this list
1370                 // that's why we start from the end
1371                 this->RemoveObject(gameobj);
1372         }
1373
1374         numobj= m_delayReleaseObjects->GetCount();
1375         for (i = numobj-1;i>=0;i--)
1376         {
1377                 KX_GameObject* gameobj = (KX_GameObject*)m_delayReleaseObjects->GetValue(i);
1378                 // This list is not for object removal, but just object release
1379                 gameobj->Release();
1380         }
1381         // empty the list as we have removed all references
1382         m_delayReleaseObjects->Resize(0);       
1383 }
1384
1385
1386
1387 /**
1388   * UpdateParents: SceneGraph transformation update.
1389   */
1390 void KX_Scene::UpdateParents(double curtime)
1391 {
1392 //      int numrootobjects = GetRootParentList()->GetCount();
1393
1394         for (int i=0; i<GetRootParentList()->GetCount(); i++)
1395         {
1396                 KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
1397                 parentobj->NodeUpdateGS(curtime,true);
1398         }
1399 }
1400
1401
1402
1403 RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat, bool &bucketCreated)
1404 {
1405         return m_bucketmanager->FindBucket(polymat, bucketCreated);
1406 }
1407
1408
1409
1410 void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
1411                                                          class RAS_IRasterizer* rasty,
1412                                                          class RAS_IRenderTools* rendertools)
1413 {
1414         m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
1415         KX_BlenderMaterial::EndFrame();
1416 }
1417
1418 void KX_Scene::UpdateObjectActivity(void) 
1419 {
1420         if (m_activity_culling) {
1421                 /* determine the activity criterium and set objects accordingly */
1422                 int i=0;
1423                 
1424                 MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
1425                 
1426                 for (i=0;i<GetObjectList()->GetCount();i++)
1427                 {
1428                         KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
1429                         
1430                         if (!ob->GetIgnoreActivityCulling()) {
1431                                 /* Simple test: more than 10 away from the camera, count
1432                                  * Manhattan distance. */
1433                                 MT_Point3 obpos = ob->NodeGetWorldPosition();
1434                                 
1435                                 if ( (fabs(camloc[0] - obpos[0]) > m_activity_box_radius)
1436                                          || (fabs(camloc[1] - obpos[1]) > m_activity_box_radius)
1437                                          || (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
1438                                 {                       
1439                                         ob->Suspend();
1440                                 } else {
1441                                         ob->Resume();
1442                                 }
1443                         }
1444                 }               
1445         }
1446 }
1447
1448 void KX_Scene::SetActivityCullingRadius(float f)
1449 {
1450         if (f < 0.5)
1451                 f = 0.5;
1452         m_activity_box_radius = f;
1453 }
1454         
1455 NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
1456 {
1457         return m_networkDeviceInterface;
1458 }
1459
1460 NG_NetworkScene* KX_Scene::GetNetworkScene()
1461 {
1462         return m_networkScene;
1463 }
1464
1465 void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
1466 {
1467         m_networkDeviceInterface = newInterface;
1468 }
1469
1470 void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
1471 {
1472         m_networkScene = newScene;
1473 }
1474
1475
1476 void    KX_Scene::SetGravity(const MT_Vector3& gravity)
1477 {
1478         GetPhysicsEnvironment()->setGravity(gravity[0],gravity[1],gravity[2]);
1479 }
1480
1481 void KX_Scene::SetNodeTree(SG_Tree* root)
1482 {
1483         m_objecttree = root;
1484 }
1485
1486 void KX_Scene::SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter)
1487 {
1488         m_sceneConverter = sceneConverter;
1489 }
1490
1491 void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
1492 {
1493         m_physicsEnvironment = physEnv;
1494
1495         KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, physEnv);
1496         m_logicmgr->RegisterEventManager(touchmgr);
1497         return;
1498 }
1499  
1500 void KX_Scene::setSuspendedTime(double suspendedtime)
1501 {
1502         m_suspendedtime = suspendedtime;
1503 }
1504 double KX_Scene::getSuspendedTime()
1505 {
1506         return m_suspendedtime;
1507 }
1508 void KX_Scene::setSuspendedDelta(double suspendeddelta)
1509 {
1510         m_suspendeddelta = suspendeddelta;
1511 }
1512 double KX_Scene::getSuspendedDelta()
1513 {
1514         return m_suspendeddelta;
1515 }
1516
1517 //----------------------------------------------------------------------------
1518 //Python
1519
1520 PyMethodDef KX_Scene::Methods[] = {
1521         KX_PYMETHODTABLE_NOARGS(KX_Scene, getLightList),
1522         KX_PYMETHODTABLE_NOARGS(KX_Scene, getObjectList),
1523         KX_PYMETHODTABLE_NOARGS(KX_Scene, getName),
1524         
1525         {NULL,NULL} //Sentinel
1526 };
1527
1528 PyAttributeDef KX_Scene::Attributes[] = {
1529         { NULL }        //Sentinel
1530 };
1531
1532 PyTypeObject KX_Scene::Type = {
1533         PyObject_HEAD_INIT(&PyType_Type)
1534                 0,
1535                 "KX_Scene",
1536                 sizeof(KX_Scene),
1537                 0,
1538                 PyDestructor,
1539                 0,
1540                 __getattr,
1541                 __setattr,
1542                 0, //&MyPyCompare,
1543                 __repr,
1544                 0, //&cvalue_as_number,
1545                 0,
1546                 0,
1547                 0,
1548                 0, 0, 0, 0, 0, 0
1549 };
1550
1551 PyParentObject KX_Scene::Parents[] = {
1552         &KX_Scene::Type,
1553                 &CValue::Type,
1554                 NULL
1555 };
1556
1557 PyObject* KX_Scene::_getattr(const char *attr)
1558 {
1559         if (!strcmp(attr, "name"))
1560                 return PyString_FromString(GetName());
1561         
1562         if (!strcmp(attr, "objects"))
1563                 return (PyObject*) m_objectlist->AddRef();
1564         
1565         if (!strcmp(attr, "active_camera"))
1566                 return (PyObject*) GetActiveCamera()->AddRef();
1567         
1568         if (!strcmp(attr, "suspended"))
1569                 return PyInt_FromLong(m_suspend);
1570         
1571         if (!strcmp(attr, "activity_culling"))
1572                 return PyInt_FromLong(m_activity_culling);
1573         
1574         if (!strcmp(attr, "activity_culling_radius"))
1575                 return PyFloat_FromDouble(m_activity_box_radius);
1576         
1577         PyObject* value = PyDict_GetItemString(m_attrlist, attr);
1578         if (value)
1579         {
1580                 Py_INCREF(value);
1581                 return value;
1582         }
1583         
1584         _getattr_up(PyObjectPlus);
1585 }
1586
1587 int KX_Scene::_delattr(const char *attr)
1588 {
1589         PyDict_DelItemString(m_attrlist, attr);
1590         return 0;
1591 }
1592
1593 int KX_Scene::_setattr(const char *attr, PyObject *pyvalue)
1594 {
1595         if (!PyDict_SetItemString(m_attrlist, attr, pyvalue))
1596                 return 0;
1597
1598         return PyObjectPlus::_setattr(attr, pyvalue);
1599 }
1600
1601 KX_PYMETHODDEF_DOC_NOARGS(KX_Scene, getLightList,
1602 "getLightList() -> list [KX_Light]\n"
1603 "Returns a list of all lights in the scene.\n"
1604 )
1605 {
1606         return (PyObject*) m_lightlist->AddRef();
1607 }
1608
1609 KX_PYMETHODDEF_DOC_NOARGS(KX_Scene, getObjectList,
1610 "getObjectList() -> list [KX_GameObject]\n"
1611 "Returns a list of all game objects in the scene.\n"
1612 )
1613 {
1614         // ShowDeprecationWarning("getObjectList()", "the objects property"); // XXX Grr, why doesnt this work?
1615         return (PyObject*) m_objectlist->AddRef();
1616 }
1617
1618 KX_PYMETHODDEF_DOC_NOARGS(KX_Scene, getName,
1619 "getName() -> string\n"
1620 "Returns the name of the scene.\n"
1621 )
1622 {
1623         return PyString_FromString(GetName());
1624 }