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