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