Fix for bugs: 1788 (forces) and 1799 (python delattr on game objects)
[blender-staging.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         if (replica->GetPhysicsController())
605         {
606                 replica->GetPhysicsController()->setPosition(newpos);
607                 replica->GetPhysicsController()->setOrientation(newori.getRotation());
608         }
609
610         // here we want to set the relative scale: the rootnode's scale will override all other
611         // scalings, so lets better prepare for it
612
613         // get the rootnode's scale
614         MT_Vector3 newscale = parentobj->GetSGNode()->GetRootSGParent()->GetLocalScale();
615
616         // set the replica's relative scale with the rootnode's scale
617         replica->NodeSetRelativeScale(newscale);
618
619         replica->GetSGNode()->UpdateWorldData(0);
620         replica->GetSGNode()->SetBBox(originalobj->GetSGNode()->BBox());
621         replica->GetSGNode()->SetRadius(originalobj->GetSGNode()->Radius());
622         
623         return replica;
624 }
625
626
627
628 void KX_Scene::RemoveObject(class CValue* gameobj)
629 {
630         KX_GameObject* newobj = (KX_GameObject*) gameobj;
631
632         // first disconnect child from parent
633         SG_Node* node = newobj->GetSGNode();
634
635         if (node)
636         {
637                 node->DisconnectFromParent();
638
639                 // recursively destruct
640                 node->Destruct();
641         }
642 }
643
644
645
646 void KX_Scene::DelayedRemoveObject(class CValue* gameobj)
647 {
648         //KX_GameObject* newobj = (KX_GameObject*) gameobj;
649         if (!m_euthanasyobjects->SearchValue(gameobj))
650         {
651                 m_euthanasyobjects->Add(gameobj->AddRef());
652         } 
653 }
654
655
656
657 void KX_Scene::NewRemoveObject(class CValue* gameobj)
658 {
659         KX_GameObject* newobj = (KX_GameObject*) gameobj;
660         //SM_Object* sumoObj = newobj->GetSumoObject();
661         //if (sumoObj)
662         //{
663         //      this->GetSumoScene()->remove(*sumoObj);
664         //}
665         // remove all sensors/controllers/actuators from logicsystem...
666         
667         SCA_SensorList& sensors = newobj->GetSensors();
668         for (SCA_SensorList::iterator its = sensors.begin();
669                  !(its==sensors.end());its++)
670         {
671                 m_logicmgr->RemoveSensor(*its);
672         }
673         
674     SCA_ControllerList& controllers = newobj->GetControllers();
675         for (SCA_ControllerList::iterator itc = controllers.begin();
676                  !(itc==controllers.end());itc++)
677         {
678                 (*itc)->UnlinkAllSensors();
679                 (*itc)->UnlinkAllActuators();
680         }
681
682         SCA_ActuatorList& actuators = newobj->GetActuators();
683         for (SCA_ActuatorList::iterator ita = actuators.begin();
684                  !(ita==actuators.end());ita++)
685         {
686                 m_logicmgr->RemoveDestroyedActuator(*ita);
687         }
688
689         // now remove the timer properties from the time manager
690         int numprops = newobj->GetPropertyCount();
691
692         for (int i = 0; i < numprops; i++)
693         {
694                 CValue* propval = newobj->GetProperty(i);
695                 if (propval->GetProperty("timer"))
696                 {
697                         m_timemgr->RemoveTimeProperty(propval);
698                 }
699         }
700         
701         newobj->RemoveMeshes();
702         if (m_objectlist->RemoveValue(newobj))
703                 newobj->Release();
704         if (m_tempObjectList->RemoveValue(newobj))
705                 newobj->Release();
706         if (m_parentlist->RemoveValue(newobj))
707                 newobj->Release();
708         if (m_euthanasyobjects->RemoveValue(newobj))
709                 newobj->Release();
710                 
711         if (newobj == m_active_camera)
712         {
713                 m_active_camera = NULL;
714         }
715 }
716
717
718
719 void KX_Scene::ReplaceMesh(class CValue* gameobj,void* meshobj)
720 {
721         KX_GameObject* newobj = (KX_GameObject*) gameobj;
722         newobj->RemoveMeshes();
723         newobj->AddMesh((RAS_MeshObject*)meshobj);
724         newobj->Bucketize();
725 }
726
727
728
729 MT_CmMatrix4x4& KX_Scene::GetViewMatrix()
730 {
731         MT_Scalar cammat[16];
732         m_active_camera->GetWorldToCamera().getValue(cammat);
733         m_viewmat = cammat;
734         return m_viewmat;
735 }
736
737
738
739 MT_CmMatrix4x4& KX_Scene::GetProjectionMatrix()
740 {
741         return m_projectionmat;
742 }
743
744
745 KX_Camera* KX_Scene::FindCamera(KX_Camera* cam)
746 {
747         set<KX_Camera*>::iterator it = m_cameras.begin();
748
749         while ( (it != m_cameras.end()) 
750                         && ((*it) != cam) ) {
751           it++;
752         }
753
754         return ((it == m_cameras.end()) ? NULL : (*it));
755 }
756
757
758 KX_Camera* KX_Scene::FindCamera(STR_String& name)
759 {
760         set<KX_Camera*>::iterator it = m_cameras.begin();
761
762         while ( (it != m_cameras.end()) 
763                         && ((*it)->GetName() != name) ) {
764           it++;
765         }
766
767         return ((it == m_cameras.end()) ? NULL : (*it));
768 }
769
770 void KX_Scene::AddCamera(KX_Camera* cam)
771 {
772         m_cameras.insert(cam);
773 }
774
775 KX_Camera* KX_Scene::GetActiveCamera()
776 {       
777         // NULL if not defined
778         return m_active_camera;
779 }
780
781
782 void KX_Scene::SetActiveCamera(KX_Camera* cam)
783 {
784         // only set if the cam is in the active list? Or add it otherwise?
785         if (!FindCamera(cam)){
786                 AddCamera(cam);
787                 if (cam) std::cout << "Added cam " << cam->GetName() << std::endl;
788         } 
789
790         m_active_camera = cam;
791 }
792
793
794
795 void KX_Scene::UpdateMeshTransformations()
796 {
797         // do this incrementally in the future
798         for (int i = 0; i < m_objectlist->GetCount(); i++)
799         {
800                 KX_GameObject* gameobj = (KX_GameObject*)m_objectlist->GetValue(i);
801                 gameobj->GetOpenGLMatrix();
802 //              gameobj->UpdateNonDynas();
803         }
804 }
805
806 void KX_Scene::MarkVisible(SG_Tree *node, RAS_IRasterizer* rasty)
807 {
808         int intersect = KX_Camera::INTERSECT;
809         KX_GameObject *gameobj = node->Client()?(KX_GameObject*) node->Client()->GetSGClientObject():NULL;
810         bool dotest = (gameobj && gameobj->GetVisible()) || node->Left() || node->Right();
811         
812         /* If the camera is inside the box, assume intersect. */
813         if (dotest && !node->inside(GetActiveCamera()->NodeGetWorldPosition()))
814         {
815                 MT_Scalar radius = node->Radius();
816                 MT_Point3 centre = node->Centre();
817                 
818                 intersect = GetActiveCamera()->SphereInsideFrustum(centre, radius); 
819                 
820                 if (intersect == KX_Camera::INTERSECT)
821                 {
822                         MT_Point3 box[8];
823                         node->get(box);
824                         intersect = GetActiveCamera()->BoxInsideFrustum(box);
825                 }
826         }
827
828         switch (intersect)
829         {
830                 case KX_Camera::OUTSIDE:
831                         MarkSubTreeVisible(node, rasty, false);
832                         break;
833                 case KX_Camera::INTERSECT:
834                         if (gameobj)
835                                 MarkVisible(rasty, gameobj);
836                         if (node->Left())
837                                 MarkVisible(node->Left(), rasty);
838                         if (node->Right())
839                                 MarkVisible(node->Right(), rasty);
840                         break;
841                 case KX_Camera::INSIDE:
842                         MarkSubTreeVisible(node, rasty, true);
843                         break;
844         }
845 }
846
847 void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool visible)
848 {
849         if (node->Client())
850         {
851                 KX_GameObject *gameobj = (KX_GameObject*) node->Client()->GetSGClientObject();
852                 if (gameobj->GetVisible())
853                 {
854                         if (visible)
855                         {
856                                 int nummeshes = gameobj->GetMeshCount();
857                                 MT_Transform t( GetActiveCamera()->GetWorldToCamera() * gameobj->GetSGNode()->GetWorldTransform());
858         
859                                 
860                                 for (int m=0;m<nummeshes;m++)
861                                 {
862                                         // this adds the vertices to the display list
863                                         (gameobj->GetMesh(m))->SchedulePolygons(t, rasty->GetDrawingMode());
864                                 }
865                         }
866                         gameobj->MarkVisible(visible);
867                 }
868         }
869         if (node->Left())
870                 MarkSubTreeVisible(node->Left(), rasty, visible);
871         if (node->Right())
872                 MarkSubTreeVisible(node->Right(), rasty, visible);
873 }
874
875 void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj)
876 {
877         // User (Python/Actuator) has forced object invisible...
878         if (!gameobj->GetVisible())
879                 return;
880         // If Frustum culling is off, the object is always visible.
881         bool vis = !GetActiveCamera()->GetFrustumCulling();
882         
883         // If the camera is inside this node, then the object is visible.
884         if (!vis)
885         {
886                 vis = gameobj->GetSGNode()->inside( GetActiveCamera()->GetCameraLocation() );
887         }
888                 
889         // Test the object's bound sphere against the view frustum.
890         if (!vis)
891         {
892                 MT_Vector3 scale = gameobj->GetSGNode()->GetWorldScaling();
893                 MT_Scalar radius = fabs(scale[scale.closestAxis()] * gameobj->GetSGNode()->Radius());
894                 switch (GetActiveCamera()->SphereInsideFrustum(gameobj->NodeGetWorldPosition(), radius))
895                 {
896                         case KX_Camera::INSIDE:
897                                 vis = true;
898                                 break;
899                         case KX_Camera::OUTSIDE:
900                                 vis = false;
901                                 break;
902                         case KX_Camera::INTERSECT:
903                                 // Test the object's bound box against the view frustum.
904                                 MT_Point3 box[8];
905                                 gameobj->GetSGNode()->getBBox(box); 
906                                 vis = GetActiveCamera()->BoxInsideFrustum(box) != KX_Camera::OUTSIDE;
907                                 break;
908                 }
909         }
910         
911         if (vis)
912         {
913                 int nummeshes = gameobj->GetMeshCount();
914                 MT_Transform t(GetActiveCamera()->GetWorldToCamera() * gameobj->GetSGNode()->GetWorldTransform());
915                 
916                 for (int m=0;m<nummeshes;m++)
917                 {
918                         // this adds the vertices to the display list
919                         (gameobj->GetMesh(m))->SchedulePolygons(t, rasty->GetDrawingMode());
920                 }
921                 // Visibility/ non-visibility are marked
922                 // elsewhere now.
923                 gameobj->MarkVisible();
924         } else {
925                 gameobj->MarkVisible(false);
926         }
927 }
928
929 void KX_Scene::CalculateVisibleMeshes(RAS_IRasterizer* rasty)
930 {
931 // FIXME: When tree is operational
932 #if 1
933         // do this incrementally in the future
934         for (int i = 0; i < m_objectlist->GetCount(); i++)
935         {
936                 MarkVisible(rasty, static_cast<KX_GameObject*>(m_objectlist->GetValue(i)));
937         }
938 #else
939         if (GetActiveCamera()->GetFrustumCulling())
940                 MarkVisible(m_objecttree, rasty);
941         else
942                 MarkSubTreeVisible(m_objecttree, rasty, true);
943 #endif
944 }
945
946 // logic stuff
947 void KX_Scene::LogicBeginFrame(double curtime)
948 {
949         // have a look at temp objects ...
950         int lastobj = m_tempObjectList->GetCount() - 1;
951         
952         for (int i = lastobj; i >= 0; i--)
953         {
954                 CValue* objval = m_tempObjectList->GetValue(i);
955                 CFloatValue* propval = (CFloatValue*) objval->GetProperty("::timebomb");
956                 
957                 if (propval)
958                 {
959                         float timeleft = propval->GetNumber() - 1.0/KX_KetsjiEngine::GetTicRate();
960                         
961                         if (timeleft > 0)
962                         {
963                                 propval->SetFloat(timeleft);
964                         }
965                         else
966                         {
967                                 DelayedRemoveObject(objval);
968                                 // remove obj
969                         }
970                 }
971                 else
972                 {
973                         // all object is the tempObjectList should have a clock
974                 }
975         }
976         m_logicmgr->BeginFrame(curtime, 1.0/KX_KetsjiEngine::GetTicRate());
977 }
978
979
980
981 void KX_Scene::LogicUpdateFrame(double curtime, bool frame)
982 {
983         m_logicmgr->UpdateFrame(curtime, frame);
984 }
985
986
987
988 void KX_Scene::LogicEndFrame()
989 {
990         m_logicmgr->EndFrame();
991         int numobj = m_euthanasyobjects->GetCount();
992
993         for (int i = numobj - 1; i >= 0; i--)
994         {
995                 KX_GameObject* gameobj = (KX_GameObject*)m_euthanasyobjects->GetValue(i);
996                 this->RemoveObject(gameobj);
997         }
998         
999         numobj = m_euthanasyobjects->GetCount();
1000         if (numobj != 0)
1001         {
1002                 // huh?
1003                 int ii=0;
1004         }
1005         // numobj is 0 we hope
1006 }
1007
1008
1009
1010 /**
1011   * UpdateParents: SceneGraph transformation update.
1012   */
1013 void KX_Scene::UpdateParents(double curtime)
1014 {
1015 //      int numrootobjects = GetRootParentList()->GetCount();
1016
1017         for (int i=0; i<GetRootParentList()->GetCount(); i++)
1018         {
1019                 KX_GameObject* parentobj = (KX_GameObject*)GetRootParentList()->GetValue(i);
1020                 parentobj->NodeUpdateGS(curtime,true);
1021         }
1022 }
1023
1024
1025
1026 RAS_MaterialBucket* KX_Scene::FindBucket(class RAS_IPolyMaterial* polymat)
1027 {
1028         return m_bucketmanager->RAS_BucketManagerFindBucket(polymat);
1029 }
1030
1031
1032
1033 void KX_Scene::RenderBuckets(const MT_Transform & cameratransform,
1034                                                          class RAS_IRasterizer* rasty,
1035                                                          class RAS_IRenderTools* rendertools)
1036 {
1037         m_bucketmanager->Renderbuckets(cameratransform,rasty,rendertools);
1038 }
1039
1040
1041
1042 void KX_Scene::UpdateObjectActivity(void) 
1043 {
1044         if (m_activity_culling) {
1045                 /* determine the activity criterium and set objects accordingly */
1046                 int i=0;
1047                 
1048                 MT_Point3 camloc = GetActiveCamera()->NodeGetWorldPosition(); //GetCameraLocation();
1049                 
1050                 for (i=0;i<GetObjectList()->GetCount();i++)
1051                 {
1052                         KX_GameObject* ob = (KX_GameObject*) GetObjectList()->GetValue(i);
1053                         
1054                         if (!ob->GetIgnoreActivityCulling()) {
1055                                 /* Simple test: more than 10 away from the camera, count
1056                                  * Manhattan distance. */
1057                                 MT_Point3 obpos = ob->NodeGetWorldPosition();
1058                                 
1059                                 if ( (fabs(camloc[0] - obpos[0]) > m_activity_box_radius)
1060                                          || (fabs(camloc[1] - obpos[1]) > m_activity_box_radius)
1061                                          || (fabs(camloc[2] - obpos[2]) > m_activity_box_radius) )
1062                                 {                       
1063                                         ob->Suspend();
1064                                 } else {
1065                                         ob->Resume();
1066                                 }
1067                         }
1068                 }               
1069         }
1070 }
1071
1072 void KX_Scene::SetActivityCullingRadius(float f)
1073 {
1074         if (f < 0.5)
1075                 f = 0.5;
1076         m_activity_box_radius = f;
1077 }
1078         
1079 NG_NetworkDeviceInterface* KX_Scene::GetNetworkDeviceInterface()
1080 {
1081         return m_networkDeviceInterface;
1082 }
1083
1084 NG_NetworkScene* KX_Scene::GetNetworkScene()
1085 {
1086         return m_networkScene;
1087 }
1088
1089 void KX_Scene::SetNetworkDeviceInterface(NG_NetworkDeviceInterface* newInterface)
1090 {
1091         m_networkDeviceInterface = newInterface;
1092 }
1093
1094 void KX_Scene::SetNetworkScene(NG_NetworkScene *newScene)
1095 {
1096         m_networkScene = newScene;
1097 }
1098
1099
1100 void    KX_Scene::SetGravity(const MT_Vector3& gravity)
1101 {
1102         GetPhysicsEnvironment()->setGravity(gravity[0],gravity[1],gravity[2]);
1103 }
1104
1105 void KX_Scene::SetNodeTree(SG_Tree* root)
1106 {
1107         m_objecttree = root;
1108 }
1109
1110 void KX_Scene::SetPhysicsEnvironment(class PHY_IPhysicsEnvironment* physEnv)
1111 {
1112         SumoPhysicsEnvironment *sme = dynamic_cast<SumoPhysicsEnvironment *>(physEnv);
1113         m_physicsEnvironment = physEnv;
1114         if (sme)
1115         {
1116                 KX_TouchEventManager* touchmgr = new KX_TouchEventManager(m_logicmgr, sme->GetSumoScene());
1117                 m_logicmgr->RegisterEventManager(touchmgr);
1118                 return;
1119         }
1120 }
1121
1122 //----------------------------------------------------------------------------
1123 //Python
1124
1125 PyMethodDef KX_Scene::Methods[] = {
1126         KX_PYMETHODTABLE(KX_Scene, getLightList),
1127         KX_PYMETHODTABLE(KX_Scene, getObjectList),
1128         KX_PYMETHODTABLE(KX_Scene, getName),
1129         
1130         {NULL,NULL} //Sentinel
1131 };
1132
1133 PyTypeObject KX_Scene::Type = {
1134         PyObject_HEAD_INIT(&PyType_Type)
1135                 0,
1136                 "KX_Scene",
1137                 sizeof(KX_Scene),
1138                 0,
1139                 PyDestructor,
1140                 0,
1141                 __getattr,
1142                 __setattr,
1143                 0, //&MyPyCompare,
1144                 __repr,
1145                 0, //&cvalue_as_number,
1146                 0,
1147                 0,
1148                 0,
1149                 0, 0, 0, 0, 0, 0
1150 };
1151
1152 PyParentObject KX_Scene::Parents[] = {
1153         &KX_Scene::Type,
1154                 &CValue::Type,
1155                 NULL
1156 };
1157
1158 PyObject* KX_Scene::_getattr(const STR_String& attr)
1159 {
1160         if (attr == "name")
1161                 return PyString_FromString(GetName());
1162         
1163         if (attr == "active_camera")
1164         {
1165                 KX_Camera *camera = GetActiveCamera();
1166                 camera->AddRef();
1167                 return (PyObject*) camera;
1168         }
1169         
1170         if (attr == "suspended")
1171                 return PyInt_FromLong(m_suspend);
1172         
1173         if (attr == "activity_culling")
1174                 return PyInt_FromLong(m_activity_culling);
1175         
1176         if (attr == "activity_culling_radius")
1177                 return PyFloat_FromDouble(m_activity_box_radius);
1178         
1179         PyObject* value = PyDict_GetItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()));
1180         if (value)
1181         {
1182                 Py_INCREF(value);
1183                 return value;
1184         }
1185         
1186         _getattr_up(PyObjectPlus);
1187 }
1188
1189 int KX_Scene::_delattr(const STR_String &attr)
1190 {
1191         PyDict_DelItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()));
1192         return 0;
1193 }
1194
1195 int KX_Scene::_setattr(const STR_String &attr, PyObject *pyvalue)
1196 {
1197
1198         if (!PyDict_SetItemString(m_attrlist, const_cast<char *>(attr.ReadPtr()), pyvalue))
1199                 return 0;
1200
1201         return PyObjectPlus::_setattr(attr, pyvalue);
1202 }
1203
1204 KX_PYMETHODDEF_DOC(KX_Scene, getLightList,
1205 "getLightList() -> list [KX_Light]\n"
1206 "Returns a list of all lights in the scene.\n"
1207 )
1208 {
1209         m_lightlist->AddRef();
1210         return (PyObject*) m_lightlist;
1211 }
1212
1213 KX_PYMETHODDEF_DOC(KX_Scene, getObjectList,
1214 "getObjectList() -> list [KX_GameObject]\n"
1215 "Returns a list of all game objects in the scene.\n"
1216 )
1217 {
1218         m_objectlist->AddRef();
1219         return (PyObject*) m_objectlist;
1220 }
1221
1222 KX_PYMETHODDEF_DOC(KX_Scene, getName,
1223 "getName() -> string\n"
1224 "Returns the name of the scene.\n"
1225 )
1226 {
1227         return PyString_FromString(GetName());
1228 }