code cleanup:
[blender.git] / source / gameengine / Converter / KX_BlenderSceneConverter.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file gameengine/Converter/KX_BlenderSceneConverter.cpp
29  *  \ingroup bgeconv
30  */
31
32
33 #if defined(WIN32) && !defined(FREE_WINDOWS)
34 #pragma warning (disable:4786) // suppress stl-MSVC debug info warning
35 #endif
36
37 #include "KX_Scene.h"
38 #include "KX_GameObject.h"
39 #include "KX_BlenderSceneConverter.h"
40 #include "KX_IpoConvert.h"
41 #include "RAS_MeshObject.h"
42 #include "KX_PhysicsEngineEnums.h"
43 #include "PHY_IPhysicsEnvironment.h"
44 #include "KX_KetsjiEngine.h"
45 #include "KX_IPhysicsController.h"
46 #include "BL_Material.h"
47 #include "BL_ActionActuator.h"
48 #include "KX_BlenderMaterial.h"
49 #include "KX_PolygonMaterial.h"
50
51
52 #include "BL_System.h"
53
54 #include "DummyPhysicsEnvironment.h"
55
56 #include "KX_ConvertPhysicsObject.h"
57
58 #ifdef USE_BULLET
59 #include "CcdPhysicsEnvironment.h"
60 #endif
61
62 #include "KX_BlenderSceneConverter.h"
63 #include "KX_BlenderScalarInterpolator.h"
64 #include "BL_BlenderDataConversion.h"
65 #include "BlenderWorldInfo.h"
66 #include "KX_Scene.h"
67
68 /* This little block needed for linking to Blender... */
69 #ifdef WIN32
70 #include "BLI_winstuff.h"
71 #endif
72
73 /* This list includes only data type definitions */
74 #include "DNA_scene_types.h"
75 #include "DNA_world_types.h"
76 #include "BKE_main.h"
77
78 #include "BLI_math.h"
79
80 extern "C"
81 {
82 #include "DNA_object_types.h"
83 #include "DNA_curve_types.h"
84 #include "DNA_mesh_types.h"
85 #include "DNA_material_types.h"
86 #include "BLI_blenlib.h"
87 #include "MEM_guardedalloc.h"
88 #include "BKE_global.h"
89 #include "BKE_animsys.h"
90 #include "BKE_library.h"
91 #include "BKE_material.h" // BKE_material_copy
92 #include "BKE_mesh.h" // BKE_mesh_copy
93 #include "DNA_space_types.h"
94 #include "DNA_anim_types.h"
95 #include "RNA_define.h"
96 #include "../../blender/editors/include/ED_keyframing.h"
97 }
98
99 /* Only for dynamic loading and merging */
100 #include "RAS_BucketManager.h" // XXX cant stay
101 #include "KX_BlenderSceneConverter.h"
102 #include "BL_BlenderDataConversion.h"
103 #include "KX_MeshProxy.h"
104 #include "RAS_MeshObject.h"
105 extern "C" {
106         #include "BKE_context.h"
107         #include "BLO_readfile.h"
108         #include "BKE_idcode.h"
109         #include "BKE_report.h"
110         #include "DNA_space_types.h"
111         #include "DNA_windowmanager_types.h" /* report api */
112         #include "../../blender/blenlib/BLI_linklist.h"
113 }
114
115 KX_BlenderSceneConverter::KX_BlenderSceneConverter(
116                                                         struct Main* maggie,
117                                                         class KX_KetsjiEngine* engine
118                                                         )
119                                                         : m_maggie(maggie),
120                                                         /*m_maggie_dyn(NULL),*/
121                                                         m_ketsjiEngine(engine),
122                                                         m_alwaysUseExpandFraming(false),
123                                                         m_usemat(false),
124                                                         m_useglslmat(false)
125 {
126         tag_main(maggie, 0); /* avoid re-tagging later on */
127         m_newfilename = "";
128 }
129
130
131 KX_BlenderSceneConverter::~KX_BlenderSceneConverter()
132 {
133         // clears meshes, and hashmaps from blender to gameengine data
134         int i;
135         // delete sumoshapes
136         
137
138         int numAdtLists = m_map_blender_to_gameAdtList.size();
139         for (i=0; i<numAdtLists; i++) {
140                 BL_InterpolatorList *adtList= *m_map_blender_to_gameAdtList.at(i);
141
142                 delete (adtList);
143         }
144
145         vector<pair<KX_Scene*,KX_WorldInfo*> >::iterator itw = m_worldinfos.begin();
146         while (itw != m_worldinfos.end()) {
147                 delete (*itw).second;
148                 itw++;
149         }
150
151         vector<pair<KX_Scene*,RAS_IPolyMaterial*> >::iterator itp = m_polymaterials.begin();
152         while (itp != m_polymaterials.end()) {
153                 delete (*itp).second;
154                 itp++;
155         }
156
157         // delete after RAS_IPolyMaterial
158         vector<pair<KX_Scene*,BL_Material *> >::iterator itmat = m_materials.begin();
159         while (itmat != m_materials.end()) {
160                 delete (*itmat).second;
161                 itmat++;
162         }       
163
164
165         vector<pair<KX_Scene*,RAS_MeshObject*> >::iterator itm = m_meshobjects.begin();
166         while (itm != m_meshobjects.end()) {
167                 delete (*itm).second;
168                 itm++;
169         }
170
171 #ifdef USE_BULLET
172         KX_ClearBulletSharedShapes();
173 #endif
174
175         /* free any data that was dynamically loaded */
176         for (vector<Main*>::iterator it=m_DynamicMaggie.begin(); !(it==m_DynamicMaggie.end()); it++) {
177                 Main *main= *it;
178                 free_main(main);
179         }
180
181         m_DynamicMaggie.clear();
182 }
183
184 void KX_BlenderSceneConverter::SetNewFileName(const STR_String& filename)
185 {
186         m_newfilename = filename;
187 }
188
189
190
191 bool KX_BlenderSceneConverter::TryAndLoadNewFile()
192 {
193         bool result = false;
194
195         // find the file
196 /*      if ()
197         {
198                 result = true;
199         }
200         // if not, clear the newfilename
201         else
202         {
203                 m_newfilename = "";     
204         }
205 */
206         return result;
207 }
208
209 Scene *KX_BlenderSceneConverter::GetBlenderSceneForName(const STR_String& name)
210 {
211         Scene *sce;
212
213         /**
214          * Find the specified scene by name, or the first
215          * scene if nothing matches (shouldn't happen).
216          */
217         if ((sce= (Scene *)BLI_findstring(&m_maggie->scene, name.ReadPtr(), offsetof(ID, name) + 2)))
218                 return sce;
219
220         for (vector<Main*>::iterator it=m_DynamicMaggie.begin(); !(it==m_DynamicMaggie.end()); it++) {
221                 Main *main= *it;
222
223                 if ((sce= (Scene *)BLI_findstring(&main->scene, name.ReadPtr(), offsetof(ID, name) + 2)))
224                         return sce;
225         }
226
227         return (Scene*)m_maggie->scene.first;
228
229 }
230 #include "KX_PythonInit.h"
231
232 #ifdef USE_BULLET
233
234 #include "LinearMath/btIDebugDraw.h"
235
236
237 struct  BlenderDebugDraw : public btIDebugDraw
238 {
239         BlenderDebugDraw () :
240                 m_debugMode(0) 
241         {
242         }
243         
244         int m_debugMode;
245
246         virtual void    drawLine(const btVector3& from,const btVector3& to,const btVector3& color)
247         {
248                 if (m_debugMode >0)
249                 {
250                         MT_Vector3 kxfrom(from[0],from[1],from[2]);
251                         MT_Vector3 kxto(to[0],to[1],to[2]);
252                         MT_Vector3 kxcolor(color[0],color[1],color[2]);
253
254                         KX_RasterizerDrawDebugLine(kxfrom,kxto,kxcolor);
255                 }
256         }
257         
258         virtual void    reportErrorWarning(const char* warningString)
259         {
260
261         }
262
263         virtual void    drawContactPoint(const btVector3& PointOnB,const btVector3& normalOnB,float distance,int lifeTime,const btVector3& color)
264         {
265                 //not yet
266         }
267
268         virtual void    setDebugMode(int debugMode)
269         {
270                 m_debugMode = debugMode;
271         }
272         virtual int             getDebugMode() const
273         {
274                 return m_debugMode;
275         }
276         ///todo: find out if Blender can do this
277         virtual void    draw3dText(const btVector3& location,const char* textString)
278         {
279
280         }
281                 
282 };
283
284 #endif
285
286 void KX_BlenderSceneConverter::ConvertScene(class KX_Scene* destinationscene,
287                                                                                         class RAS_IRenderTools* rendertools,
288                                                                                         class RAS_ICanvas* canvas)
289 {
290         //find out which physics engine
291         Scene *blenderscene = destinationscene->GetBlenderScene();
292
293         e_PhysicsEngine physics_engine = UseBullet;
294         bool useDbvtCulling = false;
295         // hook for registration function during conversion.
296         m_currentScene = destinationscene;
297         destinationscene->SetSceneConverter(this);
298         SG_SetActiveStage(SG_STAGE_CONVERTER);
299
300         if (blenderscene)
301         {
302         
303                 switch (blenderscene->gm.physicsEngine)
304                 {
305                 case WOPHY_BULLET:
306                         {
307                                 physics_engine = UseBullet;
308                                 useDbvtCulling = (blenderscene->gm.mode & WO_DBVT_CULLING) != 0;
309                                 break;
310                         }
311                         default:
312                         case WOPHY_NONE:
313                         {
314                                 physics_engine = UseNone;
315                                 break;
316                         }
317                 }
318         }
319
320         switch (physics_engine)
321         {
322 #ifdef USE_BULLET
323                 case UseBullet:
324                         {
325                                 CcdPhysicsEnvironment* ccdPhysEnv = new CcdPhysicsEnvironment(useDbvtCulling);
326                                 ccdPhysEnv->setDebugDrawer(new BlenderDebugDraw());
327                                 ccdPhysEnv->setDeactivationLinearTreshold(0.8f); // default, can be overridden by Python
328                                 ccdPhysEnv->setDeactivationAngularTreshold(1.0f); // default, can be overridden by Python
329
330                                 SYS_SystemHandle syshandle = SYS_GetSystem(); /*unused*/
331                                 int visualizePhysics = SYS_GetCommandLineInt(syshandle,"show_physics",0);
332                                 if (visualizePhysics)
333                                         ccdPhysEnv->setDebugMode(btIDebugDraw::DBG_DrawWireframe|btIDebugDraw::DBG_DrawAabb|btIDebugDraw::DBG_DrawContactPoints|btIDebugDraw::DBG_DrawText|btIDebugDraw::DBG_DrawConstraintLimits|btIDebugDraw::DBG_DrawConstraints);
334                 
335                                 //todo: get a button in blender ?
336                                 //disable / enable debug drawing (contact points, aabb's etc)   
337                                 //ccdPhysEnv->setDebugMode(1);
338                                 destinationscene->SetPhysicsEnvironment(ccdPhysEnv);
339                                 break;
340                         }
341 #endif
342                 default:
343                 case UseNone:
344                         physics_engine = UseNone;
345                         destinationscene ->SetPhysicsEnvironment(new DummyPhysicsEnvironment());
346                         break;
347         }
348
349         BL_ConvertBlenderObjects(m_maggie,
350                 destinationscene,
351                 m_ketsjiEngine,
352                 physics_engine,
353                 rendertools,
354                 canvas,
355                 this,
356                 m_alwaysUseExpandFraming
357                 );
358
359         //These lookup are not needed during game
360         m_map_blender_to_gameactuator.clear();
361         m_map_blender_to_gamecontroller.clear();
362         m_map_blender_to_gameobject.clear();
363
364         //Clearing this lookup table has the effect of disabling the cache of meshes
365         //between scenes, even if they are shared in the blend file.
366         //This cache mecanism is buggy so I leave it disable and the memory leak
367         //that would result from this is fixed in RemoveScene()
368         m_map_mesh_to_gamemesh.clear();
369
370 #ifndef USE_BULLET
371         /* quiet compiler warning */
372         (void)useDbvtCulling;
373 #endif
374
375 }
376
377 // This function removes all entities stored in the converter for that scene
378 // It should be used instead of direct delete scene
379 // Note that there was some provision for sharing entities (meshes...) between
380 // scenes but that is now disabled so all scene will have their own copy
381 // and we can delete them here. If the sharing is reactivated, change this code too..
382 // (see KX_BlenderSceneConverter::ConvertScene)
383 void KX_BlenderSceneConverter::RemoveScene(KX_Scene *scene)
384 {
385         int i, size;
386         // delete the scene first as it will stop the use of entities
387         delete scene;
388         // delete the entities of this scene
389         vector<pair<KX_Scene*,KX_WorldInfo*> >::iterator worldit;
390         size = m_worldinfos.size();
391         for (i=0, worldit=m_worldinfos.begin(); i<size; ) {
392                 if ((*worldit).first == scene) {
393                         delete (*worldit).second;
394                         *worldit = m_worldinfos.back();
395                         m_worldinfos.pop_back();
396                         size--;
397                 } else {
398                         i++;
399                         worldit++;
400                 }
401         }
402
403         vector<pair<KX_Scene*,RAS_IPolyMaterial*> >::iterator polymit;
404         size = m_polymaterials.size();
405         for (i=0, polymit=m_polymaterials.begin(); i<size; ) {
406                 if ((*polymit).first == scene) {
407                         delete (*polymit).second;
408                         *polymit = m_polymaterials.back();
409                         m_polymaterials.pop_back();
410                         size--;
411                 } else {
412                         i++;
413                         polymit++;
414                 }
415         }
416
417         vector<pair<KX_Scene*,BL_Material*> >::iterator matit;
418         size = m_materials.size();
419         for (i=0, matit=m_materials.begin(); i<size; ) {
420                 if ((*matit).first == scene) {
421                         delete (*matit).second;
422                         *matit = m_materials.back();
423                         m_materials.pop_back();
424                         size--;
425                 } else {
426                         i++;
427                         matit++;
428                 }
429         }
430
431         vector<pair<KX_Scene*,RAS_MeshObject*> >::iterator meshit;
432         size = m_meshobjects.size();
433         for (i=0, meshit=m_meshobjects.begin(); i<size; ) {
434                 if ((*meshit).first == scene) {
435                         delete (*meshit).second;
436                         *meshit = m_meshobjects.back();
437                         m_meshobjects.pop_back();
438                         size--;
439                 } else {
440                         i++;
441                         meshit++;
442                 }
443         }
444 }
445
446 // use blender materials
447 void KX_BlenderSceneConverter::SetMaterials(bool val)
448 {
449         m_usemat = val;
450         m_useglslmat = false;
451 }
452
453 void KX_BlenderSceneConverter::SetGLSLMaterials(bool val)
454 {
455         m_usemat = val;
456         m_useglslmat = val;
457 }
458
459 bool KX_BlenderSceneConverter::GetMaterials()
460 {
461         return m_usemat;
462 }
463
464 bool KX_BlenderSceneConverter::GetGLSLMaterials()
465 {
466         return m_useglslmat;
467 }
468
469 void KX_BlenderSceneConverter::RegisterBlenderMaterial(BL_Material *mat)
470 {
471         m_materials.push_back(pair<KX_Scene*,BL_Material *>(m_currentScene,mat));
472 }
473
474
475
476 void KX_BlenderSceneConverter::SetAlwaysUseExpandFraming(
477         bool to_what)
478 {
479         m_alwaysUseExpandFraming= to_what;
480 }
481
482         
483
484 void KX_BlenderSceneConverter::RegisterGameObject(
485                                                                         KX_GameObject *gameobject, 
486                                                                         struct Object *for_blenderobject) 
487 {
488         /* only maintained while converting, freed during game runtime */
489         m_map_blender_to_gameobject.insert(CHashedPtr(for_blenderobject),gameobject);
490 }
491
492 /* only need to run this during conversion since
493  * m_map_blender_to_gameobject is freed after conversion */
494 void KX_BlenderSceneConverter::UnregisterGameObject(
495                                                                         KX_GameObject *gameobject) 
496 {
497         struct Object *bobp= gameobject->GetBlenderObject();
498         if (bobp) {
499                 CHashedPtr bptr(bobp);
500                 KX_GameObject **gobp= m_map_blender_to_gameobject[bptr];
501                 if (gobp && *gobp == gameobject)
502                 {
503                         // also maintain m_map_blender_to_gameobject if the gameobject
504                         // being removed is matching the blender object
505                         m_map_blender_to_gameobject.remove(bptr);
506                 }
507         }
508 }
509
510 KX_GameObject *KX_BlenderSceneConverter::FindGameObject(
511                                                                         struct Object *for_blenderobject) 
512 {
513         KX_GameObject **obp= m_map_blender_to_gameobject[CHashedPtr(for_blenderobject)];
514         
515         return obp?*obp:NULL;
516 }
517
518 void KX_BlenderSceneConverter::RegisterGameMesh(
519                                                                         RAS_MeshObject *gamemesh,
520                                                                         struct Mesh *for_blendermesh)
521 {
522         if (for_blendermesh) { /* dynamically loaded meshes we don't want to keep lookups for */
523                 m_map_mesh_to_gamemesh.insert(CHashedPtr(for_blendermesh),gamemesh);
524         }
525         m_meshobjects.push_back(pair<KX_Scene*,RAS_MeshObject*>(m_currentScene,gamemesh));
526 }
527
528
529
530 RAS_MeshObject *KX_BlenderSceneConverter::FindGameMesh(
531                                                                         struct Mesh *for_blendermesh/*,
532                                                                         unsigned int onlayer*/)
533 {
534         RAS_MeshObject** meshp = m_map_mesh_to_gamemesh[CHashedPtr(for_blendermesh)];
535         
536         if (meshp/* && onlayer==(*meshp)->GetLightLayer()*/) {
537                 return *meshp;
538         } else {
539                 return NULL;
540         }
541 }
542
543         
544
545
546         
547
548 void KX_BlenderSceneConverter::RegisterPolyMaterial(RAS_IPolyMaterial *polymat)
549 {
550         m_polymaterials.push_back(pair<KX_Scene*,RAS_IPolyMaterial*>(m_currentScene,polymat));
551 }
552
553
554
555 void KX_BlenderSceneConverter::RegisterInterpolatorList(
556                                                                         BL_InterpolatorList *actList,
557                                                                         struct bAction *for_act)
558 {
559         m_map_blender_to_gameAdtList.insert(CHashedPtr(for_act), actList);
560 }
561
562
563
564 BL_InterpolatorList *KX_BlenderSceneConverter::FindInterpolatorList(
565                                                                         struct bAction *for_act)
566 {
567         BL_InterpolatorList **listp = m_map_blender_to_gameAdtList[CHashedPtr(for_act)];
568                 
569         return listp?*listp:NULL;
570 }
571
572
573
574 void KX_BlenderSceneConverter::RegisterGameActuator(
575                                                                         SCA_IActuator *act,
576                                                                         struct bActuator *for_actuator)
577 {
578         m_map_blender_to_gameactuator.insert(CHashedPtr(for_actuator), act);
579 }
580
581
582
583 SCA_IActuator *KX_BlenderSceneConverter::FindGameActuator(
584                                                                         struct bActuator *for_actuator)
585 {
586         SCA_IActuator **actp = m_map_blender_to_gameactuator[CHashedPtr(for_actuator)];
587         
588         return actp?*actp:NULL;
589 }
590
591
592
593 void KX_BlenderSceneConverter::RegisterGameController(
594                                                                         SCA_IController *cont,
595                                                                         struct bController *for_controller)
596 {
597         m_map_blender_to_gamecontroller.insert(CHashedPtr(for_controller), cont);
598 }
599
600
601
602 SCA_IController *KX_BlenderSceneConverter::FindGameController(
603                                                                         struct bController *for_controller)
604 {
605         SCA_IController **contp = m_map_blender_to_gamecontroller[CHashedPtr(for_controller)];
606         
607         return contp?*contp:NULL;
608 }
609
610
611
612 void KX_BlenderSceneConverter::RegisterWorldInfo(
613                                                                         KX_WorldInfo *worldinfo)
614 {
615         m_worldinfos.push_back(pair<KX_Scene*,KX_WorldInfo*>(m_currentScene,worldinfo));
616 }
617
618 void    KX_BlenderSceneConverter::ResetPhysicsObjectsAnimationIpo(bool clearIpo)
619 {
620
621         KX_SceneList* scenes = m_ketsjiEngine->CurrentScenes();
622         int numScenes = scenes->size();
623         int i;
624         for (i=0;i<numScenes;i++)
625         {
626                 KX_Scene* scene = scenes->at(i);
627                 //PHY_IPhysicsEnvironment* physEnv = scene->GetPhysicsEnvironment();
628                 CListValue* parentList = scene->GetRootParentList();
629                 int numObjects = parentList->GetCount();
630                 int g;
631                 for (g=0;g<numObjects;g++)
632                 {
633                         KX_GameObject* gameObj = (KX_GameObject*)parentList->GetValue(g);
634                         if (gameObj->IsDynamic())
635                         {
636                                 //KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController();
637                                 
638                                 Object* blenderObject = gameObj->GetBlenderObject();
639                                 if (blenderObject)
640                                 {
641 #if 0
642                                         //erase existing ipo's
643                                         Ipo* ipo = blenderObject->ipo;//findIpoForName(blenderObject->id.name+2);
644                                         if (ipo)
645                                         {       //clear the curve data
646                                                 if (clearIpo) {//rcruiz
647                                                         IpoCurve *icu1;
648                                                                                                                 
649                                                         int numCurves = 0;
650                                                         for ( icu1 = (IpoCurve*)ipo->curve.first; icu1;  ) {
651                                                         
652                                                                 IpoCurve* tmpicu = icu1;
653                                                                 
654                                                                 /*int i;
655                                                                 BezTriple *bezt;
656                                                                 for ( bezt = tmpicu->bezt, i = 0;       i < tmpicu->totvert; i++, bezt++) {
657                                                                         printf("(%f,%f,%f),(%f,%f,%f),(%f,%f,%f)\n",bezt->vec[0][0],bezt->vec[0][1],bezt->vec[0][2],bezt->vec[1][0],bezt->vec[1][1],bezt->vec[1][2],bezt->vec[2][0],bezt->vec[2][1],bezt->vec[2][2]);
658                                                                 }*/
659                                                                 
660                                                                 icu1 = icu1->next;
661                                                                 numCurves++;
662                         
663                                                                 BLI_remlink( &( blenderObject->ipo->curve ), tmpicu );
664                                                                 if ( tmpicu->bezt )
665                                                                         MEM_freeN( tmpicu->bezt );
666                                                                 MEM_freeN( tmpicu );
667                                                                 localDel_ipoCurve( tmpicu );
668                                                         }
669                                                 }
670                                         } else
671                                         {       ipo = NULL; // XXX add_ipo(blenderObject->id.name+2, ID_OB);
672                                                 blenderObject->ipo = ipo;
673
674                                         }
675 #endif
676                                 }
677                         }
678
679                 }
680                 
681         
682         }
683
684
685
686 }
687
688 void    KX_BlenderSceneConverter::resetNoneDynamicObjectToIpo()
689 {
690         if (addInitFromFrame) {         
691                 KX_SceneList* scenes = m_ketsjiEngine->CurrentScenes();
692                 int numScenes = scenes->size();
693                 if (numScenes>=0) {
694                         KX_Scene* scene = scenes->at(0);
695                         CListValue* parentList = scene->GetRootParentList();
696                         for (int ix=0;ix<parentList->GetCount();ix++) {
697                                 KX_GameObject* gameobj = (KX_GameObject*)parentList->GetValue(ix);
698                                 if (!gameobj->IsDynamic()) {
699                                         Object* blenderobject = gameobj->GetBlenderObject();
700                                         if (!blenderobject)
701                                                 continue;
702                                         if (blenderobject->type==OB_ARMATURE)
703                                                 continue;
704                                         float eu[3];
705                                         mat4_to_eul(eu,blenderobject->obmat);                                   
706                                         MT_Point3 pos = MT_Point3(
707                                                 blenderobject->obmat[3][0],
708                                                 blenderobject->obmat[3][1],
709                                                 blenderobject->obmat[3][2]
710                                         );
711                                         MT_Vector3 eulxyz = MT_Vector3(
712                                                 eu[0],
713                                                 eu[1],
714                                                 eu[2]
715                                         );
716                                         MT_Vector3 scale = MT_Vector3(
717                                                 blenderobject->size[0],
718                                                 blenderobject->size[1],
719                                                 blenderobject->size[2]
720                                         );
721                                         gameobj->NodeSetLocalPosition(pos);
722                                         gameobj->NodeSetLocalOrientation(MT_Matrix3x3(eulxyz));
723                                         gameobj->NodeSetLocalScale(scale);
724                                         gameobj->NodeUpdateGS(0);
725                                 }
726                         }
727                 }
728         }
729 }
730
731
732         ///this generates ipo curves for position, rotation, allowing to use game physics in animation
733 void    KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber)
734 {
735
736         KX_SceneList* scenes = m_ketsjiEngine->CurrentScenes();
737         int numScenes = scenes->size();
738         int i;
739         for (i=0;i<numScenes;i++)
740         {
741                 KX_Scene* scene = scenes->at(i);
742                 //PHY_IPhysicsEnvironment* physEnv = scene->GetPhysicsEnvironment();
743                 CListValue* parentList = scene->GetObjectList();
744                 int numObjects = parentList->GetCount();
745                 int g;
746                 for (g=0;g<numObjects;g++)
747                 {
748                         KX_GameObject* gameObj = (KX_GameObject*)parentList->GetValue(g);
749                         Object* blenderObject = gameObj->GetBlenderObject();
750                         if (blenderObject && blenderObject->parent==NULL && gameObj->IsDynamic())
751                         {
752                                 //KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController();
753
754                                 if (blenderObject->adt==NULL)
755                                         BKE_id_add_animdata(&blenderObject->id);
756
757                                 if (blenderObject->adt)
758                                 {
759                                         const MT_Point3& position = gameObj->NodeGetWorldPosition();
760                                         //const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
761                                         const MT_Matrix3x3& orn = gameObj->NodeGetWorldOrientation();
762
763                                         position.getValue(blenderObject->loc);
764
765                                         float tmat[3][3];
766                                         for (int r=0;r<3;r++)
767                                                 for (int c=0;c<3;c++)
768                                                         tmat[r][c] = (float)orn[c][r];
769
770                                         mat3_to_compatible_eul(blenderObject->rot, blenderObject->rot, tmat);
771
772                                         insert_keyframe(NULL, &blenderObject->id, NULL, NULL, "location", -1, (float)frameNumber, INSERTKEY_FAST);
773                                         insert_keyframe(NULL, &blenderObject->id, NULL, NULL, "rotation_euler", -1, (float)frameNumber, INSERTKEY_FAST);
774
775 #if 0
776                                         const MT_Point3& position = gameObj->NodeGetWorldPosition();
777                                         //const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
778                                         const MT_Matrix3x3& orn = gameObj->NodeGetWorldOrientation();
779                                         
780                                         float eulerAngles[3];   
781                                         float eulerAnglesOld[3] = {0.0f, 0.0f, 0.0f};                                           
782                                         float tmat[3][3];
783                                         
784                                         // XXX animato
785                                         Ipo* ipo = blenderObject->ipo;
786
787                                         //create the curves, if not existing, set linear if new
788
789                                         IpoCurve *icu_lx = findIpoCurve((IpoCurve *)ipo->curve.first,"LocX");
790                                         if (!icu_lx) {
791                                                 icu_lx = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_X, 1);
792                                                 if (icu_lx) icu_lx->ipo = IPO_LIN;
793                                         }
794                                         IpoCurve *icu_ly = findIpoCurve((IpoCurve *)ipo->curve.first,"LocY");
795                                         if (!icu_ly) {
796                                                 icu_ly = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Y, 1);
797                                                 if (icu_ly) icu_ly->ipo = IPO_LIN;
798                                         }
799                                         IpoCurve *icu_lz = findIpoCurve((IpoCurve *)ipo->curve.first,"LocZ");
800                                         if (!icu_lz) {
801                                                 icu_lz = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Z, 1);
802                                                 if (icu_lz) icu_lz->ipo = IPO_LIN;
803                                         }
804                                         IpoCurve *icu_rx = findIpoCurve((IpoCurve *)ipo->curve.first,"RotX");
805                                         if (!icu_rx) {
806                                                 icu_rx = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_X, 1);
807                                                 if (icu_rx) icu_rx->ipo = IPO_LIN;
808                                         }
809                                         IpoCurve *icu_ry = findIpoCurve((IpoCurve *)ipo->curve.first,"RotY");
810                                         if (!icu_ry) {
811                                                 icu_ry = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Y, 1);
812                                                 if (icu_ry) icu_ry->ipo = IPO_LIN;
813                                         }
814                                         IpoCurve *icu_rz = findIpoCurve((IpoCurve *)ipo->curve.first,"RotZ");
815                                         if (!icu_rz) {
816                                                 icu_rz = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Z, 1);
817                                                 if (icu_rz) icu_rz->ipo = IPO_LIN;
818                                         }
819                                         
820                                         if (icu_rx) eulerAnglesOld[0]= eval_icu( icu_rx, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
821                                         if (icu_ry) eulerAnglesOld[1]= eval_icu( icu_ry, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
822                                         if (icu_rz) eulerAnglesOld[2]= eval_icu( icu_rz, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
823                                         
824                                         // orn.getValue((float *)tmat); // uses the wrong ordering, cant use this
825                                         for (int r=0;r<3;r++)
826                                                 for (int c=0;c<3;c++)
827                                                         tmat[r][c] = orn[c][r];
828                                         
829                                         // mat3_to_eul( eulerAngles,tmat); // better to use Mat3ToCompatibleEul
830                                         mat3_to_compatible_eul( eulerAngles, eulerAnglesOld,tmat);
831                                         
832                                         //eval_icu
833                                         for (int x = 0; x < 3; x++)
834                                                 eulerAngles[x] *= (float) ((180 / 3.14159265f) / 10.0);
835                                         
836                                         //fill the curves with data
837                                         if (icu_lx) insert_vert_icu(icu_lx, frameNumber, position.x(), 1);
838                                         if (icu_ly) insert_vert_icu(icu_ly, frameNumber, position.y(), 1);
839                                         if (icu_lz) insert_vert_icu(icu_lz, frameNumber, position.z(), 1);
840                                         if (icu_rx) insert_vert_icu(icu_rx, frameNumber, eulerAngles[0], 1);
841                                         if (icu_ry) insert_vert_icu(icu_ry, frameNumber, eulerAngles[1], 1);
842                                         if (icu_rz) insert_vert_icu(icu_rz, frameNumber, eulerAngles[2], 1);
843                                         
844                                         // Handles are corrected at the end, testhandles_ipocurve isn't needed yet
845 #endif
846                                 }
847                         }
848                 }
849         }
850 }
851
852
853 void    KX_BlenderSceneConverter::TestHandlesPhysicsObjectToAnimationIpo()
854 {
855
856         KX_SceneList* scenes = m_ketsjiEngine->CurrentScenes();
857         int numScenes = scenes->size();
858         int i;
859         for (i=0;i<numScenes;i++)
860         {
861                 KX_Scene* scene = scenes->at(i);
862                 //PHY_IPhysicsEnvironment* physEnv = scene->GetPhysicsEnvironment();
863                 CListValue* parentList = scene->GetRootParentList();
864                 int numObjects = parentList->GetCount();
865                 int g;
866                 for (g=0;g<numObjects;g++)
867                 {
868                         KX_GameObject* gameObj = (KX_GameObject*)parentList->GetValue(g);
869                         if (gameObj->IsDynamic())
870                         {
871                                 //KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController();
872                                 
873 #if 0
874                                 Object* blenderObject = gameObj->GetBlenderObject();
875                                 if (blenderObject && blenderObject->ipo)
876                                 {
877                                         // XXX animato
878                                         Ipo* ipo = blenderObject->ipo;
879                                         
880                                         //create the curves, if not existing
881                                         //testhandles_ipocurve checks for NULL
882                                         testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocX"));
883                                         testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocY"));
884                                         testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocZ"));
885                                         testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotX"));
886                                         testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotY"));
887                                         testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotZ"));
888                                 }
889 #endif
890                         }
891                 }
892         }
893 }
894
895 #ifdef WITH_PYTHON
896 PyObject *KX_BlenderSceneConverter::GetPyNamespace()
897 {
898         return m_ketsjiEngine->GetPyNamespace();
899 }
900 #endif
901
902 vector<Main*> &KX_BlenderSceneConverter::GetMainDynamic()
903 {
904         return m_DynamicMaggie;
905 }
906
907 Main* KX_BlenderSceneConverter::GetMainDynamicPath(const char *path)
908 {
909         for (vector<Main*>::iterator it=m_DynamicMaggie.begin(); !(it==m_DynamicMaggie.end()); it++)
910                 if (BLI_path_cmp((*it)->name, path) == 0)
911                         return *it;
912         
913         return NULL;
914 }
915
916 bool KX_BlenderSceneConverter::LinkBlendFileMemory(void *data, int length, const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options)
917 {
918         BlendHandle *bpy_openlib = BLO_blendhandle_from_memory(data, length);
919
920         // Error checking is done in LinkBlendFile
921         return LinkBlendFile(bpy_openlib, path, group, scene_merge, err_str, options);
922 }
923
924 bool KX_BlenderSceneConverter::LinkBlendFilePath(const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options)
925 {
926         BlendHandle *bpy_openlib = BLO_blendhandle_from_file((char *)path, NULL);
927
928         // Error checking is done in LinkBlendFile
929         return LinkBlendFile(bpy_openlib, path, group, scene_merge, err_str, options);
930 }
931
932 bool KX_BlenderSceneConverter::LinkBlendFile(BlendHandle *bpy_openlib, const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options)
933 {
934         Main *main_newlib; /* stored as a dynamic 'main' until we free it */
935         Main *main_tmp= NULL; /* created only for linking, then freed */
936         LinkNode *names = NULL;
937         int idcode= BKE_idcode_from_name(group);
938         short flag= 0; /* don't need any special options */
939         ReportList reports;
940         static char err_local[255];
941         
942         /* only scene and mesh supported right now */
943         if (idcode!=ID_SCE && idcode!=ID_ME &&idcode!=ID_AC) {
944                 snprintf(err_local, sizeof(err_local), "invalid ID type given \"%s\"\n", group);
945                 *err_str= err_local;
946                 BLO_blendhandle_close(bpy_openlib);
947                 return false;
948         }
949         
950         if (GetMainDynamicPath(path)) {
951                 snprintf(err_local, sizeof(err_local), "blend file already open \"%s\"\n", path);
952                 *err_str= err_local;
953                 BLO_blendhandle_close(bpy_openlib);
954                 return false;
955         }
956
957         if (bpy_openlib==NULL) {
958                 snprintf(err_local, sizeof(err_local), "could not open blendfile \"%s\"\n", path);
959                 *err_str= err_local;
960                 return false;
961         }
962         
963         main_newlib= (Main *)MEM_callocN( sizeof(Main), "BgeMain");
964         BKE_reports_init(&reports, RPT_STORE);  
965
966         /* here appending/linking starts */
967         main_tmp = BLO_library_append_begin(main_newlib, &bpy_openlib, (char *)path);
968
969         int totnames_dummy;
970         names = BLO_blendhandle_get_datablock_names( bpy_openlib, idcode, &totnames_dummy);
971         
972         int i=0;
973         LinkNode *n= names;
974         while(n) {
975                 BLO_library_append_named_part(main_tmp, &bpy_openlib, (char *)n->link, idcode);
976                 n= (LinkNode *)n->next;
977                 i++;
978         }
979         BLI_linklist_free(names, free); /* free linklist *and* each node's data */
980         
981         BLO_library_append_end(NULL, main_tmp, &bpy_openlib, idcode, flag);
982
983         /* now do another round of linking for Scenes so all actions are properly loaded */
984         if (idcode==ID_SCE && options & LIB_LOAD_LOAD_ACTIONS) {
985                 main_tmp = BLO_library_append_begin(main_newlib, &bpy_openlib, (char *)path);
986
987                 int totnames_dummy;
988                 names = BLO_blendhandle_get_datablock_names( bpy_openlib, ID_AC, &totnames_dummy);
989         
990                 int i=0;
991                 LinkNode *n= names;
992                 while(n) {
993                         BLO_library_append_named_part(main_tmp, &bpy_openlib, (char *)n->link, ID_AC);
994                         n= (LinkNode *)n->next;
995                         i++;
996                 }
997                 BLI_linklist_free(names, free); /* free linklist *and* each node's data */
998         
999                 BLO_library_append_end(NULL, main_tmp, &bpy_openlib, ID_AC, flag);
1000         }
1001         
1002         BLO_blendhandle_close(bpy_openlib);
1003
1004         BKE_reports_clear(&reports);
1005         /* done linking */      
1006         
1007         /* needed for lookups*/
1008         GetMainDynamic().push_back(main_newlib);
1009         strncpy(main_newlib->name, path, sizeof(main_newlib->name));    
1010         
1011         
1012         if (idcode==ID_ME) {
1013                 /* Convert all new meshes into BGE meshes */
1014                 ID* mesh;
1015         
1016                 for (mesh= (ID *)main_newlib->mesh.first; mesh; mesh= (ID *)mesh->next ) {
1017                         if (options & LIB_LOAD_VERBOSE)
1018                                 printf("MeshName: %s\n", mesh->name+2);
1019                         RAS_MeshObject *meshobj = BL_ConvertMesh((Mesh *)mesh, NULL, scene_merge, this);
1020                         scene_merge->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj);
1021                 }
1022         }
1023         else if (idcode==ID_AC) {
1024                 /* Convert all actions */
1025                 ID *action;
1026
1027                 for (action= (ID *)main_newlib->action.first; action; action= (ID *)action->next) {
1028                         if (options & LIB_LOAD_VERBOSE)
1029                                 printf("ActionName: %s\n", action->name+2);
1030                         scene_merge->GetLogicManager()->RegisterActionName(action->name+2, action);
1031                 }
1032         }
1033         else if (idcode==ID_SCE) {              
1034                 /* Merge all new linked in scene into the existing one */
1035                 ID *scene;
1036                 for (scene= (ID *)main_newlib->scene.first; scene; scene= (ID *)scene->next ) {
1037                         if (options & LIB_LOAD_VERBOSE)
1038                                 printf("SceneName: %s\n", scene->name+2);
1039                         
1040                         /* merge into the base  scene */
1041                         KX_Scene* other= m_ketsjiEngine->CreateScene((Scene *)scene);
1042                         scene_merge->MergeScene(other);
1043                         
1044                         // RemoveScene(other); // Don't run this, it frees the entire scene converter data, just delete the scene
1045                         delete other;
1046                 }
1047
1048                 /* Now handle all the actions */
1049                 if (options & LIB_LOAD_LOAD_ACTIONS) {
1050                         ID *action;
1051
1052                         for (action= (ID *)main_newlib->action.first; action; action= (ID *)action->next) {
1053                                 if (options & LIB_LOAD_VERBOSE)
1054                                         printf("ActionName: %s\n", action->name+2);
1055                                 scene_merge->GetLogicManager()->RegisterActionName(action->name+2, action);
1056                         }
1057                 }
1058         }
1059         
1060         return true;
1061 }
1062
1063 /* Note m_map_*** are all ok and don't need to be freed
1064  * most are temp and NewRemoveObject frees m_map_gameobject_to_blender */
1065 bool KX_BlenderSceneConverter::FreeBlendFile(struct Main *maggie)
1066 {
1067         int maggie_index= -1;
1068         int i=0;
1069
1070         if (maggie==NULL)
1071                 return false;
1072         
1073         /* tag all false except the one we remove */
1074         for (vector<Main*>::iterator it=m_DynamicMaggie.begin(); !(it==m_DynamicMaggie.end()); it++) {
1075                 Main *main= *it;
1076                 if (main != maggie) {
1077                         tag_main(main, 0);
1078                 }
1079                 else {
1080                         maggie_index= i;
1081                 }
1082                 i++;
1083         }
1084
1085         /* should never happen but just to be safe */
1086         if (maggie_index == -1)
1087                 return false;
1088
1089         m_DynamicMaggie.erase(m_DynamicMaggie.begin() + maggie_index);
1090         tag_main(maggie, 1);
1091
1092
1093         /* free all tagged objects */
1094         KX_SceneList* scenes = m_ketsjiEngine->CurrentScenes();
1095         int numScenes = scenes->size();
1096
1097
1098         for (int scene_idx=0;scene_idx<numScenes;scene_idx++)
1099         {
1100                 KX_Scene* scene = scenes->at(scene_idx);
1101                 if (IS_TAGGED(scene->GetBlenderScene())) {
1102                         RemoveScene(scene); // XXX - not tested yet
1103                         scene_idx--;
1104                         numScenes--;
1105                 }
1106                 else {
1107                         
1108                         /* in case the mesh might be refered to later */
1109                         {
1110                                 CTR_Map<STR_HashedString,void*> &mapStringToMeshes = scene->GetLogicManager()->GetMeshMap();
1111                                 
1112                                 for (int i=0; i<mapStringToMeshes.size(); i++)
1113                                 {
1114                                         RAS_MeshObject *meshobj= (RAS_MeshObject *) *mapStringToMeshes.at(i);
1115                                         if (meshobj && IS_TAGGED(meshobj->GetMesh()))
1116                                         {       
1117                                                 STR_HashedString mn = meshobj->GetName();
1118                                                 mapStringToMeshes.remove(mn);
1119                                                 m_map_mesh_to_gamemesh.remove(CHashedPtr(meshobj->GetMesh()));
1120                                                 i--;
1121                                         }
1122                                 }
1123                         }
1124
1125                         /* Now unregister actions */
1126                         {
1127                                 CTR_Map<STR_HashedString,void*> &mapStringToActions = scene->GetLogicManager()->GetActionMap();
1128
1129                                 for (int i=0; i<mapStringToActions.size(); i++)
1130                                 {
1131                                         ID *action= (ID*) *mapStringToActions.at(i);
1132
1133                                         if (IS_TAGGED(action))
1134                                         {
1135                                                 STR_HashedString an = action->name+2;
1136                                                 mapStringToActions.remove(an);
1137                                                 i--;
1138                                         }
1139                                 }
1140                         }
1141                         
1142                         //scene->FreeTagged(); /* removed tagged objects and meshes*/
1143                         CListValue *obj_lists[] = {scene->GetObjectList(), scene->GetInactiveList(), NULL};
1144
1145                         for (int ob_ls_idx=0; obj_lists[ob_ls_idx]; ob_ls_idx++)
1146                         {
1147                                 CListValue *obs= obj_lists[ob_ls_idx];
1148                                 RAS_MeshObject* mesh;
1149
1150                                 for (int ob_idx = 0; ob_idx < obs->GetCount(); ob_idx++)
1151                                 {
1152                                         KX_GameObject* gameobj = (KX_GameObject*)obs->GetValue(ob_idx);
1153                                         if (IS_TAGGED(gameobj->GetBlenderObject())) {
1154
1155                                                 int size_before = obs->GetCount();
1156
1157                                                 /* Eventually calls RemoveNodeDestructObject
1158                                                  * frees m_map_gameobject_to_blender from UnregisterGameObject */
1159                                                 scene->RemoveObject(gameobj);
1160
1161                                                 if (size_before != obs->GetCount())
1162                                                         ob_idx--;
1163                                                 else {
1164                                                         printf("ERROR COULD NOT REMOVE \"%s\"\n", gameobj->GetName().ReadPtr());
1165                                                 }
1166                                         }
1167                                         else {
1168                                                 /* free the mesh, we could be referecing a linked one! */
1169                                                 int mesh_index= gameobj->GetMeshCount();
1170                                                 while(mesh_index--) {
1171                                                         mesh= gameobj->GetMesh(mesh_index);
1172                                                         if (IS_TAGGED(mesh->GetMesh())) {
1173                                                                 gameobj->RemoveMeshes(); /* XXX - slack, should only remove meshes that are library items but mostly objects only have 1 mesh */
1174                                                                 break;
1175                                                         }
1176                                                 }
1177
1178                                                 /* make sure action actuators are not referencing tagged actions */
1179                                                 for (unsigned int act_idx=0; act_idx<gameobj->GetActuators().size(); act_idx++)
1180                                                 {
1181                                                         if (gameobj->GetActuators()[act_idx]->IsType(SCA_IActuator::KX_ACT_ACTION))
1182                                                         {
1183                                                                 BL_ActionActuator *act = (BL_ActionActuator*)gameobj->GetActuators()[act_idx];
1184                                                                 if (IS_TAGGED(act->GetAction()))
1185                                                                         act->SetAction(NULL);
1186                                                         }
1187                                                 }
1188                                         }
1189                                 }
1190                         }
1191                 }
1192         }
1193
1194
1195         int size;
1196
1197         // delete the entities of this scene
1198         /* TODO - */
1199 #if 0
1200         vector<pair<KX_Scene*,KX_WorldInfo*> >::iterator worldit;
1201         size = m_worldinfos.size();
1202         for (i=0, worldit=m_worldinfos.begin(); i<size; ) {
1203                 if ((*worldit).second) {
1204                         delete (*worldit).second;
1205                         *worldit = m_worldinfos.back();
1206                         m_worldinfos.pop_back();
1207                         size--;
1208                 } else {
1209                         i++;
1210                         worldit++;
1211                 }
1212         }
1213 #endif
1214
1215
1216         /* Worlds don't reference original blender data so we need to make a set from them */
1217         typedef std::set<KX_WorldInfo*> KX_WorldInfoSet;
1218         KX_WorldInfoSet worldset;
1219         for (int scene_idx=0;scene_idx<numScenes;scene_idx++)
1220         {
1221                 KX_Scene* scene = scenes->at(scene_idx);
1222                 if (scene->GetWorldInfo())
1223                         worldset.insert( scene->GetWorldInfo() );
1224         }
1225
1226         vector<pair<KX_Scene*,KX_WorldInfo*> >::iterator worldit;
1227         size = m_worldinfos.size();
1228         for (i=0, worldit=m_worldinfos.begin(); i<size; ) {
1229                 if ((*worldit).second && (worldset.count((*worldit).second)) == 0) {
1230                         delete (*worldit).second;
1231                         *worldit = m_worldinfos.back();
1232                         m_worldinfos.pop_back();
1233                         size--;
1234                 } else {
1235                         i++;
1236                         worldit++;
1237                 }
1238         }
1239         worldset.clear();
1240         /* done freeing the worlds */
1241
1242
1243
1244
1245         vector<pair<KX_Scene*,RAS_IPolyMaterial*> >::iterator polymit;
1246         size = m_polymaterials.size();
1247
1248
1249
1250         for (i=0, polymit=m_polymaterials.begin(); i<size; ) {
1251                 RAS_IPolyMaterial *mat= (*polymit).second;
1252                 Material *bmat= NULL;
1253
1254                 /* Why do we need to check for RAS_BLENDERMAT if both are cast to a (PyObject*)? - Campbell */
1255                 if (mat->GetFlag() & RAS_BLENDERMAT) {
1256                         KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(mat);
1257                         bmat= bl_mat->GetBlenderMaterial();
1258
1259                 } else {
1260                         KX_PolygonMaterial *kx_mat = static_cast<KX_PolygonMaterial*>(mat);
1261                         bmat= kx_mat->GetBlenderMaterial();
1262                 }
1263
1264                 if (IS_TAGGED(bmat)) {
1265                         /* only remove from bucket */
1266                         ((*polymit).first)->GetBucketManager()->RemoveMaterial(mat);
1267                 }
1268
1269                 i++;
1270                 polymit++;
1271         }
1272
1273
1274
1275         for (i=0, polymit=m_polymaterials.begin(); i<size; ) {
1276                 RAS_IPolyMaterial *mat= (*polymit).second;
1277                 Material *bmat= NULL;
1278
1279                 /* Why do we need to check for RAS_BLENDERMAT if both are cast to a (PyObject*)? - Campbell */
1280                 if (mat->GetFlag() & RAS_BLENDERMAT) {
1281                         KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(mat);
1282                         bmat= bl_mat->GetBlenderMaterial();
1283
1284                 } else {
1285                         KX_PolygonMaterial *kx_mat = static_cast<KX_PolygonMaterial*>(mat);
1286                         bmat= kx_mat->GetBlenderMaterial();
1287                 }
1288
1289                 if (bmat) {
1290                         //printf("FOUND MAT '%s' !!! ", ((ID*)bmat)->name+2);
1291                 }
1292                 else {
1293                         //printf("LOST MAT  !!!");
1294                 }
1295
1296                 if (IS_TAGGED(bmat)) {
1297
1298                         delete (*polymit).second;
1299                         *polymit = m_polymaterials.back();
1300                         m_polymaterials.pop_back();
1301                         size--;
1302                         //printf("tagged !\n");
1303                 } else {
1304                         i++;
1305                         polymit++;
1306                         //printf("(un)tagged !\n");
1307                 }
1308         }
1309
1310         vector<pair<KX_Scene*,BL_Material*> >::iterator matit;
1311         size = m_materials.size();
1312         for (i=0, matit=m_materials.begin(); i<size; ) {
1313                 BL_Material *mat= (*matit).second;
1314                 if (IS_TAGGED(mat->material)) {
1315                         delete (*matit).second;
1316                         *matit = m_materials.back();
1317                         m_materials.pop_back();
1318                         size--;
1319                 } else {
1320                         i++;
1321                         matit++;
1322                 }
1323         }
1324
1325         vector<pair<KX_Scene*,RAS_MeshObject*> >::iterator meshit;
1326         size = m_meshobjects.size();
1327         for (i=0, meshit=m_meshobjects.begin(); i<size; ) {
1328                 RAS_MeshObject *me= (*meshit).second;
1329                 if (IS_TAGGED(me->GetMesh())) {
1330                         delete (*meshit).second;
1331                         *meshit = m_meshobjects.back();
1332                         m_meshobjects.pop_back();
1333                         size--;
1334                 } else {
1335                         i++;
1336                         meshit++;
1337                 }
1338         }
1339
1340         free_main(maggie);
1341
1342         return true;
1343 }
1344
1345 bool KX_BlenderSceneConverter::FreeBlendFile(const char *path)
1346 {
1347         return FreeBlendFile(GetMainDynamicPath(path));
1348 }
1349
1350 bool KX_BlenderSceneConverter::MergeScene(KX_Scene *to, KX_Scene *from)
1351 {
1352
1353         {
1354                 vector<pair<KX_Scene*,KX_WorldInfo*> >::iterator itp = m_worldinfos.begin();
1355                 while (itp != m_worldinfos.end()) {
1356                         if ((*itp).first==from)
1357                                 (*itp).first= to;
1358                         itp++;
1359                 }
1360         }
1361
1362         {
1363                 vector<pair<KX_Scene*,RAS_IPolyMaterial*> >::iterator itp = m_polymaterials.begin();
1364                 while (itp != m_polymaterials.end()) {
1365                         if ((*itp).first==from) {
1366                                 (*itp).first= to;
1367
1368                                 /* also switch internal data */
1369                                 RAS_IPolyMaterial*mat= (*itp).second;
1370                                 mat->Replace_IScene(to);
1371                         }
1372                         itp++;
1373                 }
1374         }
1375
1376         {
1377                 vector<pair<KX_Scene*,RAS_MeshObject*> >::iterator itp = m_meshobjects.begin();
1378                 while (itp != m_meshobjects.end()) {
1379                         if ((*itp).first==from)
1380                                 (*itp).first= to;
1381                         itp++;
1382                 }
1383         }
1384
1385         {
1386                 vector<pair<KX_Scene*,BL_Material*> >::iterator itp = m_materials.begin();
1387                 while (itp != m_materials.end()) {
1388                         if ((*itp).first==from)
1389                                 (*itp).first= to;
1390                         itp++;
1391                 }
1392         }
1393         
1394         return true;
1395 }
1396
1397 /* This function merges a mesh from the current scene into another main
1398  * it does not convert */
1399 RAS_MeshObject *KX_BlenderSceneConverter::ConvertMeshSpecial(KX_Scene* kx_scene, Main *maggie, const char *name)
1400 {
1401         /* Find a mesh in the current main */
1402         ID *me= static_cast<ID *>(BLI_findstring(&m_maggie->mesh, name, offsetof(ID, name) + 2));
1403         
1404         if (me==NULL) {
1405                 printf("Could not be found \"%s\"\n", name);
1406                 return NULL;
1407         }
1408         
1409         /* Watch this!, if its used in the original scene can cause big troubles */
1410         if (me->us > 0) {
1411                 printf("Mesh has a user \"%s\"\n", name);
1412                 me = (ID*)BKE_mesh_copy((Mesh*)me);
1413                 me->us--;
1414         }
1415         BLI_remlink(&m_maggie->mesh, me); /* even if we made the copy it needs to be removed */
1416         BLI_addtail(&maggie->mesh, me);
1417
1418         
1419         /* Must copy the materials this uses else we cant free them */
1420         {
1421                 Mesh *mesh= (Mesh *)me;
1422                 
1423                 /* ensure all materials are tagged */
1424                 for (int i=0; i<mesh->totcol; i++)
1425                         if (mesh->mat[i])
1426                                 mesh->mat[i]->id.flag &= ~LIB_DOIT;
1427                 
1428                 for (int i=0; i<mesh->totcol; i++)
1429                 {
1430                         Material *mat_old= mesh->mat[i];
1431                         
1432                         /* if its tagged its a replaced material */
1433                         if (mat_old && (mat_old->id.flag & LIB_DOIT)==0)
1434                         {
1435                                 Material *mat_old= mesh->mat[i];
1436                                 Material *mat_new= BKE_material_copy( mat_old );
1437                                 
1438                                 mat_new->id.flag |= LIB_DOIT;
1439                                 mat_old->id.us--;
1440                                 
1441                                 BLI_remlink(&m_maggie->mat, mat_new);
1442                                 BLI_addtail(&maggie->mat, mat_new);
1443                                 
1444                                 mesh->mat[i]= mat_new;
1445                                 
1446                                 /* the same material may be used twice */
1447                                 for (int j=i+1; j<mesh->totcol; j++)
1448                                 {
1449                                         if (mesh->mat[j]==mat_old)
1450                                         {
1451                                                 mesh->mat[j]= mat_new;
1452                                                 mat_new->id.us++;
1453                                                 mat_old->id.us--;
1454                                         }
1455                                 }
1456                         }
1457                 }
1458         }
1459         
1460         RAS_MeshObject *meshobj = BL_ConvertMesh((Mesh *)me, NULL, kx_scene, this);
1461         kx_scene->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj);
1462         m_map_mesh_to_gamemesh.clear(); /* This is at runtime so no need to keep this, BL_ConvertMesh adds */
1463         return meshobj;
1464 }