More warning cleanups...
[blender.git] / source / gameengine / Ketsji / KX_Scene.cpp
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  * Ketsji scene. Holds references to all scene data.
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #include <config.h>
36 #endif
37
38 #ifdef WIN32
39 #pragma warning (disable : 4786)
40 #endif //WIN32
41
42 #include "KX_KetsjiEngine.h"
43 #include "RAS_IPolygonMaterial.h"
44 #include "KX_Scene.h"
45 #include "ListValue.h"
46 #include "SCA_LogicManager.h"
47 #include "SCA_TimeEventManager.h"
48 #include "SCA_AlwaysEventManager.h"
49 #include "SCA_RandomEventManager.h"
50 #include "KX_RayEventManager.h"
51 #include "KX_TouchEventManager.h"
52 #include "SCA_KeyboardManager.h"
53 #include "SCA_MouseManager.h"
54 #include "SCA_PropertyEventManager.h"
55 #include "KX_Camera.h"
56
57 #include "RAS_MeshObject.h"
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
70 #include "KX_SG_NodeRelationships.h"
71
72 #include "KX_NetworkEventManager.h"
73 #include "NG_NetworkScene.h"
74 #include "PHY_IPhysicsEnvironment.h"
75 #include "KX_IPhysicsController.h"
76
77 #include "SM_Scene.h"
78 #include "SumoPhysicsEnvironment.h"
79
80 void* KX_SceneReplicationFunc(SG_IObject* node,void* gameobj,void* scene)
81 {
82         KX_GameObject* replica = ((KX_Scene*)scene)->AddNodeReplicaObject(node,(KX_GameObject*)gameobj);
83
84         return (void*)replica;
85 }
86
87 void* KX_SceneDestructionFunc(SG_IObject* node,void* gameobj,void* scene)
88 {
89         ((KX_Scene*)scene)->RemoveNodeDestructObject(node,(KX_GameObject*)gameobj);
90
91         return NULL;
92 };
93
94 SG_Callbacks KX_Scene::m_callbacks = SG_Callbacks(KX_SceneReplicationFunc,KX_SceneDestructionFunc,KX_GameObject::UpdateTransformFunc);
95
96 // temporarily var until there is a button in the userinterface
97 // (defined in KX_PythonInit.cpp)
98 extern bool gUseVisibilityTemp;
99
100 KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice,
101                                    class SCA_IInputDevice* mousedevice,
102                                    class NG_NetworkDeviceInterface *ndi,
103                                    class SND_IAudioDevice* adi,
104                                    const STR_String& sceneName): 
105         PyObjectPlus(&KX_Scene::Type),
106         m_keyboardmgr(NULL),
107         m_mousemgr(NULL),
108         m_physicsEnvironment(0),
109         m_sceneName(sceneName),
110         m_adi(adi),
111         m_networkDeviceInterface(ndi),
112         m_active_camera(NULL),
113         m_ueberExecutionPriority(0)
114 {
115                 
116
117         m_activity_culling = false;
118         m_suspend = false;
119         m_isclearingZbuffer = true;
120         m_tempObjectList = new CListValue();
121         m_objectlist = new CListValue();
122         m_parentlist = new CListValue();
123         m_lightlist= new CListValue();
124         m_euthanasyobjects = new CListValue();
125
126         m_logicmgr = new SCA_LogicManager();
127         
128         m_timemgr = new SCA_TimeEventManager(m_logicmgr);
129         m_keyboardmgr = new SCA_KeyboardManager(m_logicmgr,keyboarddevice);
130         m_mousemgr = new SCA_MouseManager(m_logicmgr,mousedevice);
131         
132         SCA_AlwaysEventManager* alwaysmgr = new SCA_AlwaysEventManager(m_logicmgr);
133         SCA_PropertyEventManager* propmgr = new SCA_PropertyEventManager(m_logicmgr);
134         SCA_RandomEventManager* rndmgr = new SCA_RandomEventManager(m_logicmgr);
135         KX_RayEventManager* raymgr = new KX_RayEventManager(m_logicmgr);
136
137         KX_NetworkEventManager* netmgr = new KX_NetworkEventManager(m_logicmgr, ndi);
138
139         m_logicmgr->RegisterEventManager(alwaysmgr);
140         m_logicmgr->RegisterEventManager(propmgr);
141         m_logicmgr->RegisterEventManager(m_keyboardmgr);
142         m_logicmgr->RegisterEventManager(m_mousemgr);
143         m_logicmgr->RegisterEventManager(m_timemgr);
144         m_logicmgr->RegisterEventManager(rndmgr);
145         m_logicmgr->RegisterEventManager(raymgr);
146         m_logicmgr->RegisterEventManager(netmgr);
147
148         m_soundScene = new SND_Scene(adi);
149         assert (m_networkDeviceInterface != NULL);
150         m_networkScene = new NG_NetworkScene(m_networkDeviceInterface);
151         
152         m_rootnode = NULL;
153
154         m_bucketmanager=new RAS_BucketManager();
155
156         m_canvasDesignWidth = 0;
157         m_canvasDesignHeight = 0;
158         
159         m_attrlist = PyDict_New(); /* new ref */
160 }
161
162
163
164 KX_Scene::~KX_Scene()
165 {
166         
167 //      int numobj = m_objectlist->GetCount();
168
169         //int numrootobjects = GetRootParentList()->GetCount();
170         for (int i = 0; i < GetRootParentList()->GetCount(); i++)
171         {
172                 KX_GameObject* parentobj = (KX_GameObject*) GetRootParentList()->GetValue(i);
173                 this->RemoveObject(parentobj);
174         }
175
176         if(m_objectlist)
177                 m_objectlist->Release();
178         
179         if (m_parentlist)
180                 m_parentlist->Release();
181         
182         if (m_lightlist)
183                 m_lightlist->Release();
184         
185         if (m_tempObjectList)
186                 m_tempObjectList->Release();
187
188         if (m_euthanasyobjects)
189                 m_euthanasyobjects->Release();
190         
191         if (m_logicmgr)
192                 delete m_logicmgr;
193
194         if (m_physicsEnvironment)
195                 delete m_physicsEnvironment;
196
197         if (m_soundScene)
198                 delete m_soundScene;
199
200         if (m_networkScene)
201                 delete m_networkScene;
202         
203         if (m_bucketmanager)
204         {
205                 delete m_bucketmanager;
206         }
207         
208         Py_DECREF(m_attrlist);
209 }
210
211
212
213
214 void KX_Scene::SetProjectionMatrix(MT_CmMatrix4x4& pmat)
215 {
216         m_projectionmat = pmat;
217 }
218
219
220
221 RAS_BucketManager* KX_Scene::GetBucketManager()
222 {
223         return m_bucketmanager;
224 }
225
226
227
228 CListValue* KX_Scene::GetObjectList()
229 {
230         return m_objectlist;
231 }
232
233
234
235 CListValue* KX_Scene::GetRootParentList()
236 {
237         return m_parentlist;
238 }
239
240
241
242 CListValue* KX_Scene::GetLightList()
243 {
244         return m_lightlist;
245 }
246
247 SCA_LogicManager* KX_Scene::GetLogicManager()
248 {
249         return m_logicmgr;
250 }
251
252 SCA_TimeEventManager* KX_Scene::GetTimeEventManager()
253 {
254         return m_timemgr;
255 }
256
257
258
259
260 void KX_Scene::SetFramingType(RAS_FrameSettings & frame_settings)
261 {
262         m_frame_settings = frame_settings;
263 };
264
265 /**
266  * Return a const reference to the framing 
267  * type set by the above call.
268  * The contents are not guarenteed to be sensible
269  * if you don't call the above function.
270  */
271 const RAS_FrameSettings& KX_Scene::GetFramingType() const 
272 {
273         return m_frame_settings;
274 };      
275
276
277
278 /**
279  * Store the current scene's viewport on the 
280  * game engine canvas.
281  */
282 void KX_Scene::SetSceneViewport(const RAS_Rect &viewport)
283 {
284         m_viewport = viewport;
285 }
286
287
288
289 const RAS_Rect& KX_Scene::GetSceneViewport() const 
290 {
291         return m_viewport;
292 }
293
294
295
296 void KX_Scene::SetWorldInfo(class KX_WorldInfo* worldinfo)
297 {
298         m_worldinfo = worldinfo;
299 }
300
301
302
303 class KX_WorldInfo* KX_Scene::GetWorldInfo()
304 {
305         return m_worldinfo;
306 }
307
308
309
310 SND_Scene* KX_Scene::GetSoundScene()
311 {
312         return m_soundScene;
313 }
314
315 const STR_String& KX_Scene::GetName()
316 {
317         return m_sceneName;
318 }
319
320
321 void KX_Scene::Suspend()
322 {
323         m_suspend = true;
324 }
325
326 void KX_Scene::Resume()
327 {
328         m_suspend = false;
329 }
330
331 void KX_Scene::SetActivityCulling(bool b)
332 {
333         m_activity_culling = b;
334 }
335
336 bool KX_Scene::IsSuspended()
337 {
338         return m_suspend;
339 }
340
341 bool KX_Scene::IsClearingZBuffer()
342 {
343         return m_isclearingZbuffer;
344 }
345
346 void KX_Scene::EnableZBufferClearing(bool isclearingZbuffer)
347 {
348         m_isclearingZbuffer = isclearingZbuffer;
349 }
350
351 void KX_Scene::RemoveNodeDestructObject(class SG_IObject* node,class CValue* gameobj)
352 {
353         KX_GameObject* orgobj = (KX_GameObject*)gameobj;        
354         NewRemoveObject(orgobj);
355
356         if (node)
357                 delete node;
358 }
359
360 KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CValue* gameobj)
361 {
362         KX_GameObject* orgobj = (KX_GameObject*)gameobj;
363         KX_GameObject* newobj = (KX_GameObject*)orgobj->GetReplica();
364         m_map_gameobject_to_replica.insert(orgobj, newobj);
365
366         // also register 'timers' (time properties) of the replica
367         int numprops = newobj->GetPropertyCount();
368
369         for (int i = 0; i < numprops; i++)
370         {
371                 CValue* prop = newobj->GetProperty(i);
372
373                 if (prop->GetProperty("timer"))
374                         this->m_timemgr->AddTimeProperty(prop);
375         }
376
377         if (node)
378         {
379                 newobj->SetSGNode((SG_Node*)node);
380         }
381         else
382         {
383                 m_rootnode = new SG_Node(newobj,this,KX_Scene::m_callbacks);
384         
385                 // this fixes part of the scaling-added object bug
386                 SG_Node* orgnode = orgobj->GetSGNode();
387                 m_rootnode->SetLocalScale(orgnode->GetLocalScale());
388                 m_rootnode->SetLocalPosition(orgnode->GetLocalPosition());
389                 m_rootnode->SetLocalOrientation(orgnode->GetLocalOrientation());
390
391                 // define the relationship between this node and it's parent.
392                 KX_NormalParentRelation * parent_relation = 
393                         KX_NormalParentRelation::New();
394                 m_rootnode->SetParentRelation(parent_relation);
395
396                 newobj->SetSGNode(m_rootnode);
397         }
398         
399         SG_IObject* replicanode = newobj->GetSGNode();
400         SG_Node* rootnode = (replicanode == m_rootnode ? NULL : m_rootnode);
401
402         replicanode->SetSGClientObject(newobj);
403
404         // this is the list of object that are send to the graphics pipeline
405         m_objectlist->Add(newobj);
406         newobj->Bucketize();
407
408         // logic cannot be replicated, until the whole hierarchy is replicated.
409         m_logicHierarchicalGameObjects.push_back(newobj);
410         //replicate controllers of this node
411         SGControllerList        scenegraphcontrollers = orgobj->GetSGNode()->GetSGControllerList();
412         replicanode->RemoveAllControllers();
413         SGControllerList::iterator cit;
414         //int numcont = scenegraphcontrollers.size();
415         
416         for (cit = scenegraphcontrollers.begin();!(cit==scenegraphcontrollers.end());++cit)
417         {
418                 // controller replication is quite complicated
419                 // only replicate ipo and physics controller for now
420
421                 SG_Controller* replicacontroller = (*cit)->GetReplica((SG_Node*) replicanode);
422                 if (replicacontroller)
423                 {
424                         replicacontroller->SetObject(replicanode);
425                         replicanode->AddSGController(replicacontroller);
426                 }
427         }
428         
429         return newobj;
430 }
431
432
433
434 // before calling this method KX_Scene::ReplicateLogic(), make sure to
435 // have called 'GameObject::ReParentLogic' for each object this
436 // hierarchy that's because first ALL bricks must exist in the new
437 // replica of the hierarchy in order to make cross-links work properly
438 // !
439 void KX_Scene::ReplicateLogic(KX_GameObject* newobj)
440 {
441         // also relink the controller to sensors/actuators
442         SCA_ControllerList& controllers = newobj->GetControllers();
443         //SCA_SensorList&     sensors     = newobj->GetSensors();
444         //SCA_ActuatorList&   actuators   = newobj->GetActuators();
445
446         for (SCA_ControllerList::iterator itc = controllers.begin(); !(itc==controllers.end());itc++)
447         {
448                 SCA_IController* cont = (*itc);
449                 cont->SetUeberExecutePriority(m_ueberExecutionPriority);
450                 vector<SCA_ISensor*> linkedsensors = cont->GetLinkedSensors();
451                 vector<SCA_IActuator*> linkedactuators = cont->GetLinkedActuators();
452
453                 // disconnect the sensors and actuators
454                 cont->UnlinkAllSensors();
455                 cont->UnlinkAllActuators();
456                 
457                 // now relink each sensor
458                 for (vector<SCA_ISensor*>::iterator its = linkedsensors.begin();!(its==linkedsensors.end());its++)
459                 {
460                         SCA_ISensor* oldsensor = (*its);
461                         STR_String name = oldsensor->GetName();
462                         //find this name in the list
463                         SCA_ISensor* newsensor = newobj->FindSensor(name);
464                 
465                         if (newsensor)
466                         {
467                                 // relink this newsensor to the controller
468                                 m_logicmgr->RegisterToSensor(cont,newsensor);
469                         }
470                         else
471                         {
472                                 // it can be linked somewhere in the hierarchy or...
473                                 for (vector<KX_GameObject*>::iterator git = m_logicHierarchicalGameObjects.begin();
474                                 !(git==m_logicHierarchicalGameObjects.end());++git)
475                                 {
476                                         newsensor = (*git)->FindSensor(name);
477                                         if (newsensor)
478                                                 break;
479                                 } 
480
481                                 if (newsensor)
482                                 {
483                                         // relink this newsensor to the controller somewhere else within this
484                                         // hierarchy
485                                         m_logicmgr->RegisterToSensor(cont,newsensor);
486                                 }
487                                 else
488                                 {
489                                         // must be an external sensor, so...
490                                         m_logicmgr->RegisterToSensor(cont,oldsensor);
491                                 }
492                         }
493                 }
494                 
495                 // now relink each actuator
496                 for (vector<SCA_IActuator*>::iterator ita = linkedactuators.begin();!(ita==linkedactuators.end());ita++)
497                 {
498                         SCA_IActuator* oldactuator = (*ita);
499                         STR_String name = oldactuator->GetName();
500                         //find this name in the list
501                         SCA_IActuator* newactuator = newobj->FindActuator(name);
502                         if (newactuator)
503                         {
504                                 // relink this newsensor to the controller
505                                 m_logicmgr->RegisterToActuator(cont,newactuator);
506                                 newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
507                         }
508                         else
509                         {
510                                 // it can be linked somewhere in the hierarchy or...
511                                 for (vector<KX_GameObject*>::iterator git = m_logicHierarchicalGameObjects.begin();
512                                 !(git==m_logicHierarchicalGameObjects.end());++git)
513                                 {
514                                         newactuator= (*git)->FindActuator(name);
515                                         if (newactuator)
516                                                 break;
517                                 } 
518
519                                 if (newactuator)
520                                 {
521                                         // relink this actuator to the controller somewhere else within this
522                                         // hierarchy
523                                         m_logicmgr->RegisterToActuator(cont,newactuator);
524                                         newactuator->SetUeberExecutePriority(m_ueberExecutionPriority);
525                                 }
526                                 else
527                                 {
528                                         // must be an external actuator, so...
529                                         m_logicmgr->RegisterToActuator(cont,oldactuator);
530                                 }
531                         }
532                 }
533         }
534 }
535
536
537
538 SCA_IObject* KX_Scene::AddReplicaObject(class CValue* originalobject,
539                                                                                 class CValue* parentobject,
540                                                                                 int lifespan)
541 {
542
543         m_logicHierarchicalGameObjects.clear();
544         m_map_gameobject_to_replica.clear();
545
546         // todo: place a timebomb in the object, for temporarily objects :)
547         // lifespan of zero means 'this object lives forever'
548         KX_GameObject* originalobj = (KX_GameObject*) originalobject;
549         KX_GameObject* parentobj = (KX_GameObject*) parentobject;
550
551         m_ueberExecutionPriority++;
552
553         // lets create a replica
554         KX_GameObject* replica = (KX_GameObject*) AddNodeReplicaObject(NULL,originalobj);
555
556         if (lifespan > 0)
557         {
558                 // add a timebomb to this object
559                 // for now, convert between so called frames and realtime
560                 m_tempObjectList->Add(replica->AddRef());
561                 replica->SetProperty("::timebomb",new CFloatValue(lifespan*0.02));
562         }
563
564         // add to 'rootparent' list (this is the list of top hierarchy objects, updated each frame)
565         m_parentlist->Add(replica->AddRef());
566
567         // recurse replication into children nodes
568
569         NodeList& children = originalobj->GetSGNode()->GetSGChildren();
570
571         replica->GetSGNode()->ClearSGChildren();
572         for (NodeList::iterator childit = children.begin();!(childit==children.end());++childit)
573         {
574                 SG_Node* orgnode = (*childit);
575                 SG_Node* childreplicanode = orgnode->GetSGReplica();
576                 replica->GetSGNode()->AddChild(childreplicanode);
577         }
578
579         //      relink any pointers as necessary, sort of a temporary solution
580         vector<KX_GameObject*>::iterator git;
581         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
582         {
583                 (*git)->Relink(&m_map_gameobject_to_replica);
584         }
585
586         // now replicate logic
587         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
588         {
589                 (*git)->ReParentLogic();
590         }
591         
592         // replicate crosslinks etc. between logic bricks
593         for (git = m_logicHierarchicalGameObjects.begin();!(git==m_logicHierarchicalGameObjects.end());++git)
594         {
595                 ReplicateLogic((*git));
596         }
597         
598         MT_Point3 newpos = ((KX_GameObject*) parentobject)->NodeGetWorldPosition();
599         replica->NodeSetLocalPosition(newpos);
600
601         MT_Matrix3x3 newori = ((KX_GameObject*) parentobject)->NodeGetWorldOrientation();
602         replica->NodeSetLocalOrientation(newori);
603         
604         // get the rootnode's scale
605         MT_Vector3 newscale = parentobj->GetSGNode()->GetRootSGParent()->GetLocalScale();
606
607         // set the replica's relative scale with the rootnode's scale
608         replica->NodeSetRelativeScale(newscale);
609
610         if (replica->GetPhysicsController())
611         {
612                 replica->GetPhysicsController()->setPosition(newpos);
613                 replica->GetPhysicsController()->setOrientation(newori.getRotation());
614                 replica->GetPhysicsController()->setScaling(newscale);
615         }
616
617         // here we want to set the relative scale: the rootnode's scale will override all other
618         // scalings, so lets better prepare for it
619
620
621         replica->GetSGNode()->UpdateWorldData(0);
622         replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
623         replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
624         
625         return replica;
626 }
627
628
629
630 void KX_Scene::RemoveObject(class CValue* gameobj)
631 {
632         KX_GameObject* newobj = (KX_GameObject*) gameobj;
633
634         // first disconnect child from parent
635         SG_Node* node = newobj->GetSGNode();
636
637         if (node)
638         {
639                 node->DisconnectFromParent();
640
641                 // recursively destruct
642                 node->Destruct();
643         }
644 }
645
646
647
648 void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
649 {
650         //KX_GameObject* newobj = (KX_GameObject*) gameobj;
651         if (!m_euthanasyobjects->SearchValue(gameobj))
652         {
653                 m_euthanasyobjects->Add(gameobj->AddRef());
654         } 
655 }
656
657
658
659 void KX_Scene::NewRemoveObject(class CValue* gameobj)
660 {
661         KX_GameObject* newobj = (KX_GameObject*) gameobj;
662         //SM_Object* sumoObj = newobj->GetSumoObject();
663         //if (sumoObj)
664         //{
665         //      this->GetSumoScene()->remove(*sumoObj);
666         //}
667         // remove all sensors/controllers/actuators from logicsystem...
668         
669         SCA_SensorList& sensors = newobj->GetSensors();
670         for (SCA_SensorList::iterator its = sensors.begin();
671                  !(its==sensors.end());its++)
672         {
673                 m_logicmgr->RemoveSensor(*its);
674         }
675         
676     SCA_ControllerList& controllers = newobj->GetControllers();
677         for (SCA_ControllerList::iterator itc = controllers.begin();
678                  !(itc==controllers.end());itc++)
679         {
680                 (*itc)->UnlinkAllSensors();
681                 (*itc)->UnlinkAllActuators();
682         }
683
684         SCA_ActuatorList& actuators = newobj->GetActuators();
685         for (SCA_ActuatorList::iterator ita = actuators.begin();
686                  !(ita==actuators.end());ita++)
687         {
688                 m_logicmgr->RemoveDestroyedActuator(*ita);
689         }
690
691         // now remove the timer properties from the time manager
692         int numprops = newobj->GetPropertyCount();
693
694         for (int i = 0; i < numprops; i++)
695         {
696                 CValue* propval = newobj->GetProperty(i);
697                 if (propval->GetProperty("timer"))
698                 {
699                         m_timemgr->RemoveTimeProperty(propval);
700                 }
701         }
702         
703         newobj->RemoveMeshes();
704         if (m_objectlist->RemoveValue(newobj))
705                 newobj->Release();
706         if (m_tempObjectList->RemoveValue(newobj))
707                 newobj->Release();
708         if (m_parentlist->RemoveValue(newobj))
709                 newobj->Release();
710         if (m_euthanasyobjects->RemoveValue(newobj))
711                 newobj->Release();
712                 
713         if (newobj == m_active_camera)
714         {
715                 m_active_camera = NULL;
716         }
717 }
718
719
720
721 void KX_Scene::ReplaceMesh(class CValue* gameobj,void* meshobj)
722 {
723         KX_GameObject* newobj = (KX_GameObject*) gameobj;
724         newobj->RemoveMeshes();
725         newobj->AddMesh((RAS_MeshObject*)meshobj);
726         newobj->Bucketize();
727 }
728
729
730
731 MT_CmMatrix4x4& KX_Scene::GetViewMatrix()
732 {
733         MT_Scalar cammat[16];
734         m_active_camera->GetWorldToCamera().getValue(cammat);
735         m_viewmat = cammat;
736         return m_viewmat;
737 }
738
739
740
741 MT_CmMatrix4x4& KX_Scene::GetProjectionMatrix()
742 {
743         return m_projectionmat;
744 }
745
746
747 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
748 {
749         set<KX_Camera*>::iterator it = m_cameras.begin();
750
751         while ( (it != m_cameras.end()) 
752                         && ((*it) != cam) ) {
753           it++;
754         }
755
756         return ((it == m_cameras.end()) ? NULL : (*it));
757 }
758
759
760 KX_Camera* KX_Scene::FindCamera(STR_String& name)
761 {
762         set<KX_Camera*>::iterator it = m_cameras.begin();
763
764         while ( (it != m_cameras.end()) 
765                         && ((*it)->GetName() != name) ) {
766           it++;
767         }
768
769         return ((it == m_cameras.end()) ? NULL : (*it));
770 }
771
772 void KX_Scene::AddCamera(KX_Camera* cam)
773 {
774         m_cameras.insert(cam);
775 }
776
777 KX_Camera* KX_Scene::GetActiveCamera()
778 {       
779         // NULL if not defined
780         return m_active_camera;
781 }
782
783
784 void KX_Scene::SetActiveCamera(KX_Camera* cam)
785 {
786         // only set if the cam is in the active list? Or add it otherwise?
787         if (!FindCamera(cam)){
788                 AddCamera(cam);
789                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
790         } 
791
792         m_active_camera = cam;
793 }
794
795
796
797 void KX_Scene::UpdateMeshTransformations()
798 {
799         // do this incrementally in the future
800         for (int i = 0; i < m_objectlist->GetCount(); i++)
801         {
802                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
803                 gameobj->GetOpenGLMatrix();
804 //              gameobj->UpdateNonDynas();
805         }
806 }
807
808 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty)
809 {
810         int intersect = KX_Camera::INTERSECT;
811         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
812         bool dotest = (gameobj && gameobj->GetVisible()) || node->Left() || node->Right();
813         
814         /* If the camera is inside the box, assume intersect. */
815         if (dotest && !node->inside(GetActiveCamera()->NodeGetWorldPosition()))
816         {
817                 MT_Scalar radius = node->Radius();
818                 MT_Point3 centre = node->Centre();
819                 
820                 intersect = GetActiveCamera()->SphereInsideFrustum(centre, radius); 
821                 
822                 if (intersect == KX_Camera::INTERSECT)
823                 {
824                         MT_Point3 box[8];
825                         node->get(box);
826                         intersect = GetActiveCamera()->BoxInsideFrustum(box);
827                 }
828         }
829
830         switch (intersect)
831         {
832                 case KX_Camera::OUTSIDE:
833                         MarkSubTreeVisible(node, rasty, false);
834                         break;
835                 case KX_Camera::INTERSECT:
836                         if (gameobj)
837                                 MarkVisible(rasty, gameobj);
838                         if (node->Left())
839                                 MarkVisible(node->Left(), rasty);
840                         if (node->Right())
841                                 MarkVisible(node->Right(), rasty);
842                         break;
843                 case KX_Camera::INSIDE:
844                         MarkSubTreeVisible(node, rasty, true);
845                         break;
846         }
847 }
848
849 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible)
850 {
851         if (node->Client())
852         {
853                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
854                 if (gameobj->GetVisible())
855                 {
856                         if (visible)
857                         {
858                                 int nummeshes = gameobj->GetMeshCount();
859                                 MT_Transform t( GetActiveCamera()->GetWorldToCamera() * gameobj->GetSGNode()->GetWorldTransform());
860         
861                                 
862                                 for (int m=0;m<nummeshes;m++)
863                                 {
864                                         // this adds the vertices to the display list
865                                         (gameobj->GetMesh(m))->SchedulePolygons(t, rasty->GetDrawingMode());
866                                 }
867                         }
868                         gameobj->MarkVisible(visible);
869                 }
870         }
871         if (node->Left())
872                 MarkSubTreeVisible(node->Left(), rasty, visible);
873         if (node->Right())
874                 MarkSubTreeVisible(node->Right(), rasty, visible);
875 }
876
877 void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj)
878 {
879         // User (Python/Actuator) has forced object invisible...
880         if (!gameobj->GetVisible())
881                 return;
882         // If Frustum culling is off, the object is always visible.
883         bool vis = !GetActiveCamera()->GetFrustumCulling();
884         
885         // If the camera is inside this node, then the object is visible.
886         if (!vis)
887         {
888                 vis = gameobj->GetSGNode()->inside( GetActiveCamera()->GetCameraLocation() );
889         }
890                 
891         // Test the object's bound sphere against the view frustum.
892         if (!vis)
893         {
894                 MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
895                 MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
896                 switch (GetActiveCamera()->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
897                 {
898                         case KX_Camera::INSIDE:
899                                 vis = true;
900                                 break;
901                         case KX_Camera::OUTSIDE:
902                                 vis = false;
903                                 break;
904                         case KX_Camera::INTERSECT:
905                                 // Test the object's bound box against the view frustum.
906                                 MT_Point3 box[8];
907                                 gameobj->GetSGNode()->getBBox(box); 
908                                 vis = GetActiveCamera()->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
909                                 break;
910                 }
911         }
912         
913         if (vis)
914         {
915                 int nummeshes = gameobj->GetMeshCount();
916                 MT_Transform t(GetActiveCamera()->GetWorldToCamera() * gameobj->GetSGNode()->GetWorldTransform());
917                 
918                 for (int m=0;m<nummeshes;m++)
919                 {
920                         // this adds the vertices to the display list
921                         (gameobj->GetMesh(m))->SchedulePolygons(t, rasty->GetDrawingMode());
922                 }
923                 // Visibility/ non-visibility are marked
924                 // elsewhere now.
925                 gameobj->MarkVisible();
926         } else {
927                 gameobj->MarkVisible(false);
928         }
929 }
930
931 void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty)
932 {
933 // FIXME: When tree is operational
934 #if 1
935         // do this incrementally in the future
936         for (int i = 0; i < m_objectlist->GetCount(); i++)
937         {
938                 MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)));
939         }
940 #else
941         if (GetActiveCamera()->GetFrustumCulling())
942                 MarkVisible(m_objecttree, rasty);
943         else
944                 MarkSubTreeVisible(m_objecttree, rasty, true);
945 #endif
946 }
947
948 // logic stuff
949 void KX_Scene::LogicBeginFrame(double curtime)
950 {
951         // have a look at temp objects ...
952         int lastobj = m_tempObjectList->GetCount() - 1;
953         
954         for (int i = lastobj; i >= 0; i--)
955         {
956                 CValue* objval = m_tempObjectList->GetValue(i);
957                 CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
958                 
959                 if (propval)
960                 {
961                         float timeleft = propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate();
962                         
963                         if (timeleft > 0)
964                         {
965                                 propval->SetFloat(timeleft);
966                         }
967                         else
968                         {
969                                 DelayedRemoveObject(objval);
970                                 // remove obj
971                         }
972                 }
973                 else
974                 {
975                         // all object is the tempObjectList should have a clock
976                 }
977         }
978         m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate());
979 }
980
981
982
983 void KX_Scene::LogicUpdateFrame(double curtime, bool frame)
984 {
985         m_logicmgr->UpdateFrame(curtime, frame);
986 }
987
988
989
990 void KX_Scene::LogicEndFrame()
991 {
992         m_logicmgr->EndFrame();
993         int numobj = m_euthanasyobjects->GetCount();
994
995         for (int i = numobj - 1; i >= 0; i--)
996         {
997                 KX_GameObject* gameobj = (KX_GameObject*)m_euthanasyobjects->GetValue(i);
998                 this->RemoveObject(gameobj);
999         }
1000 }
1001
1002
1003
1004 /**
1005   * UpdateParents: SceneGraph transformation update.
1006   */
1007 void KX_Scene::UpdateParents(double curtime)
1008 {
1009 //      int numrootobjects = GetRootParentList()->GetCount();
1010
1011         for (int i=0; i<GetRootParentList()->GetCount(); i++)
1012         {
1013                 KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
1014                 parentobj->NodeUpdateGS(curtime,true);
1015         }
1016 }
1017
1018
1019
1020 RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat)
1021 {
1022         return m_bucketmanager->RAS_BucketManagerFindBucket(polymat);
1023 }
1024
1025
1026
1027 void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
1028                                                          class RAS_IRasterizer* rasty,
1029                                                          class RAS_IRenderTools* rendertools)
1030 {
1031         m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
1032 }
1033
1034
1035
1036 void KX_Scene::UpdateObjectActivity(void) 
1037 {
1038         if (m_activity_culling) {
1039                 /* determine the activity criterium and set objects accordingly */
1040                 int i=0;
1041                 
1042                 MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
1043                 
1044                 for (i=0;i<GetObjectList()->GetCount();i++)
1045                 {
1046                         KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
1047                         
1048                         if (!ob->GetIgnoreActivityCulling()) {
1049                                 /* Simple test: more than 10 away from the camera, count
1050                                  * Manhattan distance. */
1051                                 MT_Point3 obpos = ob->NodeGetWorldPosition();
1052                                 
1053                                 if ( (fabs(camloc[0] - obpos[0]) > m_activity_box_radius)
1054                                          || (fabs(camloc[1] - obpos[1]) > m_activity_box_radius)
1055                                          || (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
1056                                 {                       
1057                                         ob->Suspend();
1058                                 } else {
1059                                         ob->Resume();
1060                                 }
1061                         }
1062                 }               
1063         }
1064 }
1065
1066 void KX_Scene::SetActivityCullingRadius(float f)
1067 {
1068         if (f < 0.5)
1069                 f = 0.5;
1070         m_activity_box_radius = f;
1071 }
1072         
1073 NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
1074 {
1075         return m_networkDeviceInterface;
1076 }
1077
1078 NG_NetworkScene* KX_Scene::GetNetworkScene()
1079 {
1080         return m_networkScene;
1081 }
1082
1083 void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
1084 {
1085         m_networkDeviceInterface = newInterface;
1086 }
1087
1088 void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
1089 {
1090         m_networkScene = newScene;
1091 }
1092
1093
1094 void    KX_Scene::SetGravity(const MT_Vector3& gravity)
1095 {
1096         GetPhysicsEnvironment()->setGravity(gravity[0],gravity[1],gravity[2]);
1097 }
1098
1099 void KX_Scene::SetNodeTree(SG_Tree* root)
1100 {
1101         m_objecttree = root;
1102 }
1103
1104 void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
1105 {
1106         SumoPhysicsEnvironment *sme = dynamic_cast<SumoPhysicsEnvironment *>(physEnv);
1107         m_physicsEnvironment = physEnv;
1108         if (sme)
1109         {
1110                 KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, sme->GetSumoScene());
1111                 m_logicmgr->RegisterEventManager(touchmgr);
1112                 return;
1113         }
1114 }
1115
1116 //----------------------------------------------------------------------------
1117 //Python
1118
1119 PyMethodDef KX_Scene::Methods[] = {
1120         KX_PYMETHODTABLE(KX_Scene, getLightList),
1121         KX_PYMETHODTABLE(KX_Scene, getObjectList),
1122         KX_PYMETHODTABLE(KX_Scene, getName),
1123         
1124         {NULL,NULL} //Sentinel
1125 };
1126
1127 PyTypeObject KX_Scene::Type = {
1128         PyObject_HEAD_INIT(&PyType_Type)
1129                 0,
1130                 "KX_Scene",
1131                 sizeof(KX_Scene),
1132                 0,
1133                 PyDestructor,
1134                 0,
1135                 __getattr,
1136                 __setattr,
1137                 0, //&MyPyCompare,
1138                 __repr,
1139                 0, //&cvalue_as_number,
1140                 0,
1141                 0,
1142                 0,
1143                 0, 0, 0, 0, 0, 0
1144 };
1145
1146 PyParentObject KX_Scene::Parents[] = {
1147         &KX_Scene::Type,
1148                 &CValue::Type,
1149                 NULL
1150 };
1151
1152 PyObject* KX_Scene::_getattr(const STR_String& attr)
1153 {
1154         if (attr == "name")
1155                 return PyString_FromString(GetName());
1156         
1157         if (attr == "active_camera")
1158         {
1159                 KX_Camera *camera = GetActiveCamera();
1160                 camera->AddRef();
1161                 return (PyObject*) camera;
1162         }
1163         
1164         if (attr == "suspended")
1165                 return PyInt_FromLong(m_suspend);
1166         
1167         if (attr == "activity_culling")
1168                 return PyInt_FromLong(m_activity_culling);
1169         
1170         if (attr == "activity_culling_radius")
1171                 return PyFloat_FromDouble(m_activity_box_radius);
1172         
1173         PyObject* value = PyDict_GetItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()));
1174         if (value)
1175         {
1176                 Py_INCREF(value);
1177                 return value;
1178         }
1179         
1180         _getattr_up(PyObjectPlus);
1181 }
1182
1183 int KX_Scene::_delattr(const STR_String &attr)
1184 {
1185         PyDict_DelItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()));
1186         return 0;
1187 }
1188
1189 int KX_Scene::_setattr(const STR_String &attr, PyObject *pyvalue)
1190 {
1191
1192         if (!PyDict_SetItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()), pyvalue))
1193                 return 0;
1194
1195         return PyObjectPlus::_setattr(attr, pyvalue);
1196 }
1197
1198 KX_PYMETHODDEF_DOC(KX_Scene, getLightList,
1199 "getLightList() -> list [KX_Light]\n"
1200 "Returns a list of all lights in the scene.\n"
1201 )
1202 {
1203         m_lightlist->AddRef();
1204         return (PyObject*) m_lightlist;
1205 }
1206
1207 KX_PYMETHODDEF_DOC(KX_Scene, getObjectList,
1208 "getObjectList() -> list [KX_GameObject]\n"
1209 "Returns a list of all game objects in the scene.\n"
1210 )
1211 {
1212         m_objectlist->AddRef();
1213         return (PyObject*) m_objectlist;
1214 }
1215
1216 KX_PYMETHODDEF_DOC(KX_Scene, getName,
1217 "getName() -> string\n"
1218 "Returns the name of the scene.\n"
1219 )
1220 {
1221         return PyString_FromString(GetName());
1222 }