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