gameObject -> blenderObject mapping was being created but wasnt needed.
[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(&KX_Scene::Type),
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         /* currently does nothing, keep incase we need to Unregister something */
1012 #if 0
1013         if (m_sceneConverter)
1014                 m_sceneConverter->UnregisterGameObject(newobj);
1015 #endif
1016         
1017         // return value will be 0 if the object is actually deleted (all reference gone)
1018         
1019         return ret;
1020 }
1021
1022
1023
1024 void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj, bool use_gfx, bool use_phys)
1025 {
1026         KX_GameObject* gameobj = static_cast<KX_GameObject*>(obj);
1027         RAS_MeshObject* mesh = static_cast<RAS_MeshObject*>(meshobj);
1028
1029         if(!gameobj) {
1030                 std::cout << "KX_Scene::ReplaceMesh Warning: invalid object, doing nothing" << std::endl;
1031                 return;
1032         }
1033         
1034         if(use_gfx && mesh != NULL)
1035         {               
1036                 gameobj->RemoveMeshes();
1037                 gameobj->AddMesh(mesh);
1038                 
1039                 if (gameobj->m_isDeformable)
1040                 {
1041                         BL_DeformableGameObject* newobj = static_cast<BL_DeformableGameObject*>( gameobj );
1042                         
1043                         if (newobj->GetDeformer())
1044                         {
1045                                 delete newobj->GetDeformer();
1046                                 newobj->SetDeformer(NULL);
1047                         }
1048         
1049                         if (mesh->IsDeformed())
1050                         {
1051                                 // we must create a new deformer but which one?
1052                                 KX_GameObject* parentobj = newobj->GetParent();
1053                                 // this always return the original game object (also for replicate)
1054                                 Object* blendobj = newobj->GetBlenderObject();
1055                                 // object that owns the new mesh
1056                                 Object* oldblendobj = static_cast<struct Object*>(m_logicmgr->FindBlendObjByGameMeshName(mesh->GetName()));
1057                                 Mesh* blendmesh = mesh->GetMesh();
1058         
1059                                 bool bHasModifier = BL_ModifierDeformer::HasCompatibleDeformer(blendobj);
1060                                 bool bHasShapeKey = blendmesh->key != NULL && blendmesh->key->type==KEY_RELATIVE;
1061                                 bool bHasDvert = blendmesh->dvert != NULL;
1062                                 bool bHasArmature = 
1063                                         parentobj &&                                                            // current parent is armature
1064                                         parentobj->GetGameObjectType() == SCA_IObject::OBJ_ARMATURE &&
1065                                         oldblendobj &&                                                          // needed for mesh deform
1066                                         blendobj->parent &&                                                     // original object had armature (not sure this test is needed)
1067                                         blendobj->parent->type == OB_ARMATURE && 
1068                                         blendobj->partype==PARSKEL && 
1069                                         blendmesh->dvert!=NULL;                                         // mesh has vertex group
1070                                 bool releaseParent = true;
1071         
1072                                 
1073                                 if (oldblendobj==NULL) {
1074                                         std::cout << "warning: ReplaceMesh() new mesh is not used in an object from the current scene, you will get incorrect behavior" << std::endl;
1075                                         bHasShapeKey= bHasDvert= bHasArmature=bHasModifier= false;
1076                                 }
1077                                 
1078                                 if (bHasModifier)
1079                                 {
1080                                         BL_ModifierDeformer* modifierDeformer;
1081                                         if (bHasShapeKey || bHasArmature)
1082                                         {
1083                                                 modifierDeformer = new BL_ModifierDeformer(
1084                                                         newobj,
1085                                                         oldblendobj, blendobj,
1086                                                         static_cast<BL_SkinMeshObject*>(mesh),
1087                                                         true,
1088                                                         static_cast<BL_ArmatureObject*>( parentobj )
1089                                                 );
1090                                                 releaseParent= false;
1091                                                 modifierDeformer->LoadShapeDrivers(blendobj->parent);
1092                                         }
1093                                         else
1094                                         {
1095                                                 modifierDeformer = new BL_ModifierDeformer(
1096                                                         newobj,
1097                                                         oldblendobj, blendobj,
1098                                                         static_cast<BL_SkinMeshObject*>(mesh),
1099                                                         false,
1100                                                         NULL
1101                                                 );
1102                                         }
1103                                         newobj->SetDeformer(modifierDeformer);
1104                                 } 
1105                                 else    if (bHasShapeKey)
1106                                 {
1107                                         BL_ShapeDeformer* shapeDeformer;
1108                                         if (bHasArmature) 
1109                                         {
1110                                                 shapeDeformer = new BL_ShapeDeformer(
1111                                                         newobj,
1112                                                         oldblendobj, blendobj,
1113                                                         static_cast<BL_SkinMeshObject*>(mesh),
1114                                                         true,
1115                                                         true,
1116                                                         static_cast<BL_ArmatureObject*>( parentobj )
1117                                                 );
1118                                                 releaseParent= false;
1119                                                 shapeDeformer->LoadShapeDrivers(blendobj->parent);
1120                                         }
1121                                         else
1122                                         {
1123                                                 shapeDeformer = new BL_ShapeDeformer(
1124                                                         newobj,
1125                                                         oldblendobj, blendobj,
1126                                                         static_cast<BL_SkinMeshObject*>(mesh),
1127                                                         false,
1128                                                         true,
1129                                                         NULL
1130                                                 );
1131                                         }
1132                                         newobj->SetDeformer( shapeDeformer);
1133                                 }
1134                                 else if (bHasArmature) 
1135                                 {
1136                                         BL_SkinDeformer* skinDeformer = new BL_SkinDeformer(
1137                                                 newobj,
1138                                                 oldblendobj, blendobj,
1139                                                 static_cast<BL_SkinMeshObject*>(mesh),
1140                                                 true,
1141                                                 true,
1142                                                 static_cast<BL_ArmatureObject*>( parentobj )
1143                                         );
1144                                         releaseParent= false;
1145                                         newobj->SetDeformer(skinDeformer);
1146                                 }
1147                                 else if (bHasDvert)
1148                                 {
1149                                         BL_MeshDeformer* meshdeformer = new BL_MeshDeformer(
1150                                                 newobj, oldblendobj, static_cast<BL_SkinMeshObject*>(mesh)
1151                                         );
1152                                         newobj->SetDeformer(meshdeformer);
1153                                 }
1154         
1155                                 // release parent reference if its not being used 
1156                                 if( releaseParent && parentobj)
1157                                         parentobj->Release();
1158                         }
1159                 }
1160
1161                 gameobj->AddMeshUser();
1162         }
1163         
1164         if(use_phys) { /* update the new assigned mesh with the physics mesh */
1165                 KX_ReInstanceBulletShapeFromMesh(gameobj, NULL, use_gfx?NULL:mesh);
1166         }
1167 }
1168
1169 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
1170 {
1171         list<KX_Camera*>::iterator it = m_cameras.begin();
1172
1173         while ( (it != m_cameras.end()) 
1174                         && ((*it) != cam) ) {
1175           it++;
1176         }
1177
1178         return ((it == m_cameras.end()) ? NULL : (*it));
1179 }
1180
1181
1182 KX_Camera* KX_Scene::FindCamera(STR_String& name)
1183 {
1184         list<KX_Camera*>::iterator it = m_cameras.begin();
1185
1186         while ( (it != m_cameras.end()) 
1187                         && ((*it)->GetName() != name) ) {
1188           it++;
1189         }
1190
1191         return ((it == m_cameras.end()) ? NULL : (*it));
1192 }
1193
1194 void KX_Scene::AddCamera(KX_Camera* cam)
1195 {
1196         if (!FindCamera(cam))
1197                 m_cameras.push_back(cam);
1198 }
1199
1200
1201 KX_Camera* KX_Scene::GetActiveCamera()
1202 {       
1203         // NULL if not defined
1204         return m_active_camera;
1205 }
1206
1207
1208 void KX_Scene::SetActiveCamera(KX_Camera* cam)
1209 {
1210         // only set if the cam is in the active list? Or add it otherwise?
1211         if (!FindCamera(cam)){
1212                 AddCamera(cam);
1213                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1214         } 
1215
1216         m_active_camera = cam;
1217 }
1218
1219 void KX_Scene::SetCameraOnTop(KX_Camera* cam)
1220 {
1221         if (!FindCamera(cam)){
1222                 // adding is always done at the back, so that's all that needs to be done
1223                 AddCamera(cam);
1224                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
1225         } else {
1226                 m_cameras.remove(cam);
1227                 m_cameras.push_back(cam);
1228         }
1229 }
1230
1231
1232 void KX_Scene::UpdateMeshTransformations()
1233 {
1234         // do this incrementally in the future
1235         for (int i = 0; i < m_objectlist->GetCount(); i++)
1236         {
1237                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
1238                 gameobj->GetOpenGLMatrix();
1239         }
1240 }
1241
1242 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty, KX_Camera* cam, int layer)
1243 {
1244         int intersect = KX_Camera::INTERSECT;
1245         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
1246         bool visible = (gameobj && gameobj->GetVisible() && (!layer || (gameobj->GetLayer() & layer)));
1247         bool dotest = visible || node->Left() || node->Right();
1248
1249         /* If the camera is inside the box, assume intersect. */
1250         if (dotest && !node->inside( cam->NodeGetWorldPosition()))
1251         {
1252                 MT_Scalar radius = node->Radius();
1253                 MT_Point3 center = node->Center();
1254                 
1255                 intersect =  cam->SphereInsideFrustum(center, radius); 
1256                 
1257                 if (intersect == KX_Camera::INTERSECT)
1258                 {
1259                         MT_Point3 box[8];
1260                         node->get(box);
1261                         intersect = cam->BoxInsideFrustum(box);
1262                 }
1263         }
1264
1265         switch (intersect)
1266         {
1267                 case KX_Camera::OUTSIDE:
1268                         MarkSubTreeVisible(node, rasty, false, cam);
1269                         break;
1270                 case KX_Camera::INTERSECT:
1271                         if (gameobj)
1272                                 MarkVisible(rasty, gameobj, cam, layer);
1273                         if (node->Left())
1274                                 MarkVisible(node->Left(), rasty, cam, layer);
1275                         if (node->Right())
1276                                 MarkVisible(node->Right(), rasty, cam, layer);
1277                         break;
1278                 case KX_Camera::INSIDE:
1279                         MarkSubTreeVisible(node, rasty, true, cam, layer);
1280                         break;
1281         }
1282 }
1283
1284 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible, KX_Camera* cam, int layer)
1285 {
1286         if (node->Client())
1287         {
1288                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
1289                 if (gameobj->GetVisible())
1290                 {
1291                         if (visible)
1292                         {
1293                                 int nummeshes = gameobj->GetMeshCount();
1294                                 
1295                                 // this adds the vertices to the display list
1296                                 for (int m=0;m<nummeshes;m++)
1297                                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1298                         }
1299
1300                         gameobj->SetCulled(!visible);
1301                         gameobj->UpdateBuckets(false);
1302                 }
1303         }
1304         if (node->Left())
1305                 MarkSubTreeVisible(node->Left(), rasty, visible, cam, layer);
1306         if (node->Right())
1307                 MarkSubTreeVisible(node->Right(), rasty, visible, cam, layer);
1308 }
1309
1310 void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Camera*  cam,int layer)
1311 {
1312         // User (Python/Actuator) has forced object invisible...
1313         if (!gameobj->GetSGNode() || !gameobj->GetVisible())
1314                 return;
1315         
1316         // Shadow lamp layers
1317         if(layer && !(gameobj->GetLayer() & layer)) {
1318                 gameobj->SetCulled(true);
1319                 gameobj->UpdateBuckets(false);
1320                 return;
1321         }
1322
1323         // If Frustum culling is off, the object is always visible.
1324         bool vis = !cam->GetFrustumCulling();
1325         
1326         // If the camera is inside this node, then the object is visible.
1327         if (!vis)
1328         {
1329                 vis = gameobj->GetSGNode()->inside( cam->GetCameraLocation() );
1330         }
1331                 
1332         // Test the object's bound sphere against the view frustum.
1333         if (!vis)
1334         {
1335                 MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
1336                 MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
1337                 switch (cam->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
1338                 {
1339                         case KX_Camera::INSIDE:
1340                                 vis = true;
1341                                 break;
1342                         case KX_Camera::OUTSIDE:
1343                                 vis = false;
1344                                 break;
1345                         case KX_Camera::INTERSECT:
1346                                 // Test the object's bound box against the view frustum.
1347                                 MT_Point3 box[8];
1348                                 gameobj->GetSGNode()->getBBox(box); 
1349                                 vis = cam->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
1350                                 break;
1351                 }
1352         }
1353         
1354         if (vis)
1355         {
1356                 int nummeshes = gameobj->GetMeshCount();
1357                 
1358                 for (int m=0;m<nummeshes;m++)
1359                 {
1360                         // this adds the vertices to the display list
1361                         (gameobj->GetMesh(m))->SchedulePolygons(rasty->GetDrawingMode());
1362                 }
1363                 // Visibility/ non-visibility are marked
1364                 // elsewhere now.
1365                 gameobj->SetCulled(false);
1366                 gameobj->UpdateBuckets(false);
1367         } else {
1368                 gameobj->SetCulled(true);
1369                 gameobj->UpdateBuckets(false);
1370         }
1371 }
1372
1373 void KX_Scene::PhysicsCullingCallback(KX_ClientObjectInfo* objectInfo, void* cullingInfo)
1374 {
1375         KX_GameObject* gameobj = objectInfo->m_gameobject;
1376         if (!gameobj->GetVisible())
1377                 // ideally, invisible objects should be removed from the culling tree temporarily
1378                 return;
1379         if(((CullingInfo*)cullingInfo)->m_layer && !(gameobj->GetLayer() & ((CullingInfo*)cullingInfo)->m_layer))
1380                 // used for shadow: object is not in shadow layer
1381                 return;
1382
1383         // make object visible
1384         gameobj->SetCulled(false);
1385         gameobj->UpdateBuckets(false);
1386 }
1387
1388 void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty,KX_Camera* cam, int layer)
1389 {
1390         bool dbvt_culling = false;
1391         if (m_dbvt_culling) 
1392         {
1393                 // test culling through Bullet
1394                 PHY__Vector4 planes[6];
1395                 // get the clip planes
1396                 MT_Vector4* cplanes = cam->GetNormalizedClipPlanes();
1397                 // and convert
1398                 planes[0].setValue(cplanes[4].getValue());      // near
1399                 planes[1].setValue(cplanes[5].getValue());      // far
1400                 planes[2].setValue(cplanes[0].getValue());      // left
1401                 planes[3].setValue(cplanes[1].getValue());      // right
1402                 planes[4].setValue(cplanes[2].getValue());      // top
1403                 planes[5].setValue(cplanes[3].getValue());      // bottom
1404                 CullingInfo info(layer);
1405                 dbvt_culling = m_physicsEnvironment->cullingTest(PhysicsCullingCallback,&info,planes,5,m_dbvt_occlusion_res);
1406         }
1407         if (!dbvt_culling) {
1408                 // the physics engine couldn't help us, do it the hard way
1409                 for (int i = 0; i < m_objectlist->GetCount(); i++)
1410                 {
1411                         MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)), cam, layer);
1412                 }
1413         }
1414 }
1415
1416 // logic stuff
1417 void KX_Scene::LogicBeginFrame(double curtime)
1418 {
1419         // have a look at temp objects ...
1420         int lastobj = m_tempObjectList->GetCount() - 1;
1421         
1422         for (int i = lastobj; i >= 0; i--)
1423         {
1424                 CValue* objval = m_tempObjectList->GetValue(i);
1425                 CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
1426                 
1427                 if (propval)
1428                 {
1429                         float timeleft = propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate();
1430                         
1431                         if (timeleft > 0)
1432                         {
1433                                 propval->SetFloat(timeleft);
1434                         }
1435                         else
1436                         {
1437                                 DelayedRemoveObject(objval);
1438                                 // remove obj
1439                         }
1440                 }
1441                 else
1442                 {
1443                         // all object is the tempObjectList should have a clock
1444                 }
1445         }
1446         m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate());
1447 }
1448
1449
1450
1451 void KX_Scene::LogicUpdateFrame(double curtime, bool frame)
1452 {
1453         m_logicmgr->UpdateFrame(curtime, frame);
1454 }
1455
1456
1457
1458 void KX_Scene::LogicEndFrame()
1459 {
1460         m_logicmgr->EndFrame();
1461         int numobj = m_euthanasyobjects->GetCount();
1462
1463         KX_GameObject* obj;
1464
1465         while ((numobj = m_euthanasyobjects->GetCount()) > 0)
1466         {
1467                 // remove the object from this list to make sure we will not hit it again
1468                 obj = (KX_GameObject*)m_euthanasyobjects->GetValue(numobj-1);
1469                 m_euthanasyobjects->Remove(numobj-1);
1470                 obj->Release();
1471                 RemoveObject(obj);
1472         }
1473 }
1474
1475
1476
1477 /**
1478   * UpdateParents: SceneGraph transformation update.
1479   */
1480 void KX_Scene::UpdateParents(double curtime)
1481 {
1482         // we use the SG dynamic list
1483         SG_Node* node;
1484
1485         while ((node = SG_Node::GetNextScheduled(m_sghead)) != NULL)
1486         {
1487                 node->UpdateWorldData(curtime);
1488         }
1489
1490         //for (int i=0; i<GetRootParentList()->GetCount(); i++)
1491         //{
1492         //      KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
1493         //      parentobj->NodeUpdateGS(curtime);
1494         //}
1495
1496         // the list must be empty here
1497         assert(m_sghead.Empty());
1498         // some nodes may be ready for reschedule, move them to schedule list for next time
1499         while ((node = SG_Node::GetNextRescheduled(m_sghead)) != NULL)
1500         {
1501                 node->Schedule(m_sghead);
1502         }
1503 }
1504
1505
1506 RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat, bool &bucketCreated)
1507 {
1508         return m_bucketmanager->FindBucket(polymat, bucketCreated);
1509 }
1510
1511
1512
1513 void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
1514                                                          class RAS_IRasterizer* rasty,
1515                                                          class RAS_IRenderTools* rendertools)
1516 {
1517         m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
1518         KX_BlenderMaterial::EndFrame();
1519 }
1520
1521 void KX_Scene::UpdateObjectActivity(void) 
1522 {
1523         if (m_activity_culling) {
1524                 /* determine the activity criterium and set objects accordingly */
1525                 int i=0;
1526                 
1527                 MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
1528                 
1529                 for (i=0;i<GetObjectList()->GetCount();i++)
1530                 {
1531                         KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
1532                         
1533                         if (!ob->GetIgnoreActivityCulling()) {
1534                                 /* Simple test: more than 10 away from the camera, count
1535                                  * Manhattan distance. */
1536                                 MT_Point3 obpos = ob->NodeGetWorldPosition();
1537                                 
1538                                 if ( (fabs(camloc[0] - obpos[0]) > m_activity_box_radius)
1539                                          || (fabs(camloc[1] - obpos[1]) > m_activity_box_radius)
1540                                          || (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
1541                                 {                       
1542                                         ob->Suspend();
1543                                 } else {
1544                                         ob->Resume();
1545                                 }
1546                         }
1547                 }               
1548         }
1549 }
1550
1551 void KX_Scene::SetActivityCullingRadius(float f)
1552 {
1553         if (f < 0.5)
1554                 f = 0.5;
1555         m_activity_box_radius = f;
1556 }
1557         
1558 NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
1559 {
1560         return m_networkDeviceInterface;
1561 }
1562
1563 NG_NetworkScene* KX_Scene::GetNetworkScene()
1564 {
1565         return m_networkScene;
1566 }
1567
1568 void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
1569 {
1570         m_networkDeviceInterface = newInterface;
1571 }
1572
1573 void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
1574 {
1575         m_networkScene = newScene;
1576 }
1577
1578
1579 void    KX_Scene::SetGravity(const MT_Vector3& gravity)
1580 {
1581         GetPhysicsEnvironment()->setGravity(gravity[0],gravity[1],gravity[2]);
1582 }
1583
1584 void KX_Scene::SetSceneConverter(class KX_BlenderSceneConverter* sceneConverter)
1585 {
1586         m_sceneConverter = sceneConverter;
1587 }
1588
1589 void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
1590 {
1591         m_physicsEnvironment = physEnv;
1592
1593         KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, physEnv);
1594         m_logicmgr->RegisterEventManager(touchmgr);
1595         return;
1596 }
1597  
1598 void KX_Scene::setSuspendedTime(double suspendedtime)
1599 {
1600         m_suspendedtime = suspendedtime;
1601 }
1602 double KX_Scene::getSuspendedTime()
1603 {
1604         return m_suspendedtime;
1605 }
1606 void KX_Scene::setSuspendedDelta(double suspendeddelta)
1607 {
1608         m_suspendeddelta = suspendeddelta;
1609 }
1610 double KX_Scene::getSuspendedDelta()
1611 {
1612         return m_suspendeddelta;
1613 }
1614
1615 //----------------------------------------------------------------------------
1616 //Python
1617
1618 PyTypeObject KX_Scene::Type = {
1619 #if (PY_VERSION_HEX >= 0x02060000)
1620         PyVarObject_HEAD_INIT(NULL, 0)
1621 #else
1622         /* python 2.5 and below */
1623         PyObject_HEAD_INIT( NULL )  /* required py macro */
1624         0,                          /* ob_size */
1625 #endif
1626                 "KX_Scene",
1627                 sizeof(PyObjectPlus_Proxy),
1628                 0,
1629                 py_base_dealloc,
1630                 0,
1631                 0,
1632                 0,
1633                 0,
1634                 py_base_repr,
1635                 0,0,0,0,0,0,
1636                 py_base_getattro,
1637                 py_base_setattro,
1638                 0,0,0,0,0,0,0,0,0,
1639                 Methods
1640 };
1641
1642 PyParentObject KX_Scene::Parents[] = {
1643         &KX_Scene::Type,
1644                 &CValue::Type,
1645                 NULL
1646 };
1647
1648 PyMethodDef KX_Scene::Methods[] = {
1649         KX_PYMETHODTABLE_NOARGS(KX_Scene, getLightList),
1650         KX_PYMETHODTABLE_NOARGS(KX_Scene, getObjectList),
1651         KX_PYMETHODTABLE_NOARGS(KX_Scene, getName),
1652         KX_PYMETHODTABLE(KX_Scene, addObject),
1653         
1654         {NULL,NULL} //Sentinel
1655 };
1656
1657 PyObject* KX_Scene::pyattr_get_name(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1658 {
1659         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1660         return PyString_FromString(self->GetName().ReadPtr());
1661 }
1662
1663 PyObject* KX_Scene::pyattr_get_objects(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1664 {
1665         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1666         return self->GetObjectList()->GetProxy();
1667 }
1668
1669 PyObject* KX_Scene::pyattr_get_objects_inactive(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1670 {
1671         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1672         return self->GetInactiveList()->GetProxy();
1673 }
1674
1675 PyObject* KX_Scene::pyattr_get_lights(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1676 {
1677         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1678         return self->GetLightList()->GetProxy();
1679 }
1680
1681 PyObject* KX_Scene::pyattr_get_cameras(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1682 {
1683         /* With refcounts in this case...
1684          * the new CListValue is owned by python, so its possible python holds onto it longer then the BGE
1685          * however this is the same with "scene.objects + []", when you make a copy by adding lists.
1686          */
1687         
1688         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1689         CListValue* clist = new CListValue();
1690         
1691         /* return self->GetCameras()->GetProxy(); */
1692         
1693         list<KX_Camera*>::iterator it = self->GetCameras()->begin();
1694         while (it != self->GetCameras()->end()) {
1695                 clist->Add((*it)->AddRef());
1696                 it++;
1697         }
1698         
1699         return clist->NewProxy(true);
1700 }
1701
1702 PyObject* KX_Scene::pyattr_get_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
1703 {
1704         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1705         return self->GetActiveCamera()->GetProxy();
1706 }
1707
1708
1709 int KX_Scene::pyattr_set_active_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
1710 {
1711         KX_Scene* self= static_cast<KX_Scene*>(self_v);
1712         KX_Camera *camOb;
1713         
1714         if (!ConvertPythonToCamera(value, &camOb, false, "scene.active_camera = value: KX_Scene"))
1715                 return PY_SET_ATTR_FAIL;
1716         
1717         self->SetActiveCamera(camOb);
1718         return PY_SET_ATTR_SUCCESS;
1719 }
1720
1721
1722 PyAttributeDef KX_Scene::Attributes[] = {
1723         KX_PYATTRIBUTE_RO_FUNCTION("name",                              KX_Scene, pyattr_get_name),
1724         KX_PYATTRIBUTE_RO_FUNCTION("objects",                   KX_Scene, pyattr_get_objects),
1725         KX_PYATTRIBUTE_RO_FUNCTION("objectsInactive",   KX_Scene, pyattr_get_objects_inactive), KX_PYATTRIBUTE_RO_FUNCTION("lights",                    KX_Scene, pyattr_get_lights),
1726         KX_PYATTRIBUTE_RO_FUNCTION("cameras",                   KX_Scene, pyattr_get_cameras),
1727         KX_PYATTRIBUTE_RO_FUNCTION("lights",                    KX_Scene, pyattr_get_lights),
1728         KX_PYATTRIBUTE_RW_FUNCTION("active_camera",             KX_Scene, pyattr_get_active_camera, pyattr_set_active_camera),
1729         KX_PYATTRIBUTE_BOOL_RO("suspended",                             KX_Scene, m_suspend),
1730         KX_PYATTRIBUTE_BOOL_RO("activity_culling",              KX_Scene, m_activity_culling),
1731         KX_PYATTRIBUTE_FLOAT_RW("activity_culling_radius", 0.5f, FLT_MAX, KX_Scene, m_activity_box_radius),
1732         KX_PYATTRIBUTE_BOOL_RO("dbvt_culling",                  KX_Scene, m_dbvt_culling),
1733         { NULL }        //Sentinel
1734 };
1735
1736 PyObject* KX_Scene::py_getattro__internal(PyObject *attr)
1737 {       
1738         py_getattro_up(PyObjectPlus);
1739 }
1740
1741 int KX_Scene::py_setattro__internal(PyObject *attr, PyObject *value)
1742 {
1743         py_setattro_up(PyObjectPlus);
1744 }
1745
1746 PyObject* KX_Scene::py_getattro(PyObject *attr)
1747 {
1748         PyObject *object = py_getattro__internal(attr);
1749         
1750         if (object==NULL)
1751         {
1752                 PyErr_Clear();
1753                 object = PyDict_GetItem(m_attr_dict, attr);
1754                 if(object) {
1755                         Py_INCREF(object);
1756                 }
1757                 else {
1758                         PyErr_Format(PyExc_AttributeError, "value = scene.myAttr: KX_Scene, attribute \"%s\" not found", PyString_AsString(attr));
1759                 }
1760         }
1761         
1762         return object;
1763 }
1764
1765 PyObject* KX_Scene::py_getattro_dict() {
1766         //py_getattro_dict_up(PyObjectPlus);
1767         
1768         PyObject *dict= py_getattr_dict(PyObjectPlus::py_getattro_dict(), Type.tp_dict);
1769         if(dict==NULL)
1770                 return NULL;
1771         
1772         /* normally just return this but KX_Scene has some more items */
1773         
1774         PyDict_Update(dict, m_attr_dict);
1775         return dict;
1776 }
1777
1778 int KX_Scene::py_setattro(PyObject *attr, PyObject *value)
1779 {
1780         int ret= py_setattro__internal(attr, value);
1781         
1782         if (ret==PY_SET_ATTR_MISSING) {
1783                 if (PyDict_SetItem(m_attr_dict, attr, value)==0) {
1784                         PyErr_Clear();
1785                         ret= PY_SET_ATTR_SUCCESS;
1786                 }
1787                 else {
1788                         PyErr_SetString(PyExc_AttributeError, "scene.UserAttr = value: KX_Scenes, failed assigning value to internal dictionary");
1789                         ret= PY_SET_ATTR_FAIL;
1790                 }
1791         }
1792         
1793         return ret;
1794 }
1795
1796 int KX_Scene::py_delattro(PyObject *attr)
1797 {
1798         PyDict_DelItem(m_attr_dict, attr);
1799         return 0;
1800 }
1801
1802 KX_PYMETHODDEF_DOC_NOARGS(KX_Scene, getLightList,
1803 "getLightList() -> list [KX_Light]\n"
1804 "Returns a list of all lights in the scene.\n"
1805 )
1806 {
1807         ShowDeprecationWarning("getLightList()", "the lights property");
1808         return m_lightlist->GetProxy();
1809 }
1810
1811 KX_PYMETHODDEF_DOC_NOARGS(KX_Scene, getObjectList,
1812 "getObjectList() -> list [KX_GameObject]\n"
1813 "Returns a list of all game objects in the scene.\n"
1814 )
1815 {
1816         ShowDeprecationWarning("getObjectList()", "the objects property");
1817         return m_objectlist->GetProxy();
1818 }
1819
1820 KX_PYMETHODDEF_DOC_NOARGS(KX_Scene, getName,
1821 "getName() -> string\n"
1822 "Returns the name of the scene.\n"
1823 )
1824 {
1825         ShowDeprecationWarning("getName()", "the name property");
1826         return PyString_FromString(GetName());
1827 }
1828
1829 KX_PYMETHODDEF_DOC(KX_Scene, addObject,
1830 "addObject(object, other, time=0)\n"
1831 "Returns the added object.\n")
1832 {
1833         PyObject *pyob, *pyother;
1834         KX_GameObject *ob, *other;
1835
1836         int time = 0;
1837
1838         if (!PyArg_ParseTuple(args, "OO|i:addObject", &pyob, &pyother, &time))
1839                 return NULL;
1840
1841         if (    !ConvertPythonToGameObject(pyob, &ob, false, "scene.addObject(object, other, time): KX_Scene (first argument)") ||
1842                         !ConvertPythonToGameObject(pyother, &other, false, "scene.addObject(object, other, time): KX_Scene (second argument)") )
1843                 return NULL;
1844
1845
1846         SCA_IObject* replica = AddReplicaObject((SCA_IObject*)ob, other, time);
1847         
1848         // release here because AddReplicaObject AddRef's
1849         // the object is added to the scene so we dont want python to own a reference
1850         replica->Release();
1851         return replica->GetProxy();
1852 }