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