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