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